def __init__(self, junit_file=None):
     """ Constructor """
     self.junit_file = junit_file
     self.html_template = "{0}{1}Reporting{1}html_results_template.html"\
                          .format(Tools.__path__[0], os.sep)
     self.junit_root = xml_Utils.getRoot(self.junit_file)
     self.html_root = xml_Utils.getRoot(self.html_template)
     self.table = getElementWithTagAttribValueMatch(self.html_root, "table",
                                                    "name",
                                                    "ResultsSummaryTable")
     self.html_results_path = self._get_html_resultspath()
     self.html_results_dir = os.path.dirname(self.html_results_path)
Example #2
0
    def generate_html(self, junitObj, givenPath, is_final):
        """ build the html givenPath: added this feature in case of later down the line calling from outside junit
        file ( no actual use as of now )
        """
        if junitObj:
            self.junit_file = junitObj
            self.junit_root = xml_Utils.getRoot(self.junit_file)
        if givenPath:
            self.givenPath = givenPath

        self.set_line_objs()
        html = ''
        for item in self.lineObjs:
            html += item.html
        html = self.merge_html(html)

        if is_final is True:
            html += '<div class="complete"></div>'

        elem_file = open(self.get_path(), 'w')
        elem_file.write(html)
        elem_file.close()
        katana = katana_interface_class.KatanaInterface()
        katana.send_file(self.get_path(), '/execution/updateHtmlResult')

        if is_final is True:
            katana.end_comunication()

        self.lineObjs = []
        print_info("++++ Results Summary ++++")
        print_info("Open the Results summary file given below in a browser to "
                   "view results summary for this execution")
        print_info("Results sumary file: {0}".format(self.get_path()))
        print_info("+++++++++++++++++++++++++")
    def generate_html(self, junitObj, givenPath):
        """ build the html givenPath: added this feature in case of later down the line calling from outside junit
        file ( no actual use as of now )
        """
        if junitObj:
            self.junit_file = junitObj
            self.junit_root = xml_Utils.getRoot(self.junit_file)
        if givenPath:
            self.givenPath = givenPath

        self.set_line_objs()
        html = ''
        for item in self.lineObjs:
            html += item.html
        html = self.merge_html(html)

        elem_file = open(self.get_path(), 'w')
        elem_file.write(html)
        elem_file.close()
        self.lineObjs = []
        print_info("++++ Results Summary ++++")
        print_info("Open the Results summary file given below in a browser to "
                   "view results summary for this execution")
        print_info("Results sumary file: {0}".format(self.get_path()))
        print_info("+++++++++++++++++++++++++")
def split_kwargs_on_tag_equalto(kwargs, datafile, browser):
    """
    This function splits kwargs on tag=
    If the value is an xpath, then it follows the xpath and returns the value
    Else, if is it a singular tag name, then it searched for a tag with that
    name under the current <browser>
    """
    idf_data_dict = {}
    final_dict = {}
    for element in kwargs:
        if isinstance(kwargs[element],str) and kwargs[element] is not None and\
        kwargs[element] is not False:
            if kwargs[element].startswith("tag") and "=" in kwargs[element]:
                temp_list = kwargs[element].split("=")
                temp_var = temp_list[1]
                for i in range(2, len(temp_list)):
                    temp_var = temp_var + "=" + temp_list[i]
                temp_var = temp_var.strip()
                if "/" in temp_var:
                    root = xml_Utils.getRoot(datafile)
                    idf_data_dict[element] = root.find(temp_var).text
                else:
                    if browser.get(temp_var, None) is None:
                        if browser.find(temp_var) is not None:
                            idf_data_dict[element] = browser.find(
                                temp_var).text
                    else:
                        idf_data_dict[element] = browser.get(temp_var, None)
            else:
                final_dict[element] = kwargs[element]
        else:
            final_dict[element] = kwargs[element]

    return final_dict, idf_data_dict
