def mark_for_deletion(tc, tag): if tag in tc.title: wi = TestCase(uri=tc.uri) wi.title = "stoner-DeleteMe" try: wi.update() print "Changed {} title from {} to {}".format(wi.work_item_id, tc.title, wi.title) except: print "Failed to change {}".format(wi.work_item_id)
def add_colon_tc(tc): parts = tc.title.split() if ":" not in tc.title: newtitle = parts[0] + " : " + parts[1] wi = TestCase(uri=tc.uri) wi.title = newtitle try: wi.update() print "Changed title to {}".format(newtitle) except: print "Failed to update {}".format(wi.title)
def test_013_incident_report_test(self): """This test does the following: * gets a TestRun * gets a TestCase * adds test_steps * creates a TestRecord * populates the TestRecord * Fail the testRecord * reloads the TestCase * Verifies that an Incident Report was Created """ tr = TestRun(project_id=DEFAULT_PROJ, test_run_id=TEST_RUN_ID) tests = [["Test 1", "Result 1"], ["Test 2", "Result 2"], ["Test 3", "Result 3"]] set_steps = [] for test in tests: ts = TestStep() ts.values = test set_steps.append(ts) tc = TestCase(work_item_id=self.NEW_TEST_CASE) tc.set_test_steps(set_steps) tc.update() tc.reload() steps = tc.test_steps.steps results = [] for step in steps: res = TestStepResult() res.result = "failed" res.comment = "This is the result" results.append(res) rec = TestRecord() rec.test_step_results = results rec.test_case_id = self.NEW_TEST_CASE rec.comment = "Incident Report was Created" rec.duration = "50.5" rec.result = "failed" rec.executed_by = tr.logged_in_user_id rec.executed = datetime.datetime.now() tr.update_test_record_by_object(self.NEW_TEST_CASE, rec) tc.reload() linked_work_items = tc.linked_work_items_derived idx = len(linked_work_items) - 1 incident = Incident(project_id="proj1", work_item_id=linked_work_items[idx].work_item_id) self.assertIsNotNone(incident)
def remove_linked_requirements_from_tests(test_cases): """ Removes all linked Items from TestCase objects in test_Cases :param test_cases: :return: """ with open("/tmp/tc_delete.txt", "w") as tcd: for tc in test_cases: tc = TestCase(uri=tc.uri) linked_items = tc.linked_work_items for li in linked_items: tc.remove_linked_item(li.work_item_id, "verifies") tc.title = "DeleteMe" if tc.author == "ci-user": tc.author = "stoner" tcd.write(tc.work_item_id + "\n") tcd.flush() tc.update()
def fix_tc_title(tc): """ Need to add RHSM-TC : prefix to the existing testcases :param tc: :return: """ if tc.title.startswith("RHSM-TC : "): print "TestCase already starts with RHSM-TC : " return newtitle = "RHSM-TC : " + tc.title wi = TestCase(uri=tc.uri) wi.title = newtitle try: wi.update() print "Changed {} title to {}".format(wi.work_item_id, newtitle) except: print "Failed to update {}".format(wi.title)
def test_case(path, collect_only, project): """Sync test cases with Polarion.""" testcases = testimony.get_testcases([path]) for path, tests in testcases.items(): requirement = None for test in tests: # Expect test_case_id to be path.test_name or # path.ClassName.test_name. test_case_id_parts = [ path.replace('/', '.').replace('.py', ''), test.name ] if test.parent_class is not None: test_case_id_parts.insert(-1, test.parent_class) test_case_id = '.'.join(test_case_id_parts) if requirement is None: requirement_name = parse_requirement_name(test_case_id) results = Requirement.query('{0}'.format(requirement_name), fields=['title', 'work_item_id']) if len(results) > 0: # As currently is not possible to get a single # match for the title, make sure to not use a # not intended Requirement. for result in results: if result.title == requirement_name: requirement = result if requirement is None: click.echo( 'Creating requirement {0}.'.format(requirement_name)) if not collect_only: requirement = Requirement.create(project, requirement_name, '', reqtype='functional') results = TestCase.query(test_case_id, fields=['description', 'work_item_id']) if len(results) == 0: click.echo( 'Creating test case {0} for requirement {1}.'.format( test.name, requirement_name)) if not collect_only: test_case = TestCase.create( project, test.name, test.docstring if test.docstring else '', caseautomation='automated', casecomponent='-', caseimportance='medium', caselevel='component', caseposneg='positive', subtype1='-', test_case_id=test_case_id, testtype='functional', ) click.echo( 'Liking test case {0} to verify requirement {1}.'.format( test.name, requirement_name)) if not collect_only: test_case.add_linked_item(requirement.work_item_id, 'verifies') else: click.echo( 'Updating test case {0} for requirement {1}.'.format( test.name, requirement_name)) # Ensure that a single match for the Test Case is # returned. assert len(results) == 1 test_case = results[0] if (not collect_only and test_case.description != test.docstring): test_case = TestCase(project, test_case.work_item_id) test_case.description = (test.docstring if test.docstring else '') test_case.update()
def test_019_update(self): tc = TestCase(project_id=DEFAULT_PROJ, work_item_id=self.work_item_id) tc.status = "approved" tc.update() tc2 = TestCase(project_id=DEFAULT_PROJ, work_item_id=self.work_item_id) self.assertEqual(tc2.status, "approved")
# tc.description = "TBD" # tc.description.decode('utf-8') # tc.automation_script = "https://rhos-qe-jenkins.rhev-ci-vms.eng.rdu2.redhat.com/" # auto_test_id = tc.get_custom_field('automation-test-id').value # tc.automation_script = auto_test_id try: # tc.add_approvee('achernet') # tc.edit_approval('achernet','approved') # if tc.customerscenario == False: tc.status = 'proposed' # tc.automation_script = tc._check_encode(tc.automation_script) # tc.customerscenario = True tc.update() except StandardError: print 'Why, like this?' print "Unexpected error:", sys.exc_info()[0] # except: # print "Unexpected error:", sys.exc_info()[0] #tc.status="approved" # tc.get_custom_field('automation-test-id').value = tc._check_encode(tc.get_custom_field('automation-test-id').value) # auto_test_id = tc.get_custom_field('automation-test-id').value # print auto_test_id
def to_done(context, issue_id): '''Validate and update fields across Jira, Gerrit and Polarion using \ ADMIN_USER credentials. Args: context (dict): A dict of form {'caller': 'CALLER_NAME'} issue_id (str): Jira Issue ID for fields updation Raises: InvalidParamsError: If 'issue_id' param is missing from JSON-RPC \ request. ### Example (JSON-RPC request): {"jsonrpc": "2.0", "method":"to_done", "params": {"issue_id": "JIRA_ISSUE_ID", "id": "INTEGER/STRING"} ''' # Holds all the info required to perform below operations info_dict = {} # Jira try: issue = jira.issue(issue_id, fields='summary,comment,assignee') except JIRAError as err: raise ApiError('Jira Error', -32000, f'{err.status_code}: {err.text}') from err if issue.fields.assignee.name != context['caller']: raise ApiError('Not an assignee', -3200, 'This issue is not assigned to you') summary = issue.fields.summary info_dict['pol_id'] = summary[0:summary.find('\t')] comment = issue.fields.comment.comments[-1].body # Expects comment body as below # rb: 12345 # fn: test_function_1 test_function_2 info_dict['rb'] = re.search(r'rb: (\d+)', comment).group(0) # One polarion test may correspond to many 'test_' functions in worst case temp_fns = re.findall(r'(test_\w+)', comment) if not (info_dict['rb'] and temp_fns): raise ApiError( 'Malformed comment body', -32000, 'Comment expression ' 'should be of form: rb: 12345\nfn: test_func_1 test_func_2') # Gerrit resp = gerrit.get(f'/changes/?q={info_dict["rb"]}') if resp: info_dict['rb_status'] = resp[0]['status'] change_id = resp[0]['change_id'] info_dict['fn_path'] = [] else: raise ApiError( 'Gerrit error', -32000, f'No patch exists in Gerrit with id: {info_dict["rb"]}') # Take note of test_script and function name if it is actually merged if info_dict['rb_status'] == 'MERGED': resp = gerrit.get(f'/changes/{change_id}/revisions/current/files') for each_file in resp.keys(): # Don't store 'COMMIT_MSG' if each_file.startswith('tests'): # Read it's content for 'test_' functions file_name = each_file.replace('/', '%2F') # TODO: Is there a way to query only test functions without # reading whole file? resp = ( gerrit.get( f'/changes/{change_id}/revisions/current/files/{file_name}/content' # noqa )) if resp: # Take note of all 'test_' functions in the file all_fns = re.findall(r'def (test_\w+)', resp) for fn in all_fns: # Check 'test_' function from file matches any function # given in Jira comment and take note of the file path if fn in temp_fns: info_dict['fn_path'].append((fn, each_file)) if len(info_dict['fn_path']) != temp_fns: raise ApiError('Patch function doesn\'t exist', -32000, f'{temp_fns} doesn\'t exist in {info_dict["rb"]}') else: raise ApiError('Gerrit error', -32000, f'RB: {info_dict["rb"]} is not merged') # Polarion try: testcase = TestCase(work_item_id=info_dict['pol_id']) except Exception as excep: raise ApiError('Polarion error', -32000, str(excep)) from excep if testcase.caseautomation != 'automated': testcase.caseautomation = 'automated' setattr(testcase, 'testcase-automation_id', ' '.join(entry[0] for entry in info_dict['fn_path'])) script_path = '\n'.join( POL_MARKUP.format(entry[1]) for entry in info_dict['fn_path']) testcase.automation_script = script_path try: testcase.update() except Exception as excep: raise ApiError('Polarion error', -32000, str(excep)) from excep else: raise ApiError( 'Polarion error', -32000, f'{info_dict["id"]} is ' 'already marked as "automated" in Polarion') # Jira # Transistion to 'Done' state # Example: To get what transistions are possible for current Jira project # >>> trans = jira.transitions(issue) # >>> available = [(t['id'], t['name']) for t in trans]; print(available) # >>> [('21', 'In Progress'), ('31', 'Done'), ('51', 'To Do'), ('61', 'In # Review')] # >>> jira_state = [num[0] for num in available if num[1] == 'Done' ][0] try: jira.transition_issue(issue, '31') except JIRAError as err: raise ApiError( 'Jira Error', -32000, ('Polarion fields are updated but mark Jira manually to ' '"Done", error:' + str(err))) from err # Add JIRA comment with gathered info if update is successful body = '\n'.join( str(key) + ': ' + str(value) for key, value in info_dict.items() if key not in ('rb', 'pol_id')) body += f'\nGerrit: {ENV.GERRIT_URL}/{info_dict["rb"]}' body += f'\nPolarion: {ENV.POLARION_URL}/#/project/{ENV.POLARION_PROJECT}/workitem?id={info_dict["pol_id"]}' # noqa body += '\nGerrit status is verified and Polarion fields are updated' try: jira.add_comment(issue, body) except JIRAError as err: raise ApiError( 'Jira Error', -32000, ('Polarion and Jira fields are updated but unable to add Jira ' 'comment' + str(err))) from err return 'Gerrit fields are validated, Jira and Polarion fields are updated'
def test_case(path, collect_only, project): """Sync test cases with Polarion.""" testcases = testimony.get_testcases([path]) for path, tests in testcases.items(): requirement = None for test in tests: # Expect test_case_id to be path.test_name or # path.ClassName.test_name. test_case_id_parts = [ path.replace('/', '.').replace('.py', ''), test.name ] if test.parent_class is not None: test_case_id_parts.insert(-1, test.parent_class) test_case_id = '.'.join(test_case_id_parts) if requirement is None: requirement_name = parse_requirement_name(test_case_id) results = Requirement.query( '{0}'.format(requirement_name), fields=['title', 'work_item_id'] ) if len(results) > 0: # As currently is not possible to get a single # match for the title, make sure to not use a # not intended Requirement. for result in results: if result.title == requirement_name: requirement = result if requirement is None: click.echo( 'Creating requirement {0}.'.format(requirement_name)) if not collect_only: requirement = Requirement.create( project, requirement_name, '', reqtype='functional' ) results = TestCase.query( test_case_id, fields=['description', 'work_item_id']) if len(results) == 0: click.echo( 'Creating test case {0} for requirement {1}.' .format(test.name, requirement_name) ) if not collect_only: test_case = TestCase.create( project, test.name, test.docstring if test.docstring else '', caseautomation='automated', casecomponent='-', caseimportance='medium', caselevel='component', caseposneg='positive', subtype1='-', test_case_id=test_case_id, testtype='functional', ) click.echo( 'Liking test case {0} to verify requirement {1}.' .format(test.name, requirement_name) ) if not collect_only: test_case.add_linked_item( requirement.work_item_id, 'verifies') else: click.echo( 'Updating test case {0} for requirement {1}.' .format(test.name, requirement_name) ) # Ensure that a single match for the Test Case is # returned. assert len(results) == 1 test_case = results[0] if (not collect_only and test_case.description != test.docstring): test_case = TestCase(project, test_case.work_item_id) test_case.description = ( test.docstring if test.docstring else '') test_case.update()
def edit_tc_title(tc_, prefix): tc = TestCase(uri=tc_.uri) tc.title += prefix tc.update()