def get_jira_system_creds(datafile, system_name, list_my_info):
     """Returns a python dictionary containing key value pairs of
     requested info and their values for the provided system name from the datafile """
     if system_name is not None:
         element = xml_Utils.getElementWithTagAttribValueMatch(datafile,
                                                               'system',
                                                               'name',
                                                               system_name)
     else:
         element = xml_Utils.getElementWithTagAttribValueMatch(datafile, 'system',
                                                               'default', "true")
         if element is None:
             node_value = xml_Utils.getNodeValuebyAttribute(datafile, 'system', 'name')
             element = xml_Utils.getElementWithTagAttribValueMatch(datafile, 'system',
                                                                   'name',
                                                                   node_value)
     if element is not None and element is not False:
         output_dict = {}
         for item in list_my_info:
             output_dict[item] = xml_Utils.get_text_from_direct_child(element, item)
         return output_dict
     else:
         msg = ("There is no project with name: '{0}' in the jira config "
                "file: '{1}'".format(system_name, "Tools/jira/jira_config.xml"))
         print_warning(msg)
         return False
 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)
Exemple #3
0
def get_database_details(config_file, server_type, system_name, info_list):
    """ To get the database system details from database config file """

    system = server_type + "/system"
    if system_name is not None:
        element = xml_Utils.getElementWithTagAttribValueMatch(
            config_file, system, 'name', system_name)
    else:
        element = xml_Utils.getElementWithTagAttribValueMatch(
            config_file, system, 'default', "true")
        if element is None:
            node_value = xml_Utils.getNodeValuebyAttribute(
                config_file, system, 'name')
            element = xml_Utils.getElementWithTagAttribValueMatch(
                config_file, system, 'name', node_value)

    if element is not None and element is not False:
        output_dict = {}
        for item in info_list:
            output_dict[item] = xml_Utils.get_text_from_direct_child(
                element, item)
        return output_dict
    else:
        if system_name is not None:
            msg = "There is no system with name: '{0}' under '{1}' in " \
                  "the database config file: '{2}'".format(system_name,
                                                           server_type,
                                                           config_file)
            print_warning(msg)
        elif server_type == "dataservers":
            msg = "Value for td_system/var_system tag is not provided in " \
                  "the datafile and there is no system listed in database " \
                  "config file under dataservers block to be used as default"
            print_warning(msg)

        return False
Exemple #4
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
    def html_from_junit(self):
        """Generate html file from the junit result file
        using the html template """

        heading_row = getElementWithTagAttribValueMatch(
            self.html_root, "tr", "name", "HeadingRow")
        # get project node from junit file.
        # project_node is the root of the junit file
        project_node_list = [self.junit_root]
        for project_node in project_node_list:
            # for each project node in project_node_list create project records
            self.create_project_records(project_node)
            # for each project node in project_node_list get its testsuite node list.
            testsuite_node_list = project_node.findall("testsuite")
            for testsuite_node in testsuite_node_list:
                # for each testsuite in testsuite node list create testsuite records.
                self.create_testsuite_records(testsuite_node)
                # for each testsuite node in testsuite node list get its testcase list.
                testcase_node_list = testsuite_node.findall("testcase")
                # for each testcase in testcase node list create testcase record.
                for testcase_node in testcase_node_list:
                    self.create_testcase_record(testcase_node)
                    tc_resultsdir = testcase_node.get("resultsdir")
                    tc_logsdir = testcase_node.get("logsdir")
                    tc_name = testcase_node.get("name")
                    tc_details = {
                        "tc_resultsdir": tc_resultsdir,
                        "tc_logsdir": tc_logsdir,
                        "tc_name": tc_name
                    }
                    # for each testcase node in testcase node list get its
                    # keyword(property type = 'keyword') list.
                    kw_node_list = xml_Utils.\
                        getChildElementsListWithTagAttribValueMatch(
                         testcase_node, 'property', 'type', 'keyword')
                    # for each kw nod ein kw_node_list create kw record
                    for kw_node in kw_node_list:
                        self.create_keyword_record(kw_node,
                                                   tc_details=tc_details)
