Exemple #1
0
 def get_project(self):
     """
     Get all the Project issues held in Jira.
     :raise Exception: Response status code is not 200 ok
     :return: a Request response.
     """
     response = requests.get("{}/rest/api/2/project".format(self.url),
                             headers=self.header())
     if response.status_code != 200:
         log.error("Getting project cast an error {}".format(response.text))
         raise Exception("Getting project cast an error {}".format(
             response.text))
     else:
         return {
             "status_code": response.status_code,
             "content": JiraIssue.sanitize(content=response.content)
         }
Exemple #2
0
 def get_jira_test(self, jira_id=None):
     # get the test case from JIRA from a jira_id (ex: PFWES-5336)
     assert jira_id is not None, "Impossible to get jira issue: {}".format(
         jira_id)
     log.debug("## Get jira: {}".format(jira_id))
     jira_test_json = self.__connection.get_issue(jira_id)
     jira_test = 0
     if jira_test_json.status_code != 200:  # if we can't get the test
         log.error(
             "Connection to JIRA impossible. Check url, login/password - HTTP: {}"
             .format(jira_test_json.status_code))
         log.debug(jira_test_json.content)
         quit(1)
     else:
         jira_test = JiraIssue.sanitize(jira_test_json.content)
         log.debug('jira {}\n{}'.format(jira_id, jira_test))
         # check if jira's ID is a test case
         if jira_test["fields"]["issuetype"]['name'] != 'Test':
             log.error("{} is not a test case!".format(jira_id))
             quit(2)
     return jira_test
    def __add_execution_to_report(url=None,
                                  headers=None,
                                  test_execution_key=None,
                                  new_report_sheet=None,
                                  folder=None,
                                  relative_folder=None):
        # this function add lines in test execution's sheet

        test_execution = JiraIssue.search(
            url=url,
            headers=headers,
            search_request={
                "jql": 'issuekey="{}"'.format(test_execution_key),  # noqa
                "fields": ["key", "summary", "description"]
            })  # noqa

        # header definition
        new_report_sheet.merge_range(
            1, 1, 1, 5,
            test_execution.json()["issues"][0]["fields"]["summary"])
        new_report_sheet.write_string('A2', 'Test execution:')

        # get test data
        tests = XRayIssues.get_tests_in_execution(
            url=url, headers=headers, test_execution_key=test_execution_key)
        evidences = JiraIssue.sanitize(content=tests.content)
        evidences = {item["key"]: item for item in evidences}

        current_row = 4
        log.debug("{} data: \n{}".format(test_execution_key, tests.json()))
        log.debug("Evidences {} data: \n{}".format(test_execution_key,
                                                   evidences))

        for index, test in enumerate(tests.json()):
            #  Create the download folder
            os.makedirs(os.path.join(folder, test["key"]))
            #  Get steps or scenarios
            steps = JiraIssue.search(url=url,
                                     headers=headers,
                                     search_request={
                                         "jql":
                                         'issuekey="{}"'.format(test["key"]),
                                         "fields": [
                                             "key", "customfield_10204",
                                             "customfield_10206", "summary",
                                             "issuelinks"
                                         ]
                                     })
            steps = JiraIssue.sanitize(content=steps.content)
            # log.info("step {} data:\n[{}".format(test["key"], steps))

            story_key = ''
            story_name = ''
            # try to catch story attached to the test
            try:
                # these fields doesn't exist for Release level, only for test plan / exec level
                short_link = steps["issues"][0]["fields"]["issuelinks"][
                    0]  # to ease readability
                story_key = short_link["inwardIssue"]["key"]
                story_name = short_link["inwardIssue"]["fields"]["summary"]
            except (KeyError, IndexError):
                try:
                    # on old version, field use outward instead of inward
                    short_link = steps["issues"][0]["fields"]["issuelinks"][
                        0]  # ease readability

                    log.debug("step {} data:\n{}".format(
                        test["key"], short_link["outwardIssue"]["key"]))
                    story_key = short_link["outwardIssue"]["key"]
                    story_name = short_link["outwardIssue"]["fields"][
                        "summary"]
                except (KeyError, IndexError):
                    log.warning("There is no story / improvement attached to"
                                " test {}".format(test["key"]))

            if steps["issues"][0]["fields"]["customfield_10204"] is not None:
                steps_list = [
                    steps["issues"][0]["fields"]["customfield_10204"]
                ]
            else:
                steps_list = [
                    item["step"] for item in steps["issues"][0]["fields"]
                    ["customfield_10206"]["steps"]
                ]

            file_list = evidences[test["key"]]["evidences"]
            defect_list = evidences[test["key"]]["defects"]

            lines_to_write = max(
                (len(steps_list), len(file_list), len(defect_list)))
            for step_index, step in enumerate(steps_list):
                new_report_sheet.write_string(current_row + step_index, 6,
                                              step)
            for evidence_index, evidence in enumerate(file_list):
                file_name = evidence["fileName"]
                JiraAttachments.download_file(url=evidence["fileURL"],
                                              headers=headers,
                                              file_absolute_path=os.path.join(
                                                  folder, test["key"],
                                                  file_name))
                new_report_sheet.write_url(current_row + evidence_index,
                                           7,
                                           os.path.join(
                                               relative_folder, test["key"],
                                               file_name),
                                           string=file_name)
            # set jira's ID url
            new_report_sheet.write_url(current_row,
                                       3,
                                       "{}/browse/{}".format(url, test["key"]),
                                       string=test["key"])  # Test ID
            if story_key != '':
                new_report_sheet.write_url(current_row,
                                           1,
                                           "{}/browse/{}".format(
                                               url, story_key),
                                           string=story_key)  # US ID
            new_report_sheet.write_string(current_row, 2,
                                          story_name)  # US name

            # merge rows when result is on multi lines
            if lines_to_write > 1:
                # set values and merge rows
                new_report_sheet.merge_range(
                    current_row, 4, current_row + lines_to_write - 1, 4,
                    steps["issues"][0]["fields"]["summary"])
                new_report_sheet.merge_range(current_row, 5,
                                             current_row + lines_to_write - 1,
                                             5, test["status"])
                # value already set, only merge rows
                new_report_sheet.merge_range(
                    current_row, 1, current_row + lines_to_write - 1, 1,
                    story_key)  # US ID field  # todo improve format
                new_report_sheet.merge_range(current_row, 2,
                                             current_row + lines_to_write - 1,
                                             2, None)  # US title field
                new_report_sheet.merge_range(
                    current_row, 3, current_row + lines_to_write - 1, 3,
                    test["key"])  # Test ID   # todo improve format
                new_report_sheet.merge_range(current_row, 6,
                                             current_row + lines_to_write - 1,
                                             6, None)  # Step field
            else:
                new_report_sheet.write_string(current_row, 1,
                                              story_key)  # todo improve format
                new_report_sheet.write_string(
                    current_row, 3, test["key"])  # todo improve format
                new_report_sheet.write_string(
                    current_row, 4, steps["issues"][0]["fields"]["summary"])
                new_report_sheet.write_string(current_row, 5, test["status"])

            current_row = current_row + lines_to_write