Example #5
0
def get_response_file(testdatafile):
    """
        Build the response dict with response tag name and response text
    """
    from Framework.Utils.xml_Utils import getRoot, getElementListWithSpecificXpath
    tmp_list = getElementListWithSpecificXpath(testdatafile, "./global/response_file")
    response_file = tmp_list[0].text if tmp_list != [] else ""
    response_dict = {}
    cmd_specific_response_dict = {}
    if response_file != "":
        root = getRoot(response_file)
        # Parse global responses
        responses = root.find("responses")
        if responses is not None:
            for resp in responses:
                resp_name = resp.tag
                resp_text = resp.get("text", "")
                if resp_name in response_dict:
                    pNote("A response with tag name {} has been created before with value: {}"
                          "Please rename with a different tag name".\
                          format(resp_name, response_dict[resp_name]))
                else:
                    response_dict[resp_name] = resp_text
        else:
            pNote("Unable to find responses, please put all responses inside a responses tag",
                  "ERROR")
        # Parse cmd specific responses
        cmd_specific_response_dict = get_cmd_specific_response_file(root)
    else:
        pNote("Unable to retrieve response file from testdata file, please put the path in"
              " response_file tag inside global section of the testdata file", "ERROR")

    MockUtils.cli_Utils.response_dict = response_dict
    MockUtils.cli_Utils.cmd_specific_response_dict = cmd_specific_response_dict
Example #6
0
    def add_html_result_to_mongodb(self, input_xml):
        """ To add case/suite/project results as a document to MongoDB
        database collections, here collection names are case/suite/project """

        root = xml_Utils.getRoot(input_xml)
        file_type = self.get_file_type(root)
        results_dict = self.get_html_results(file_type, root)

        coll_dict = {
            'case': 'case_html_results',
            'suite': 'suite_html_results',
            'project': 'project_html_results'
        }

        collection = self.db[coll_dict.get(file_type)]

        # create a new document with _id as case/suite/project name
        if collection.find({'_id': results_dict['name']}).count() == 0:
            collection.insert({'_id': results_dict['name']})

        collection.update({'_id': results_dict['name']},
                          {'$push': {
                              'results': results_dict
                          }})
        print_info("Successfully added html results in MongoDB database")
def iron_claw_warrior_xml_files(filepath):
    """Validate Warrior xml files (Testcase/Testsuite/Project) against
    their xsd schema files """
    try:
        root = xml_Utils.getRoot(filepath)
    except ElementTree.ParseError, err:
        print_error("PARSING ERROR:{0}".format(err))
        return False
def iron_claw_warrior_xml_files(filepath):
    """Validate Warrior xml files (Testcase/Testsuite/Project) against
    their xsd schema files """
    try:
        root = xml_Utils.getRoot(filepath)
    except ElementTree.ParseError as err:
        print_error("PARSING ERROR:{0}".format(err))
        return False
    ironclaw_object = IronClaw()

    if root.tag == 'Testcase':
        result = ironclaw_object.testcase_prerun(filepath)
    if root.tag == 'TestSuite':
        result = ironclaw_object.testsuite_prerun(filepath, root)
    if root.tag == 'Project':
        result = ironclaw_object.project_prerun(filepath, root)

    return result
    def project_prerun(self, project_filepath, root):
        """Executes prerun of a project file """

        print('\n')
        print_info('+' * 40)
        print_debug("Validating Project xml")
        print_info('+' * 40)
        project_xsd_fullpath = self.xsd_dir + os.sep + 'warrior_project.xsd'
        project_status = self.xml_to_xsd_validation(project_filepath,
                                                    project_xsd_fullpath)
        if project_status:
            check_files_dict = self.check_proj_results_logsdir(
                project_filepath)
            for testsuite in root.iter('Testsuite'):
                testsuite_path_rel = testsuite_utils.get_path_from_xmlfile(
                    testsuite)
                testsuite_path = file_Utils.getAbsPath(
                    testsuite_path_rel, os.path.dirname(project_filepath))

                if os.path.isfile(testsuite_path):
                    print('\n')
                    print_info("Testsuite_path: {0}, Testsuite"\
                               "file exists...".format(testsuite_path))
                    ts_root = xml_Utils.getRoot(testsuite_path)
                    tsuite_status = self.testsuite_prerun(
                        testsuite_path, ts_root, check_files_dict)
                else:
                    print('\n')
                    tsuite_status = False
                    print_error('testsuite_path: {0},\
                                Testsuite file does not exist'.format(
                        testsuite_path))
                    print_info('SUITE STATUS: {0}'.format('FAILED'))
                project_status &= tsuite_status

        else:
            print_error("Incorrect xml format")

        time.sleep(5)
        print('\n')
        status = testcase_Utils.convertLogic(project_status)
        print_info('PROJECT STATUS: {0}ED'.format(status))

        return project_status