Exemple #6
0
def send_smart_cmd(connect_testdata, session_object, tag_value,
                   call_system_name, pre_tag):
    """
        The beacons of Gondor are lit
        send out the smart command
        :param connect_testdata:
            the smart testdata file that contains the smart cmd
        :param session_object:
            use this pexpect object to send out command
        :param tag_value:
            specify the testdata block of commands that get sent out
        :param call_system_name:
            in order to get passed the substitutions, a system name must be provided
        :param pre_tag:
            Distinguish if it is a connect smart action or disconnect smart action
    """
    if xml_Utils.getElementWithTagAttribValueMatch(connect_testdata,
                                                   "testdata", "title",
                                                   tag_value) is not None:
        print_info(
            "**********The following command are sent as part of the smart analysis**********"
        )
        main_log = session_object.logfile
        if pre_tag:
            smart_log = main_log.name.replace(".log", "pre_.log")
        else:
            smart_log = main_log.name.replace(".log", "post_.log")
        session_object.logfile = open(smart_log, "a")
        send_commands_from_testdata(connect_testdata,
                                    session_object,
                                    title=tag_value,
                                    system_name=call_system_name)
        session_object.logfile = main_log
        print_info("**********smart analysis finished**********")
    else:
        print_error()
    def wait_until_visibility_of_element_located(self, system_name, timeout="5",
                                                 locator=None,
                                                 locator_type=None,
                                                 browser_name="all",
                                                 element_tag=None,
                                                 element_config_file=None):
        """
        This keyword would check whether an element is present on the DOM of a
        page and visible.

        :Datafile Usage:

            Tags or attributes to be used in input datafile for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the datafile as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child of the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. timeout = This contains the information of how much time the
                         browser needs to wait for an element whose existence in
                         the DOM is unknown to become visible

                         Eg: <timeout>15</timeout>

            4. locator_type = This contains information about the type of
                              locator that you want to use. Can be 'xpath',
                              'id', 'css', 'link', 'tag','class', 'name'

            5. locator = This contains the value of the locator. Something like
                         "form", "nav-tags", "//[dh./dhh[yby]"

            6. element_config_file = This contains the location of the json
                                     file that contains information about all
                                     the elements that you require for the
                                     testcase execution
            7. element_tag = This contains the name of the element in that
                             element_config_file which you want to use

            USING LOCATOR_TYPE, LOCATOR, ELEMENT_CONFIG_FILE, AND ELEMENT_TAG
            =================================================================

            None of these arguments are mandatory BUT to search an element,
            you need to provide Warrior with some way to do it.

            a. You can either directly give values for the locator_type and
            locator. So if locator_type = name and locator = navigation-bar,
            then Warrior can search for an element with name "navigation-bar"

            b. You can give location of the element_config_file and a tag inside
            it so that Warrior can search for that tag and get the required
            information from there.

            - Now, if the locator type is given, Warrior
            will search for that locator_type in the children of that element in
            the element_config_file

            - You can also set defaults in the element_config_file, and now,
            even if the locator_type is not given, Warrior will know which
            element to find. If locator_type is given, the default will be
            overridden

            - If locator_type is not f=given, and the defaults are not
            specified, then the first element in the child list of the element
            tag would be picked.

            NOTES:
                For these four arguments to be given correctly, ONE of the
                following conditions must be satisfied.

                1. locator_type and locator must be given
                2. locator_type, element_config_file, and element_tag must be given
                3. element_config_file, and element_tag must be given

                The datafile has the first priority, then the json file, and
                then finally the testcase.

                If all arguments are passed from the same place, then, if
                locator and locator_type are given, then they would have
                priority. Otherwise, the element_config_file would be searched

                The locator_type locator, element_tag can be given the datafile
                as children of the <browser> tag, but these values would remain
                constant for that browser. It is recommended that these values
                be passed from the testcase step.

                The element_config_file typically would not change from step to
                step, so it can be passed from the data file

        :Arguments:

            1. system_name(str) = the system name.
            2. browser_name(str) = Unique name for this particular browser
            3. timeout(str) = amount of time the browser should wait
            4. locator_type(str) = type of the locator - xpath, id, etc.
            5. locator(str) = locator by which the element should be located.
            6. element_config_file(str) = location of the element config file
            7. element_tag(str) = json id of the locator that you want to use
                                  from the element config file

        :Returns:

            1. status(bool)= True / False.

        """
        arguments = locals()
        arguments.pop('self')
        status = True
        wdesc = "Browser would wait until visibility of an element known to " \
                "be is determined"
        pNote(wdesc)
        pSubStep(wdesc)
        browser_details = {}

        system = xml_Utils.getElementWithTagAttribValueMatch(self.datafile,
                                                             "system",
                                                             "name",
                                                             system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(arguments,
                                                                self.datafile,
                                                                browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None:
                current_browser = Utils.data_Utils.get_object_from_datarepository(system_name + "_" + browser_details["browser_name"])
                if not current_browser:
                    pNote("Browser of system {0} and name {1} not found in the "
                          "datarepository"
                          .format(system_name, browser_details["browser_name"]),
                          "Exception")
                    status = False
                else:
                    status = self.wait_oper_object.\
                        wait_until_visibility_of_element_located(current_browser,
                                                                 browser_details["locator_type"],
                                                                 browser_details["locator"],
                                                                 browser_details["timeout"])
            browser_details = {}
        Utils.testcase_Utils.report_substep_status(status)
        if current_browser:
            selenium_Utils.save_screenshot_onerror(status, current_browser)
        return status
    def set_implicit_wait(self, system_name, timeout, browser_name="all",
                          element_config_file=None, element_tag=None):
        """
        This keyword would permanently set the implicit wait time for given
        browser instance(s)

        :Datafile Usage:

            Tags or attributes to be used in input datafile for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the datafile as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child of the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. timeout = This contains the information of how much time the
                         browser needs to wait for any action to be performed
                         on it

                         Eg: <timeout>15</timeout>

            4. element_config_file = This <element_config_file> tag is a child
                                     of the <browser> tag in the data file. This
                                     stores the location of the element
                                     configuration file that contains all
                                     element locators.

                                  Eg: <element_config_file>
                                      ../Config_files/selenium_config.json
                                      </element_config_file>

            5. element_tag = This element_tag refers to a particular element in
                             the json fie which contains relevant information to
                             that element. If you want to use this one element
                             through out the testcase for a particular browser,
                             you can include it in the data file. If this not
                             the case, then you should create an argument tag
                             in the relevant testcase step and add the value
                             directly in the testcase step.

                             FOR DATA FILE
                             Eg: <element_tag>json_name_1</element_tag>

                             FOR TEST CASE
                             Eg: <argument name="element_tag" value="json_name_1">

        :Arguments:

            1. system_name(str) = the system name.
            2. browser_name(str) = Unique name for this particular browser
            3. timeout(str) = amount of time the browser should wait
            4. element_config_file (str) = location of the element configuration
                                           file that contains all element
                                           locators
            5. element_tag (str) = particular element in the json fie which
                                   contains relevant information to that element

        :Returns:

            1. status(bool)= True / False.

        """
        arguments = locals()
        arguments.pop('self')
        status = True
        wdesc = "This would permanently set the implicit wait time for " \
                "given browser instance(s)"
        pNote(wdesc)
        pSubStep(wdesc)
        browser_details = {}

        system = xml_Utils.getElementWithTagAttribValueMatch(self.datafile,
                                                             "system",
                                                             "name",
                                                             system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(arguments,
                                                                self.datafile,
                                                                browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None:
                current_browser = Utils.data_Utils.get_object_from_datarepository(system_name + "_" + browser_details["browser_name"])
                if not current_browser:
                    pNote("Browser of system {0} and name {1} not found in the "
                          "datarepository"
                          .format(system_name, browser_details["browser_name"]),
                          "Exception")
                    status = False
                else:
                    self.wait_oper_object.\
                        implicit_wait(current_browser,
                                      browser_details["timeout"])
            browser_details = {}
        Utils.testcase_Utils.report_substep_status(status)
        if current_browser:
            selenium_Utils.save_screenshot_onerror(status, current_browser)
        return status
    def update_jira_issue(self, jiraid, status):
        """
        Update the jira issue using the jiraid
        Transition to correct issue status based on warrior status
        :Arguments:
            1. jiraid(str) - Jira issue ID
            2. status(str/boolean) - warrior execution status
        :Returns:
            1. oper_status(Boolean) - True/False
        """

        print_info("Updating the status of the Jira issue '{0}'".format(jiraid))
        issue_type = self.get_jira_issue_type(jiraid)
        if not issue_type:
            # when failed to get the type of the Jira issue
            return False

        oper_status = False
        status_map = {"true": "pass", "false": "fail"}
        status = status_map[str(status).lower()] if str(status).lower() in \
            status_map else str(status).lower()

        # Find the correct jira system from the jira_config.xml
        if self.jiraproj is not None:
            jiraproj = self.jiraproj
            sys_elem = xml_Utils.getElementWithTagAttribValueMatch(self.jira_template_xml,
                                                                   'system', 'name', jiraproj)
        else:
            jiraproj = "default"
            sys_elem = xml_Utils.getElementWithTagAttribValueMatch(self.jira_template_xml,
                                                                   'system', jiraproj, "true")

        # Find the correct issue type and status
        if sys_elem is not None and sys_elem is not False:
            sys_data = xml_Utils.get_children_as_dict(sys_elem)

            type_matched = None
            for t in sys_data["issue_type"]:
                if t["type"] == [issue_type]:
                    type_matched = t
                    break
            if type_matched is None:
                for t in sys_data["issue_type"]:
                    if t["type"] == ["default"]:
                        type_matched = t

            if type_matched is not None and status in type_matched.keys():
                # Change the jira issue status
                if type_matched[status][0]:
                    to_status = type_matched[status][0].lower()
                    oper_status = self.set_jira_issue_status(jiraid, to_status)
                else:
                    print_error("No value provided for the tag '{0}' under issue_type "
                                "'{1}' of project '{2}' in jira_config file '{3}'.".
                                format(status, issue_type, jiraproj,
                                       "Tools/jira/jira_config.xml"))
            else:
                print_error("Cannot find the correct issue type in "
                            "jira_config file, unable to update jira status")
        else:
            print_error("There is no project with name: '{0}' in the jira config "
                        "file: '{1}'".format(self.jiraproj, "Tools/jira/jira_config.xml"))

        return oper_status
    def verify_page_by_property(self,
                                system_name,
                                expected_value,
                                value_type,
                                browser_name="all",
                                element_config_file=None,
                                element_tag=None):
        """
        This keyword will verify page by property.

        :Datafile Usage:

            Tags or attributes to be used in input datafile for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the datafile as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child og the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. url = The URL that you want to open your browser to can be added
                     in the <url> tag under the <browser> tag.

                     Eg: <url>https://www.google.com</url>

            4. expected_value = This <expected_value> tag is a child og the
                                <browser> tag in the data file. This tag would
                                contain the the value you expect the browser to
                                have. This can be either a  url, page title,
                                page source, or page name

                    Eg: <expected_value>http://www.google.com</expected_value>

            5. value_type = This <value_type> tag is a child of the <browser>
                            tag in the data file. This tag would contain the
                            type of browser information that you want to verify.
                            It can either be current_url, title, name, or
                            page_source

                            Eg: <value_type>title</value_type>

            6. element_config_file = This <element_config_file> tag is a child
                                     of the <browser> tag in the data file. This
                                     stores the location of the element
                                     configuration file that contains all
                                     element locators.

                                  Eg: <element_config_file>
                                      ../Config_files/selenium_config.json
                                      </element_config_file>

            7. element_tag = This element_tag refers to a particular element in
                             the json fie which contains relevant information to
                             that element. If you want to use this one element
                             through out the testcase for a particular browser,
                             you can include it in the data file. If this not
                             the case, then you should create an argument tag
                             in the relevant testcase step and add the value
                             directly in the testcase step.

                             FOR DATA FILE
                             Eg: <element_tag>json_name_1</element_tag>

                             FOR TEST CASE
                             Eg: <argument name="element_tag" value="json_name_1">

        :Arguments:

            1. system_name(str) = the system name.
            2. expected_value (str) = The expected value of the information
                                      retrieved from the web page.
            3. value_type (str) = Type of page information that you wat to
                                  verify: current_url, name, title, or
                                  page_source
            4. browser_name(str) = Unique name for this particular browser
            5. url(str) = URL to which the browser should be directed
            6. element_config_file (str) = location of the element configuration
                                           file that contains all element
                                           locators
            7. element_tag (str) = particular element in the json fie which
                                   contains relevant information to that element

        :Returns:

            1. status(bool)= True / False.

        """
        arguments = locals()
        arguments.pop('self')
        status = True
        wdesc = "The browser will verify page by {0}".format(value_type)
        pNote(wdesc)
        pSubStep(wdesc)
        browser_details = {}

        system = xml_Utils.getElementWithTagAttribValueMatch(
            self.datafile, "system", "name", system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(
                arguments, self.datafile, browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None:
                current_browser = Utils.data_Utils.get_object_from_datarepository(
                    system_name + "_" + browser_details["browser_name"])
                if current_browser:
                    obtained_value = self.verify_oper_object.get_page_property(
                        current_browser, browser_details["value_type"])
                    if str(obtained_value) == expected_value:
                        pNote("The obtained {0}: {1} matches the expected "
                              "value: {2}. Verification success!".format(
                                  value_type, obtained_value, expected_value))
                    else:
                        pNote(
                            "The obtained {0}: {1} does not match the "
                            "expected value: {2}. Verification failed!".format(
                                value_type, obtained_value, expected_value),
                            "Error")
                        status = False
                else:
                    pNote(
                        "Browser of system {0} and name {1} not found in the "
                        "datarepository".format(
                            system_name, browser_details["browser_name"]),
                        "Exception")
                    status = False
            browser_details = {}
        Utils.testcase_Utils.report_substep_status(status)
        if current_browser:
            selenium_Utils.save_screenshot_onerror(status, current_browser)
        return status
    def verify_text_in_window_pane(self,
                                   system_name,
                                   verification_text=None,
                                   browser_name='all',
                                   element_config_file=None,
                                   element_tag=None):
        """
        This keyword is to verify whether the user provided texts exist on the web page

        :Datafile Usage:

            Tags or attributes to be used in input data file for the system or
            subsystem. If both tag and attribute is provided the attribute will
            be used.

            1. system_name = This attribute can be specified in the data file as
                             a <system> tag directly under the <credentials>
                             tag. An attribute "name" has to be added to this
                             tag and the value of that attribute would be taken
                             in as value to this keyword attribute.

                             <system name="name_of_thy_system"/>

            2. browser_name = This <browser_name> tag is a child of the
                              <browser> tag in the data file. Each browser
                              instance should have a unique name. This name can
                              be added here

                              Eg: <browser_name>Unique_name_1</browser_name>

            3. verification_text = text to be verified in the web page should be given as a comma separated value
                                   without any space in between, if it is multiple values
                                   Eg. <verification_text>Gmail,Google</verification_text>

            4. element_config_file = This contains the location of the json
                                     file that contains information about all
                                     the elements that you require for the
                                     test case execution

            5. element_tag = This contains the name of the element in that
                             element_config_file which you want to use

            USING NAME_OF_ELEMENT, ELEMENT_CONFIG_FILE, AND ELEMENT_TAG
            ==========================================================

            None of these arguments are mandatory BUT to search an element,
            you need to provide Warrior with some way to do it.

            a. You can either directly give values for the verification_text. So
            if verification_text = verification_text(comma seperated values), then Warrior can search 
            the given verification_text in the window pane

            b. You can give location of the element_config_file and a tag inside
            it so that Warrior can search for that tag and get the required
            information from there. Now, as this is the keyword -
            verify_text_in_window_pane, an child element of the element_tag with
            id as 'verification_text' would be searched for in the element_config_file

            NOTES:
                For these three arguments to be given correctly, ONE of the
                following conditions must be satisfied.

                1. verification_text must be given
                2. element_config_file, and element_tag must be given

                The data file has the first priority, then the json file, and
                then finally the test case.

                If name_of_element is given, then it would have priority.
                Otherwise, the element_config_file would be searched

                The name_of_element and the element_tag can be given the datafile
                as children of the <browser> tag, but these values would remain
                constant for that browser. It is recommended that these values
                be passed from the test case step.

                The element_config_file typically would not change from step to
                step, so it can be passed from the data file

        :Arguments:

            1. system_name(str) = the system name.
            2. browser_name(str) = Unique name for this particular browser
            3. verification_text = text to be verified in the webpage
            4. element_config_file(str) = location of the element config file
            5. element_tag(str) = json id of the locator that you want to use
                                  from the element config file

        :Returns:

            1. status(bool)= True / False.
        """
        arguments = locals()
        arguments.pop('self')
        status = True
        browser_details = {}
        system = xml_Utils.getElementWithTagAttribValueMatch(
            self.datafile, "system", "name", system_name)
        browser_list = system.findall("browser")
        try:
            browser_list.extend(system.find("browsers").findall("browser"))
        except AttributeError:
            pass

        if not browser_list:
            browser_list.append(1)
            browser_details = arguments

        for browser in browser_list:
            arguments = Utils.data_Utils.get_default_ecf_and_et(
                arguments, self.datafile, browser)
            if browser_details == {}:
                browser_details = selenium_Utils. \
                    get_browser_details(browser, datafile=self.datafile, **arguments)
            if browser_details is not None and browser_details[
                    "verification_text"] is not None:
                if not browser_details["verification_text"].startswith(
                        "verification_text"):
                    browser_details["verification_text"] = \
                        "verification_text=" + browser_details["verification_text"]
                current_browser = Utils.data_Utils.get_object_from_datarepository(
                    system_name + "_" + browser_details["browser_name"])
                if not current_browser:
                    pNote(
                        "Browser of system {0} and name {1} not found in the "
                        "data repository".format(
                            system_name, browser_details["browser_name"]),
                        "Exception")
                    status = False
                else:
                    element_located_status = current_browser.page_source
                    if element_located_status:
                        for values in browser_details[
                                "verification_text"].split(","):
                            if re.search("verification_text=", values):
                                values = re.sub("verification_text=", "",
                                                values)
                            verification_status = self.element_locator_obj.get_element(
                                current_browser,
                                'xpath=//*[contains(text(),"{}")]'.format(
                                    values),
                                findall='y')
                            if verification_status and len(
                                    verification_status) > 0:
                                print_info(
                                    "Verification text found {} times in the window pane"
                                    .format(len(verification_status)))
                            if not verification_status:
                                print_error(
                                    "The given string {} is not present in DOM"
                                    .format(values))
                                status = False
            else:
                print_error(
                    "Value for browser_details/verification_text is None. Provide the value"
                )
                status = False
            return status
Exemple #12
0
    def update_jira_issue(self, jiraid, status):
        """
            Update the jira issue using the jiraid
            Transition to correct issue status based on warrior status
        """
        issue_url = self.server + '/rest/api/2/issue/' + jiraid + "/transitions"
        status_map = {"true": "pass", "false": "fail"}
        status = status_map[str(status).lower()] if str(
            status).lower() in status_map else str(status).lower()

        # Build Auth information
        credential_handler = urllib2.HTTPPasswordMgrWithDefaultRealm()
        credential_handler.add_password(None, issue_url, self.username,
                                        self.password)
        auth = urllib2.HTTPBasicAuthHandler(credential_handler)
        userpassword = self.username + ":" + self.password
        password = base64.b64encode(userpassword)
        # Create an Authentication handler
        opener = urllib2.build_opener(auth)
        urllib2.install_opener(opener)
        opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))

        # Find the correct jira system
        if self.jiraproj is not None:
            element = xml_Utils.getElementWithTagAttribValueMatch(
                self.jira_template_xml, 'system', 'name', self.jiraproj)
        else:
            element = xml_Utils.getElementWithTagAttribValueMatch(
                self.jira_template_xml, 'system', 'default', "true")

        # Find the correct issue type and status
        if element is not None and element is not False:
            system_data = xml_Utils.get_children_as_dict(element)

            issue = None
            for x in system_data["issue_type"]:
                if x["type"] == ["test"]:
                    issue = x
            if issue is None:
                for x in system_data["issue_type"]:
                    if x["type"] == ["default"]:
                        issue = x

            postdata = None
            if issue is not None and status in issue.keys():
                # Get the correct transition for changing status
                headers = {"Authorization": "Basic " + password}
                request = urllib2.Request(str(issue_url), None, headers)
                handler = urllib2.urlopen(request)
                transitions = json.loads(handler.read())
                for trans in transitions["transitions"]:
                    if trans["to"]["name"].lower() == issue[status][0].lower():
                        postdata = """
                                    {
                                        "transition":{
                                            "id":""" + trans["id"] + """
                                        }
                                    }
                                    """

                if postdata is None:
                    print_info("Cannot change status to " +
                               str(issue[status][0]))
                    print_info("The available status are: " + str([
                        trans["to"]["name"]
                        for trans in transitions["transitions"]
                    ]))
                    return False
            else:
                print_error(
                    "Cannot find the correct issue type, unable to update Jira status"
                )
                return False

            # Update status
            headers = {
                "Authorization": "Basic " + password,
                "Content-Type": "application/json"
            }
            request = urllib2.Request(str(issue_url), postdata, headers)
            try:
                handler = urllib2.urlopen(request)
                if handler.getcode() == 204:
                    print_info("Successfully update issue status")
                    return True
                else:
                    print_error(
                        "Error occurs while updating issue status, error code: "
                        + str(handler.getcode()))
            except Exception as e:
                print_info("Error occurs while updating issue status")
                print_info(e)
        else:
            msg = "There is no project with name: '{0}' "\
            "in the jira config file: '{1}'".format(self.jiraproj, "Tools/Jira/jira_config.xml")
            print_warning(msg)
        return False