Exemple #4
0
    def update_jira_test(self, jira_id=None, jira_changes=None):
        # Update the test case from Jira with feature file data
        # jira_id = jira's id who will be updated
        # jira_changes = list of all changes
        assert jira_id is not None, "There is no jira_id to change"
        assert jira_changes is not None, "There is no change for jira_id{}".format(
            jira_id)

        results = {
            jira_id: {}
        }  # build a json for results = { jira_id: {"field1": "204 OK"}}

        # Split jira_changes to manage each field individually
        for field in jira_changes:
            log.debug("{} - jira_change[field]: {}".format(
                type(jira_changes[field]), jira_changes[field]))
            value = str(jira_changes[field])
            if field == mapping_feature_jira['story_tags']:
                # manage linked issue field
                my_result = self.__connection.create_link(from_key=jira_id,
                                                          to_key=value,
                                                          link_type='Tests')
            else:
                log.debug("field ---> {}".format(field))
                if field == mapping_feature_jira['labels']:
                    # Manage labels field
                    change = []
                    # update labels and remove unexpected labels
                    for action, data in jira_changes[field].items():
                        for tag in data:
                            change.append({action: tag})
                        value = change
                elif field == mapping_feature_jira['type']:
                    # manage case for field = type (scenario type)
                    value = [{"set": {"value": value}}]
                else:
                    # manage other fields than "label" "type" & "story tags"
                    value = [{"set": value}]

                field = field.replace('fields/', 'update/')
                log.debug('field: {} - value: \n\t{}\n'.format(field, value))
                json_data = {}
                dpath.util.new(json_data, field, value)
                log.debug("json_data: {}".format(json_data))
                # Update jira issue change by change
                my_result = self.__connection.update_issue(jira_id, json_data)

            # Manage return message of the issue's update
            if not (my_result.status_code == 204
                    or my_result.status_code == 201):
                # when error return ERROR messages
                log.warning("HTTP:{} - Error to update field: {}\n\t{}".format(
                    my_result.status_code,
                    field,  # noqa
                    JiraIssue.sanitize(my_result.content)))  # noqa
            else:
                # when not error return INFO messages
                log.info("HTTP:{} - Field: {} updated successfully".format(
                    my_result.status_code, field))

            results[jira_id][field] = my_result  # save result for this field
        # loop end
        return results