Example #10
0
def smart_analyze(prompt, testdatafile=None):
    """
        retrieve the correspond smart testdata file for smart cmd
        from either Tools/connection or testcase testdata file
        :param prompt:
            The string that will be analyzed in order to find the device system
        :param testdatafile:
            optional arg to provide a pre-defined device system in the test datafile
        :return:
            the smart datafile that contains the smart cmd to be sent
    """
    system_name = None

    if testdatafile is not None:
        # when the testdatafile is a dictionary - this happens only when
        # the testdatafile is taken from database server
        if isinstance(testdatafile, dict):
            db_td_obj = database_utils_class.\
             create_database_connection('dataservers', testdatafile.get('td_system'))
            root = db_td_obj.get_tdblock_as_xmlobj(testdatafile)
            db_td_obj.close_connection()
        else:
            root = xml_Utils.getRoot(testdatafile)
        system_name = data_Utils._get_global_var(root, "system_name")

    con_settings_dir = Tools.__path__[0] + os.sep + 'connection' + os.sep
    con_settings = con_settings_dir + "connect_settings.xml"

    if system_name is not None:
        sys_elem = xml_Utils.getElementWithTagAttribValueMatch(
            con_settings, "system", "name", system_name.text)
        if sys_elem is None or sys_elem.find("testdata") is None:
            return None
    else:
        system_list = xml_Utils.getElementListWithSpecificXpath(
            con_settings, "system[search_string]")
        for sys_elem in system_list:
            if sys_elem.find("search_string").text in prompt and sys_elem.find(
                    "testdata") is not None:
                return con_settings_dir + sys_elem.find("testdata").text
        return None

    return con_settings_dir + sys_elem.find("testdata").text
Example #11
0
    def add_xml_result_to_mongodb(self, input_xml):
        """ To add case xml results as a document to the MongoDB database
        collection - 'case' """

        root = xml_Utils.getRoot(input_xml)
        collection = self.db['case_xml_results']
        results_dict = self.get_details_from_case_xml_element(root)
        case_name = os.path.basename(os.path.splitext(input_xml)[0])

        # create a new document with _id as case_xml_results
        if collection.find({'_id': case_name}).count() == 0:
            collection.insert({'_id': case_name})

        collection.update({'_id': case_name},
                          {'$push': {
                              'results': results_dict
                          }})

        print_info("Successfully added case xml results in MongoDB database")
def get_robot_xml_files(input_list):
    """
    Find robot xml files from the list of files.
    :Arguments:
        1. input_list(list) - list of file names
    :Return:
        1. output_list(list) - list of robot xml files
    """

    output_list = []
    if input_list:
        for filename in input_list:
            try:
                root = xml_Utils.getRoot(filename)
                if root.tag == 'robot':
                    output_list.append(filename)
            except Exception:
                print_warning("{} is not a valid xml file".format(filename))

    return output_list
Example #13
0
    def write_live_results(self, junitObj, givenPath, is_final):
        """ build the html givenPath: added this feature in case of later down the line calling from outside junit
        file ( no actual use as of now )
        """
        if junitObj:
            self.junit_file = junitObj
            self.junit_root = xml_Utils.getRoot(self.junit_file)
        if givenPath:
            self.givenPath = givenPath

        self.set_line_objs()
        html = ''
        for item in self.lineObjs:
            html += item.html
        if is_final is True:
            #html += '<div class="complete"></div>'
            pass
        live_html_dict = data_Utils.get_object_from_datarepository(
            'live_html_dict', verbose=False)
        if live_html_dict:
            livehtmllocn = live_html_dict['livehtmllocn']
            live_html_iter = live_html_dict['iter']
            self.create_live_table(html, livehtmllocn, live_html_iter)

        html = self.merge_html(html)
        elem_file = open(self.get_path(), 'w')
        elem_file.write(html)
        elem_file.close()

        self.lineObjs = []
        if is_final is True:
            print_info("++++ Results Summary ++++")
            print_info(
                "Open the Results summary file given below in a browser to "
                "view results summary for this execution")
            print_info("Results sumary file: {0}".format(self.get_path()))
            print_info("+++++++++++++++++++++++++")
    def create_failing_kw_json(self):
        """Create a json file each failing keyword """

        status = False
        result_filename = file_Utils.getNameOnly(os.path.basename(
            self.xmlfile))
        tc_name = result_filename.split("_results")[0]
        #tc_name = file_Utils.getNameOnly(os.path.basename(self.xmlfile))
        #tree = xml_Utils.get_tree_from_file(self.xmlfile)
        tree = xml_Utils.getRoot(self.xmlfile)
        data_filepath = tree.find("Datafile").text
        failed = 0
        #get_tc_details_frm_resultxml
        keyword_list = tree.findall("Keyword")

        if len(keyword_list) == 0:
            print_error(
                'No Keywords found in resultfile of testcase {0}'.format(
                    tc_name))
            status = False
        else:
            for keyword in tree.findall("Keyword"):
                fail_list = []
                if keyword.find("KeywordStatus").text.upper() in [
                        'FAIL', 'EXCEPTION', 'ERROR'
                ]:
                    step_num = keyword.find("Step").get('step_num')
                    kw_resultfile = keyword.find("Resultfile").text
                    kw_resultfile_nameonly = file_Utils.getNameOnly(
                        os.path.basename(kw_resultfile))
                    failed += 1
                    #addd testcase details to json of failed keyowrds
                    fail_list.append({'tc_name': tc_name})
                    fail_list.append({'step_num': str(step_num)})
                    fail_list.append(
                        {'testcase_filepath': str(self.testcase_filepath)})
                    fail_list.append({'data_filepath': str(data_filepath)})
                    fail_list.append({'defectsdir': str(self.defectsdir)})
                    fail_list.append({'logsdir': str(self.logsdir)})
                    fail_list.append({'resultfile': str(self.resultfile)})
                    for node in keyword.iter():
                        text = self._get_text_forjson(node)
                        if text:
                            fail_list.append({node.tag: text})
                        else:
                            continue
                if len(fail_list) > 0:
                    json_file_name = "{0}{1}{2}_{3}.json".format(
                        self.defectsdir, os.sep, tc_name,
                        kw_resultfile_nameonly)
                    #                     json_file_name = self.defectsdir + os.sep + tc_name +\
                    #                                     '_step-'+str(step_num)+'_' + keyword.text +'.json'
                    j_file = open(json_file_name, 'w')
                    j_file.write(json.dumps(fail_list, indent=4))
                    j_file.close()
                    status = True
            if failed == 0:
                print_warning(
                    "There are no failed keywords in the testcase result xml file"
                )
                status = False
            return status
Example #15
0
 def __init__(self, junit_file=None):
     """ init function"""
     self.junit_file = junit_file
     self.html_template = "{0}{1}reporting{1}html_results_template.html" \
         .format(Tools.__path__[0], os.sep)
     self.junit_root = xml_Utils.getRoot(self.junit_file)