def check_get_datatype(filepath, datafile):
    """Check and get the datatype for testcase
    """
    data_type = xml_Utils.getChildTextbyParentTag(filepath, 'Details',
                                                  'Datatype')
    if str(datafile).upper().strip() == 'NO_DATA':
        data_type = 'CUSTOM'
        print_info('This test case will be run without any InputDataFile')

    elif data_type is None or data_type is False or \
            str(data_type).strip() == "":
        data_type = 'CUSTOM'

    elif data_type is not None and data_type is not False:
        data_type = str(data_type).strip()
        supported_values = ['iterative', 'custom', 'hybrid']
        if data_type.lower() not in supported_values:
            print_warning("unsupported value '{0}' provided for data_type,"
                          " supported values are " \
                          "'{1}' and case-insensitive".format(data_type, supported_values))
            print_info(
                "Hence using default value for data_type which is 'custom'")
            data_type = 'CUSTOM'
    return data_type
    def create_issues_from_jsonlist(self,
                                    json_file_list,
                                    result_xml_file,
                                    issue_type='Bug'):
        """Takes a list of json files as input and creates
        jira ticket for each json file"""

        issue_id_list = []
        for json_file in json_file_list:
            issue_summary, issue_description, step_num = self.get_issue_description(
                json_file)
            if issue_summary is not None:
                issue_id = self.create_jira_issue(issue_summary,
                                                  issue_description,
                                                  issue_type)
                self.update_issue_in_resultxml(result_xml_file, issue_id,
                                               step_num)
                if issue_id:
                    # The cases when issue_id is False/None are 1) error
                    # 2) issue exist and user chose not to append log
                    issue_id_list.append(issue_id)

        print_info("Issue List: {0}".format(issue_id_list))
        return issue_id_list
def set_params_send_email(addsubject, data_repository, files, mail_on):
    """ From data_repository array constructs body of email
        using testcase/testsuite name, logs directory, results directory
        fetches smtp host, sender, receiver from w_settings.xml
        uses paramters such as: subject, body, attachments
    :Arguments:
        1. subject - email subject
        2. data_repository - array of email body lines e.g.
            1. testcase/testsuite name
            2. logs directory
            3. results directory
        3. files - list of file attachments
        4. mail_on(optional) - it is to specify when to send an email
           Supported options below:
                (1) per_execution(default)
                (2) first_failure
                (3) every_failure
    """
    body = ""
    if isinstance(data_repository, list):
        for body_elem in data_repository:
            body += body_elem+"\n"
    else:
        body = data_repository
    params = get_email_params(mail_on)
    compress = params[4]
    if compress.upper().startswith('Y'):
        print_info("compress attribute in w_settings.xml is set to Yes. "
                   "So, all the email attachments will be compressed.")
        zip_files = []
        for file_name in files:
            zip_file = file_Utils.convert_to_zip(file_name)
            zip_files.append(zip_file)
        files = zip_files
    subject = str(params[3])+addsubject
    send_email(params[0], params[1], params[2], subject, body, files)
 def gosleep(cls, target_time):
     """sleep until target_time,
     need to be modified so window doesn't freeze"""
     try:
         target_time = datetime.datetime.strptime(target_time,
                                                  '%Y-%m-%d-%H-%M-%S')
         current_time = datetime.datetime.now().replace(microsecond=0)
         if target_time >= current_time:
             print_info('warrior will sleep until ' + str(target_time))
             print_info('please do not close this window')
             time.sleep((target_time - current_time).total_seconds())
             print_info('warrior is now awake')
         else:
             print_info('Please enter a future time')
             exit(1)
     except ValueError:
         print_error(
             'Please enter a legit time in yyyy-mm-dd-hh-mm-ss format')
         exit(1)
示例#5
0
 def print_result_in_console(self, junit_file):
     """To print the consolidated test cases result in console at the end of Test Case/Test
        Suite/Project Execution"""
     file_type = self.get_file_type(junit_file)
     # Formatting execution summary as project_summary and suite_summary returns the list values
     print_info(
         "+++++++++++++++++++++++++++++++++++++++++++++++++ Execution Summary +++++++++++++++++++++++++++++++++++++++++++++++++"
     )
     print_info("{0:10}{1:50}{2:10}{3:50}".format('Type', 'Name [DataFile]',
                                                  'Status', 'Path'))
     if file_type == "Project":
         project_exec = self.project_summary(junit_file)
         invalid_suite_path = []
         for proj in project_exec:
             print_info(
                 ("{0:10}{1:50}{2:10}{3:30}".format(proj[0], proj[1],
                                                    proj[2], proj[3])))
             testsuite_list = common_execution_utils.get_steps_lists(
                 proj[3], "Testsuites", "Testsuite")
             project_dir = os.path.dirname(proj[3])
             for testsuite in testsuite_list:
                 testsuite_rel_path = testsuite_utils.get_path_from_xmlfile(
                     testsuite)
                 if testsuite_rel_path is not None:
                     testsuite_path = Utils.file_Utils.getAbsPath(
                         testsuite_rel_path, project_dir)
                 else:
                     testsuite_path = str(testsuite_rel_path)
                 if not file_Utils.fileExists(testsuite_path):
                     invalid_suite_path.append([
                         "Suites",
                         os.path.basename(testsuite_path), "ERROR",
                         testsuite_path
                     ])
         suite_tc_list = self.suite_summary(junit_file)
         suite_tc_exec = invalid_suite_path + suite_tc_list
         self.print_execution_summary_details(suite_tc_exec)
     elif file_type == "Suites":
         suite_tc_exec = self.suite_summary(junit_file)
         self.print_execution_summary_details(suite_tc_exec)
     print_info(
         "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
     )
    def connect_target_via_host(self,
                                target,
                                user,
                                auth,
                                invoke_shell=False,
                                log=None):
        """Forward the SSH connection to another target client
           :Argument:
             1. target(string) - Name/ip target machine to be connected
             2. user - username to connect
             3. auth - password for the user
             4. invoke_shell - open shell for passing commands

           :Returns:
             1. target_session - Session object for target connection
             2. status(bool)= True / False

        """
        target_session = SSHComm(target, uid=user, pid=auth, logfile=log)
        status = False
        try:
            ssh_transport = self.sshobj.get_transport()

            channel = ssh_transport.open_channel("direct-tcpip", (target, 22),
                                                 ('localhost', 0))
            print_info("Connecting to target: {}".format(target))
            target_session.sshobj.set_missing_host_key_policy(\
                                       self.param.AutoAddPolicy())
            target_session.sshobj.connect(target,
                                          port=22,
                                          username=user,
                                          password=auth,
                                          sock=channel)
            if target_session.logfile:
                target_session.log = open(self.logfile, 'w')
            print_info("Connection to target: {}successful".format(target))
            if invoke_shell:
                print_info("Opening shell for {}".format(target))
                target_session.invoke_shell()

            status = True

        except self.param.SSHException as exception:
            print_exception(exception)

        except Exception as exception:
            print_exception(exception)

        return target_session, status
def report_testsuite_result(suite_repository, suite_status):
    """Reports the result of the testsuite executed
    Arguments:
    1. suite_repository    = (dict) dictionary caontaining all the data related to the testsuite
    2. suite_status        = (bool) status of the testsuite executed
    """
    # suite_resultfile = suite_repository['junit_resultfile']
    print_info("****** TestSuite Result ******")
    suite_status = {'TRUE': 'PASS', 'FALSE': 'FAIL', 'EXCEPTION': 'ERROR', 'ERROR': 'ERROR',
                    'RAN': 'RAN'}.get(str(suite_status).upper())
    print_info("Testsuite:{0}  STATUS:{1}".format(suite_repository['suite_name'], suite_status))
    # pSuite_report_suite_result(suite_resultfile)
    print_info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ END OF TEST SUITE "
               "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
    return suite_status
示例#8
0
 def _get_text(self, element, **kwargs):
     """gets the text from element
     :Arguments:
         1. element = a valid WebElement
     """
     print_info("get element text")
     print_info("tag: " + element.tag_name)
     if element.tag_name == "input":
         value = element.get_attribute("value")
     else:
         value = element.text
     if value is not None:
         status = True
     print_info("The text for this element is {}".format(value))
     return status, value
    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 manual_defects(self, paths):
        """parse file list and create jira issue for each failures"""
        print_debug("manual-create defects")

        if self.path_type == "dir":
            defects_json_list = []
            i = 0
            abs_cur_dir = os.path.abspath(os.curdir)
            for path in paths:
                i += 1
                print_info("Directory {0}: {1}".format(i, path))
                defect_dir = file_Utils.getAbsPath(path, abs_cur_dir)
                if file_Utils.dirExists(defect_dir):
                    for j_file in os.listdir(path):
                        j_file = os.path.join(path, j_file)
                        if j_file is not None:
                            check_file = self.check_defect_file(j_file)
                            if check_file is not None:
                                defects_json_list.append(check_file)
                else:
                    print_error("Directory does not exist in provided path {0} "\
                                "relative to cwd".format(path))
                print_debug("\n")
        else:
            defects_json_list = []
            i = 0
            for path in paths:
                i += 1
                print_info("File {0}: {1}".format(i, path))
                check_file = self.check_defect_file(path)
                if check_file is not None:
                    defects_json_list.append(check_file)
                print_debug("\n")

        if len(defects_json_list) == 0:
            print_info("No defect json files found")
            exit(0)
        elif len(defects_json_list) > 0:
            for j_file in defects_json_list:
                data_repository = self.defects_json_parser(j_file)
                if data_repository is not None:
                    data_repository['jiraproj'] = self.jiraproj
                    defect_obj = defects_driver.DefectsDriver(data_repository)
                    if defect_obj.connect_warrior_jira() is True:
                        defect_obj.create_jira_issues([j_file])
示例#11
0
    def testsuite_prerun(self,
                         testsuite_filepath,
                         root,
                         check_files_dict=None):
        """Executes prerun of a testsuite file """
        print_debug('\n')
        print_debug('*' * 40)
        print_debug("Validating Test suite xml")
        print_debug('*' * 40)

        testsuite_xsd_fullpath = self.xsd_dir + os.sep + 'warrior_suite.xsd'
        testsuite_status = self.xml_to_xsd_validation(testsuite_filepath,
                                                      testsuite_xsd_fullpath)
        if testsuite_status:
            data_file_valid, check_files_dict = self.check_testsuite_input_datafile(\
                testsuite_filepath, check_files_dict)
            testsuite_status &= data_file_valid
            for testcase in root.iter('Testcase'):
                tc_path_rel = testsuite_utils.get_path_from_xmlfile(testcase)
                tc_path = file_Utils.getAbsPath(
                    tc_path_rel, os.path.dirname(testsuite_filepath))
                time.sleep(5)
                if os.path.isfile(tc_path):
                    print_debug('\n')
                    print_info('tc_path: {0}, Testcase file exists...'.format(
                        tc_path))
                    tc_status = self.testcase_prerun(tc_path, check_files_dict)
                else:
                    print_debug('\n')
                    tc_status = False
                    print_error(
                        'tc_path: {0}, Testcase file does not exist'.format(
                            tc_path))
                    print_info('TC STATUS: {0}'.format('FAILED'))
                testsuite_status &= tc_status

        else:
            print_error("Incorrect xml format")

        time.sleep(5)
        print_debug('\n')
        status = testcase_Utils.convertLogic(testsuite_status)
        print_info('SUITE STATUS: {0}ED'.format(status))

        return testsuite_status
示例#12
0
    def project_prerun(self, project_filepath, root):
        """Executes prerun of a project file """

        print_debug('\n')
        print_debug('+' * 40)
        print_debug("Validating Project xml")
        print_debug('+' * 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_debug('\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_debug('\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_debug('\n')
        status = testcase_Utils.convertLogic(project_status)
        print_info('PROJECT STATUS: {0}ED'.format(status))

        return project_status
示例#13
0
    def retrieve_data_from_json(self, json_file, search_pattern):
        """Retrieves and returns data from input json
        file which matches with search pattern"""

        json_object = json.load(open(json_file, 'r'))
        for k, v in list(json_object.items()):
            if search_pattern == k:
                print_info("Search pattern found in json")
                return v
            else:
                if not any(k == search_pattern for k in list(v.keys())):
                    print_info("Search pattern not found")
                    return None
                else:
                    print_info("Search pattern found in json")
                    for key, value in list(v.items()):
                        if key == search_pattern:
                            return value
                        else:
                            continue
示例#14
0
    def _make_ff(self, webdriver_remote_url, desired_capabilites, profile_dir,
                 **kwargs):
        """Create an instance of firefox browser"""
        binary = kwargs.get("binary", None)
        gecko_path = kwargs.get("gecko_path", None)
        # gecko_log is the absolute path to save geckodriver log
        gecko_log = kwargs.get("gecko_log", None)
        proxy_ip = kwargs.get("proxy_ip", None)
        proxy_port = kwargs.get("proxy_port", None)
        ff_profile = None
        # if firefox is being used with proxy, set the profile here
        # if firefox_proxy details are not given, set profile_dir
        # as the ff_profile.
        if proxy_ip is not None and proxy_port is not None:
            ff_profile = self.set_firefox_proxy(profile_dir, proxy_ip,
                                                proxy_port)
        else:
            ff_profile = profile_dir
        log_dir = get_object_from_datarepository("wt_logsdir") if \
                  gecko_log in [None, False] else gecko_log
        log_dir = os.path.join(
            log_dir, "gecko_" + kwargs.get("browser_name", "default") + ".log")

        browser = None
        try:
            if webdriver_remote_url:
                browser = self._create_remote_web_driver(
                    webdriver.DesiredCapabilities.FIREFOX,
                    webdriver_remote_url, desired_capabilites, ff_profile)
            else:
                optional_args = {}
                ff_capabilities = webdriver.DesiredCapabilities.FIREFOX
                # This is for internal testing needs...some https cert is not secure
                # And firefox will need to know how to handle it
                ff_capabilities['acceptInsecureCerts'] = True

                if binary not in [False, None]:
                    if not fileExists(binary):
                        print_warning(
                            "Given firefox binary '{}' does not exist, default "
                            "firefox will be used for execution.".format(
                                binary))
                        binary = None
                else:
                    print_info("No value given for firefox binary, default "
                               "firefox will be used for execution.")

                # Force disable marionette, only needs in Selenium 3 with FF ver < 47
                # Without these lines, selenium may encounter capability not found issue
                # https://github.com/seleniumhq/selenium/issues/2739
                # https://github.com/SeleniumHQ/selenium/issues/5106#issuecomment-347298110
                if self.get_firefox_version(binary) < LooseVersion("47.0.0"):
                    ff_capabilities["marionette"] = False
                else:
                    # gecko_log will only get generate if there is failure/error
                    # Need to specify log_path for geckodriver log
                    # Gecko driver will only launch if FF version is 47 or above
                    optional_args["log_path"] = log_dir

                ffbinary = FirefoxBinary(
                    binary) if binary is not None else None
                if gecko_path is not None:
                    optional_args["executable_path"] = gecko_path
                browser = webdriver.Firefox(firefox_binary=ffbinary,
                                            capabilities=ff_capabilities,
                                            firefox_profile=ff_profile,
                                            **optional_args)
        except WebDriverException as err:
            if "executable needs to be in PATH" in str(err):
                print_error("Please provide path for geckodriver executable")
            elif "Expected browser binary location" in str(err):
                print_error("Please provide path of firefox executable")
            print_error(err)
            traceback.print_exc()
        except Exception as err:
            print_error(err)
            traceback.print_exc()

        if browser is None and\
           any((LooseVersion(webdriver.__version__) < LooseVersion("3.5.0"), gecko_path is None)):
            print_info("Unable to create Firefox browser, one possible reason is because"\
                       "Firefox version >= 47.0.1 and Selenium version < 3.5"\
                       "In order to launch Firefox ver 47 and up, Selenium needs to be updated to >= 3.5"\
                       "and needs geckodriver > 0.16")

        return browser
示例#15
0
    def close_tab(self,
                  browser_instance=None,
                  tab_number=None,
                  browser_type="firefox"):
        """Closing tabs in a browser with unique tab_number"""
        if browser_instance is None:
            browser_instance = self.current_browser

        if len(browser_instance.window_handles) > 1:
            prior_current_tab = False
            current_window_handler = browser_instance.current_window_handle
            for i in range(0, len(browser_instance.window_handles)):
                if browser_instance.window_handles[
                        i] == current_window_handler:
                    prior_current_tab = i

            status = True
            if tab_number is not None:
                status = self.switch_tab(browser_instance, tab_number,
                                         browser_type)
                if status:
                    tab_number = int(tab_number) - 1
                    browser_instance.find_element_by_tag_name(
                        'body').send_keys(Keys.LEFT_CONTROL, 'w')
                    sleep(2)
                    if tab_number == len(browser_instance.window_handles):
                        tab_number -= 1
                    browser_instance.switch_to.window(
                        browser_instance.window_handles[tab_number])
                    if prior_current_tab == len(
                            browser_instance.window_handles):
                        prior_current_tab -= 1

                    if prior_current_tab != tab_number:
                        if tab_number < prior_current_tab:
                            times = prior_current_tab - tab_number
                        else:
                            times = len(
                                browser_instance.window_handles) - tab_number
                            times += prior_current_tab
                        if browser_type == "firefox":
                            action_chains = ActionChains(browser_instance)
                            action_chains.key_down(Keys.ALT)
                            for i in range(0, times):
                                action_chains.send_keys('`')
                            action_chains.perform()
                        else:
                            element = browser_instance.find_element_by_tag_name(
                                'body')
                            for i in range(0, times):
                                element.send_keys(Keys.LEFT_CONTROL, Keys.TAB)

                    browser_instance.switch_to.window(
                        browser_instance.window_handles[prior_current_tab])
            else:
                if browser_type == "firefox":
                    print_info(
                        "The tab_number argument is None. Current window will be closed"
                    )
                else:
                    print_info(
                        "The tab_number argument is None. Current tab will be closed"
                    )
                browser_instance.find_element_by_tag_name('body').send_keys(
                    Keys.LEFT_CONTROL, 'w')
                if prior_current_tab == len(browser_instance.window_handles):
                    prior_current_tab = 0
                browser_instance.switch_to.window(
                    browser_instance.window_handles[prior_current_tab])
        else:
            status = self.close_browser(browser_instance)

        return status
示例#16
0
import traceback
from time import sleep
import platform
import urllib.request, urllib.error, urllib.parse
from subprocess import check_output, CalledProcessError
from distutils.version import LooseVersion
from warrior.Framework.Utils.datetime_utils import get_current_timestamp
from warrior.Framework.Utils.testcase_Utils import pNote
from warrior.Framework.Utils.print_Utils import print_error, print_info, print_debug, print_exception,\
    print_warning
from warrior.Framework.Utils.data_Utils import get_object_from_datarepository
from warrior.Framework.Utils.file_Utils import fileExists

try:
    from selenium import webdriver
    print_info("The Selenium Webdriver version is '{0}'".format(
        webdriver.__version__))
    from selenium.webdriver import ActionChains
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
    from selenium.common.exceptions import WebDriverException

    KEYS = {
        1: Keys.NUMPAD1,
        2: Keys.NUMPAD2,
        3: Keys.NUMPAD3,
        4: Keys.NUMPAD4,
        5: Keys.NUMPAD5,
        6: Keys.NUMPAD6,
        7: Keys.NUMPAD7,
        8: Keys.NUMPAD8,
        9: Keys.NUMPAD9
示例#17
0
 def perform_element_action(self,
                            element_or_browser,
                            locator=None,
                            action=None,
                            **kwargs):
     """Generic method to perform specific actions on an element
     :Currently supported actions and the values that they take
     if the user provided action is "get_text", it would return the
     value of the particular element and the status of it. If not it would
     return only the status"""
     browser = kwargs.get('browser')
     status = True
     if action != "perform_keypress":
         element = self._get_element(element_or_browser, locator)
     else:
         element = element_or_browser
     if element:
         action_function = self._get_action_function(action.lower())
         if not action_function:
             print_error((action + " is not a supported "
                          "a supported value."))
         else:
             count = 0
             while (count <= 3):
                 try:
                     if action == "get_text":
                         status, value = action_function(element, **kwargs)
                         if status is True:
                             return status, value
                         else:
                             status, count = self.wait_time(
                                 count, browser, locator, action)
                             if status is True:
                                 return status
                     else:
                         status = action_function(element, **kwargs)
                         if status is True:
                             return status
                         else:
                             status, count = self.wait_time(
                                 count, browser, locator, action)
                             if status is True:
                                 return status
                 except StaleElementReferenceException:
                     status = False
                     try:
                         if action == "get_text":
                             count = count + 1
                             print_info("waiting for 3 seconds "
                                        "before retrying")
                             sleep(3)
                             status, value = action_function(
                                 element, **kwargs)
                             if status is True:
                                 return status, value
                         else:
                             status, count = self.wait_time(
                                 count, browser, locator, action)
                             if status is True:
                                 return status
                     except StaleElementReferenceException:
                         status = False
                 except Exception as exception:
                     status = False
                     print_exception(exception)
                     return status
             else:
                 print_error("StaleElementReferenceException occured."
                             "Tried three times to locate the element")
                 status = False
     else:
         status = False
         print_error("Provide a valid WebElement to perform "
                     "a {0} operation got {1}".format(action, element))
     return status
示例#18
0
 def p_warn(self, level, text=""):
     """Report a warning """
     print_info("{0} STATUS:WARNING".format(text))
     #print_warning("WARNING: %s\n" % text)
     self.p_status("WARNING", level)
def report_testcase_result(tc_status, data_repository, tag="Steps"):
    """Report the testcase result to the result file

    :Arguments:
        1. tc_status (bool) = status of the executed testcase
        2. data_repository (dict) = data_repository of the executed  testcase
    """
    print_info("**** Testcase Result ***")
    tc_duration = Utils.data_Utils.get_object_from_datarepository("tc_duration")
    print_info("TESTCASE:{0}  STATUS:{1} | Duration = {2}".format(data_repository['wt_name'],
                                                 convertLogic(tc_status), tc_duration))
    print_debug("\n")
    Utils.testcase_Utils.pTestResult(tc_status, data_repository['wt_resultfile'])
    root = Utils.xml_Utils.getRoot(data_repository['wt_resultfile'])
    fail_count = 0
    for value in root.findall('Keyword'):
        kw_status = value.find('KeywordStatus').text
        if kw_status != "PASS" and kw_status != "RAN":
            fail_count += 1
            kw_name = value.find('Name').text
            get_step_value = list(value.attrib.values())
            step_num = ','.join(get_step_value)
            if fail_count == 1:
                print_info("++++++++++++++++++++++++ Summary of Failed Keywords +++++++++++++++++++"
                           "+++++")
                print_info("{0:15} {1:60} {2:10}".format('StepNumber', 'KeywordName', 'Status'))
                print_info("{0:15} {1:60} {2:10}".format(str(step_num), tag+"-"+str(kw_name),
                                                         str(kw_status)))
            elif fail_count > 1:
                print_info("{0:15} {1:60} {2:10}".format(str(step_num), tag+"-"+str(kw_name),
                                                         str(kw_status)))
    print_info("=================== END OF TESTCASE ===========================")
示例#20
0
    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.
        """
        wdesc = "to verify whether the user provided texts exist on the web page"
        pNote("KEYWORD: verify_text_in_window_pane | Description: {0}".format(
            wdesc))
        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
def execute_testcase(testcase_filepath, data_repository, tc_context,
                     runtype, tc_parallel, queue, auto_defects, suite, jiraproj,
                     tc_onError_action, iter_ts_sys, steps_tag="Steps"):
    """ Executes the testcase (provided as a xml file)
            - Takes a testcase xml file as input and executes each command in the testcase.
            - Computes the testcase status based on the stepstatus and the impact value of the step
            - Handles step failures as per the default/specific onError action/value
            - Calls the function to report the testcase status

    :Arguments:
        1. testcase_filepath (string) = the full path of the testcase xml file
        2. execution_dir (string) = the full path of the directory under which the
                                    testcase execution directory will be created
                                    (the results, logs for this testcase will be
                                    stored in this testcase execution directory.)
    """

    tc_status = True
    tc_start_time = Utils.datetime_utils.get_current_timestamp()
    tc_timestamp = str(tc_start_time)
    print_info("[{0}] Testcase execution starts".format(tc_start_time))
    get_testcase_details(testcase_filepath, data_repository, jiraproj)
    #get testwrapperfile details like testwrapperfile, data_type and runtype
    testwrapperfile, j_data_type, j_runtype, setup_on_error_action = \
        get_testwrapper_file_details(testcase_filepath, data_repository)
    data_repository['wt_testwrapperfile'] = testwrapperfile
    isRobotWrapperCase = check_robot_wrapper_case(testcase_filepath)

    # These lines are for creating testcase junit file
    from_ts = False
    pj_junit_display = 'False'
    if not 'wt_junit_object' in data_repository:
        # not from testsuite
        tc_junit_object = junit_class.Junit(filename=data_repository['wt_name'],
                                            timestamp=tc_timestamp,
                                            name="customProject_independant_testcase_execution",
                                            display=pj_junit_display)
        if "jobid" in data_repository:
            tc_junit_object.add_jobid(data_repository["jobid"])
            del data_repository["jobid"]
        tc_junit_object.create_testcase(location=data_repository['wt_filedir'],
                                        timestamp=tc_timestamp,
                                        ts_timestamp=tc_timestamp,
                                        name=data_repository['wt_name'],
                                        testcasefile_path=data_repository['wt_testcase_filepath'])
        junit_requirements(testcase_filepath, tc_junit_object, tc_timestamp)
        data_repository['wt_ts_timestamp'] = tc_timestamp
    else:
        tag = "testcase" if steps_tag == "Steps" else steps_tag
        tc_junit_object = data_repository['wt_junit_object']
        #creates testcase based on tag given Setup/Steps/Cleanup
        tc_junit_object.create_testcase(location="from testsuite", timestamp=tc_timestamp,
                                        ts_timestamp=data_repository['wt_ts_timestamp'],
                                        classname=data_repository['wt_suite_name'],
                                        name=data_repository['wt_name'],
                                        tag=tag,
                                        testcasefile_path=data_repository['wt_testcase_filepath'])
        from_ts = True
        junit_requirements(testcase_filepath, tc_junit_object, data_repository['wt_ts_timestamp'])
    data_repository['wt_tc_timestamp'] = tc_timestamp
    data_repository['tc_parallel'] = tc_parallel
    data_type = data_repository['wt_data_type']
    if not from_ts:
        data_repository["war_parallel"] = False

    # Adding resultsdir, logsdir, title as attributes to testcase_tag in the junit result file
    # Need to remove these after making resultsdir, logsdir as part of properties tag in testcase
    tc_junit_object.add_property("resultsdir", os.path.dirname(data_repository['wt_resultsdir']),
                                 "tc", tc_timestamp)
    tc_junit_object.update_attr("console_logfile", data_repository['wt_console_logfile'],
                                "tc", tc_timestamp)
    tc_junit_object.update_attr("title", data_repository['wt_title'], "tc", tc_timestamp)
    tc_junit_object.update_attr("data_file", data_repository['wt_datafile'], "tc", tc_timestamp)
    if data_repository['wt_mapfile']:
        tc_junit_object.update_attr("mapfile", data_repository['wt_mapfile'], "tc", tc_timestamp)

    data_repository['wt_junit_object'] = tc_junit_object
    print_testcase_details_to_console(testcase_filepath, data_repository, steps_tag)
    # Prints the path of result summary file at the beginning of execution
    if data_repository['war_file_type'] == "Case":
        filename = os.path.basename(testcase_filepath)
        html_filepath = os.path.join(data_repository['wt_resultsdir'],
                                     Utils.file_Utils.getNameOnly(filename)) + '.html'
        print_info("HTML result file: {0}".format(html_filepath))
    #get the list of steps in the given tag - Setup/Steps/Cleanup
    step_list = common_execution_utils.get_step_list(testcase_filepath,
                                                     steps_tag, "step")
    if not step_list:
        print_warning("Warning! cannot get steps for execution")
        tc_status = "ERROR"

    if step_list and not len(step_list):
        print_warning("step list is empty in {0} block".format(steps_tag))

    tc_state = Utils.xml_Utils.getChildTextbyParentTag(testcase_filepath,
                                                       'Details', 'State')
    if tc_state is not False and tc_state is not None and \
       tc_state.upper() == "DRAFT":
        print_warning("Testcase is in 'Draft' state, it may have keywords "
                      "that have not been developed yet. Skipping the "
                      "testcase execution and it will be marked as 'ERROR'")
        tc_status = "ERROR"
    elif isRobotWrapperCase is True and from_ts is False:
        print_warning("Case which has robot_wrapper steps should be executed "
                      "as part of a Suite. Skipping the case execution and "
                      "it will be marked as 'ERROR'")
        tc_status = "ERROR"
    elif step_list:

        setup_tc_status, cleanup_tc_status = True, True
        #1.execute setup steps if testwrapperfile is present in testcase
        #and not from testsuite execution
        #2.execute setup steps if testwrapperfile is present in testcase
        #and from testsuite execution and testwrapperfile is not defined in test suite.
        if (testwrapperfile and not from_ts) or (testwrapperfile and \
            from_ts and not 'suite_testwrapper_file' in data_repository):
            setup_step_list = common_execution_utils.get_step_list(testwrapperfile,
                                                                   "Setup", "step")
            if not len(setup_step_list):
                print_warning("step list is empty in {0} block".format("Setup"))

            print_info("****** SETUP STEPS EXECUTION STARTS *******")
            data_repository['wt_step_type'] = 'setup'
            #to consider relative paths provided from wrapperfile instead of testcase file
            original_tc_filepath = data_repository['wt_testcase_filepath']
            data_repository['wt_testcase_filepath'] = testwrapperfile
            setup_tc_status = execute_steps(j_data_type, j_runtype, \
                data_repository, setup_step_list, tc_junit_object, iter_ts_sys)
            #reset to original testcase filepath
            data_repository['wt_testcase_filepath'] = original_tc_filepath
            data_repository['wt_step_type'] = 'step'
            print_info("setup_tc_status : {0}".format(setup_tc_status))
            print_info("****** SETUP STEPS EXECUTION ENDS *******")

        if setup_on_error_action == 'next' or \
            (setup_on_error_action == 'abort' \
            and isinstance(setup_tc_status, bool) and setup_tc_status):
            if steps_tag == "Steps":
                print_info("****** TEST STEPS EXECUTION STARTS *******")
            data_repository['wt_step_type'] = 'step'
            tc_status = execute_steps(data_type, runtype, \
                data_repository, step_list, tc_junit_object, iter_ts_sys)
            if steps_tag == "Steps":
                print_info("****** TEST STEPS EXECUTION ENDS *******")

        else:
            print_error("Test steps are not executed as setup steps failed to execute,"\
                        "setup status : {0}".format(setup_tc_status))
            print_error("Steps in cleanup will be executed on besteffort")
            tc_status = "ERROR"

        if tc_context.upper() == 'NEGATIVE':
            if all([tc_status != 'EXCEPTION', tc_status != 'ERROR']):
                print_debug("Test case status is: '{0}', flip status as context is "
                            "negative".format(tc_status))
                tc_status = not tc_status

        #Execute Debug section from testcase tw file upon tc failure
        if not isinstance(tc_status, bool) or (isinstance(tc_status, bool) and tc_status is False):
            tc_testwrapperfile = None
            if Utils.xml_Utils.nodeExists(testcase_filepath, "TestWrapperFile"):
                tc_testwrapperfile = Utils.xml_Utils.getChildTextbyParentTag(testcase_filepath, \
                    'Details', 'TestWrapperFile')
                abs_cur_dir = os.path.dirname(testcase_filepath)
                tc_testwrapperfile = Utils.file_Utils.getAbsPath(tc_testwrapperfile, abs_cur_dir)

            tc_debug_step_list = None
            if tc_testwrapperfile and Utils.xml_Utils.nodeExists(tc_testwrapperfile, "Debug"):
                tc_debug_step_list = common_execution_utils.get_step_list(tc_testwrapperfile,
                                                                          "Debug", "step")
            if tc_debug_step_list:
                print_info("****** DEBUG STEPS EXECUTION STARTS *******")
                data_repository['wt_step_type'] = 'debug'
                original_tc_filepath = data_repository['wt_testcase_filepath']
                #to consider relative paths provided from wrapperfile instead of testcase file
                data_repository['wt_testcase_filepath'] = tc_testwrapperfile
                debug_tc_status = execute_steps(j_data_type, j_runtype, \
                    data_repository, tc_debug_step_list, tc_junit_object, iter_ts_sys)
                #reset to original testcase filepath
                data_repository['wt_testcase_filepath'] = original_tc_filepath
                data_repository['wt_step_type'] = 'step'
                print_info("debug_tc_status : {0}".format(debug_tc_status))
                print_info("****** DEBUG STEPS EXECUTION ENDS *******")

        #1.execute cleanup steps if testwrapperfile is present in testcase
        #and not from testsuite execution
        #2.execute cleanup steps if testwrapperfile is present in testcase
        #and from testsuite execution and testwrapperfile is not defined in test suite.
        if (testwrapperfile and not from_ts) or (testwrapperfile and \
            from_ts and not 'suite_testwrapper_file' in data_repository):
            cleanup_step_list = common_execution_utils.get_step_list(testwrapperfile,
                                                                     "Cleanup", "step")
            if not len(cleanup_step_list):
                print_warning("step list is empty in {0} block".format("Cleanup"))
            print_info("****** CLEANUP STEPS EXECUTION STARTS *******")
            data_repository['wt_step_type'] = 'cleanup'
            original_tc_filepath = data_repository['wt_testcase_filepath']
            #to consider relative paths provided from wrapperfile instead of testcase file
            data_repository['wt_testcase_filepath'] = testwrapperfile
            cleanup_tc_status = execute_steps(j_data_type, j_runtype, \
                data_repository, cleanup_step_list, tc_junit_object, iter_ts_sys)
            data_repository['wt_step_type'] = 'step'
            print_info("cleanup_tc_status : {0}".format(cleanup_tc_status))
            print_info("****** CLEANUP STEPS EXECUTION ENDS *******")

    if step_list and isinstance(tc_status, bool) and isinstance(cleanup_tc_status, bool) \
        and tc_status and cleanup_tc_status:
        tc_status = True
    #set tc status to WARN if only cleanup fails
    elif step_list and isinstance(tc_status, bool) and tc_status and cleanup_tc_status != True:
        print_warning("setting tc status to WARN as cleanup failed")
        tc_status = "WARN"

    if step_list and tc_status == False and tc_onError_action \
            and tc_onError_action.upper() == 'ABORT_AS_ERROR':
        print_info("Testcase status will be marked as ERROR as onError "
                   "action is set to 'abort_as_error'")
        tc_status = "ERROR"

    defectsdir = data_repository['wt_defectsdir']
    check_and_create_defects(tc_status, auto_defects, data_repository, tc_junit_object)

    print_debug("\n")
    tc_end_time = Utils.datetime_utils.get_current_timestamp()
    print_debug("[{0}] Testcase execution completed".format(tc_end_time))
    tc_duration = Utils.datetime_utils.get_time_delta(tc_start_time)
    hms = Utils.datetime_utils.get_hms_for_seconds(tc_duration)
    Utils.data_Utils.update_datarepository({"tc_duration" : hms})
    tc_junit_object.update_count(tc_status, "1", "ts", data_repository['wt_ts_timestamp'])
    tc_junit_object.update_count("tests", "1", "ts", data_repository['wt_ts_timestamp'])
    tc_junit_object.update_count("tests", "1", "pj", "not appicable")
    tc_junit_object.update_attr("status", str(tc_status), "tc", tc_timestamp)
    tc_junit_object.update_attr("time", str(tc_duration), "tc", tc_timestamp)
    tc_junit_object.add_testcase_message(tc_timestamp, tc_status)
    if str(tc_status).upper() in ["FALSE", "ERROR", "EXCEPTION"]:
        tc_junit_object.update_attr("defects", defectsdir, "tc", tc_timestamp)

    # Adding resultsdir, logsdir, title as attributes to testcase_tag in the junit result file
    # Need to remove these after making resultsdir, logsdir as part of properties tag in testcase
    tc_junit_object.update_attr("resultsdir", os.path.dirname(data_repository['wt_resultsdir']),
                                "tc", tc_timestamp)
    tc_junit_object.update_attr("logsdir", os.path.dirname(data_repository['wt_logsdir']),
                                "tc", tc_timestamp)
    if data_repository.get("kafka_producer", None):
        war_producer = data_repository.get("kafka_producer")
        war_producer.kafka_producer.flush(60)
        war_producer.kafka_producer.close()
        print_info("Producer Closed connection with kafka broker")
    elif data_repository.get("kafka_consumer", None):
        war_consumer = data_repository.get("kafka_consumer")
        war_consumer.kafka_consumer.close()
        print_info("Consumer closed connection with kafka broker")
        
    data_file = data_repository["wt_datafile"]
    system_name = ""
    try:
        tree = et.parse(data_file)
        for elem in tree.iter():
            if elem.tag == "system":
                for key, value in elem.items():
                    if value == "kafka_producer":
                        system_name = elem.get("name")
                        break
    except:
        pass

    if system_name:
        junit_file_obj = data_repository['wt_junit_object']
        root = junit_file_obj.root
        suite_details = root.findall("testsuite")[0]
        test_case_details = suite_details.findall("testcase")
        if test_case_details:
            test_case_details = suite_details.findall("testcase")[0]
            print_info("kafka server is presented in Inputdata file..")
            system_details = _get_system_or_subsystem(data_file, system_name)
            data = {}
            for item in system_details.getchildren():
                if item.tag == "kafka_port":
                    ssh_port = item.text
                    ssh_port = Utils.data_Utils.sub_from_env_var(ssh_port)
                    continue
                if item.tag == "ip":
                    ip_address = item.text
                    ip_address = Utils.data_Utils.sub_from_env_var(ip_address)
                    continue
                try:
                    value = ast.literal_eval(item.text)
                except ValueError:
                    value = item.text
                data.update({item.tag: value})

            ip_port = ["{}:{}".format(ip_address, ssh_port)]
            data.update({"bootstrap_servers": ip_port})
            data.update({"value_serializer": lambda x: json.dumps(x).encode('utf-8')})
            try:
                producer = WarriorKafkaProducer(**data)
                producer.send_messages('warrior_results', suite_details.items())
                producer.send_messages('warrior_results', test_case_details.items())
                print_info("message published to topic: warrior_results {}".format(
                    suite_details.items()))
                print_info("message published to topic: warrior_results {}".format(
                    test_case_details.items()))
            except:
                print_warning("Unable to connect kafka server !!")

    report_testcase_result(tc_status, data_repository, tag=steps_tag)
    if not from_ts:
        tc_junit_object.update_count(tc_status, "1", "pj", "not appicable")
        tc_junit_object.update_count("suites", "1", "pj", "not appicable")
        tc_junit_object.update_attr("status", str(tc_status), "ts",
                                    data_repository['wt_ts_timestamp'])
        tc_junit_object.update_attr("status", str(tc_status), "pj", "not appicable")
        tc_junit_object.update_attr("time", str(tc_duration), "ts",
                                    data_repository['wt_ts_timestamp'])
        tc_junit_object.update_attr("time", str(tc_duration), "pj", "not appicable")

        tc_junit_object.output_junit(data_repository['wt_resultsdir'])

        # Save JUnit/HTML results of the Case in MongoDB server
        if data_repository.get("db_obj") is not False:
            tc_junit_xml = data_repository['wt_resultsdir'] + os.sep +\
                tc_junit_object.filename + "_junit.xml"
            data_repository.get("db_obj").add_html_result_to_mongodb(tc_junit_xml)
    else:
        # send an email on TC failure(no need to send an email here when
        # executing a single case).
        if str(tc_status).upper() in ["FALSE", "ERROR", "EXCEPTION"]:
            email_setting = None
            # for first TC failure
            if "any_failures" not in data_repository:
                email_params = email.get_email_params("first_failure")
                if all(value != "" for value in email_params[:3]):
                    email_setting = "first_failure"
                data_repository['any_failures'] = True
            # for further TC failures
            if email_setting is None:
                email_params = email.get_email_params("every_failure")
                if all(value != "" for value in email_params[:3]):
                    email_setting = "every_failure"

            if email_setting is not None:
                email.compose_send_email("Test Case: ", data_repository[\
                 'wt_testcase_filepath'], data_repository['wt_logsdir'],\
                                         data_repository['wt_resultsdir'], tc_status,
                                         email_setting)

        if not tc_parallel and not data_repository["war_parallel"]:
            if 'wp_results_execdir' in data_repository:
                # Create and replace existing Project junit file for each case
                tc_junit_object.output_junit(data_repository['wp_results_execdir'],
                                             print_summary=False)
            else:
                # Create and replace existing Suite junit file for each case
                tc_junit_object.output_junit(data_repository['wt_results_execdir'],
                                             print_summary=False)

    if tc_parallel:
        tc_impact = data_repository['wt_tc_impact']
        if tc_impact.upper() == 'IMPACT':
            msg = "Status of the executed test case impacts Testsuite result"
        elif tc_impact.upper() == 'NOIMPACT':
            msg = "Status of the executed test case does not impact Teststuie result"
        print_debug(msg)
        tc_name = Utils.file_Utils.getFileName(testcase_filepath)
        # put result into multiprocessing queue and later retrieve in corresponding driver
        queue.put((tc_status, tc_name, tc_impact, tc_duration, tc_junit_object))

    # Save XML results of the Case in MongoDB server
    if data_repository.get("db_obj") is not False:
        data_repository.get("db_obj").add_xml_result_to_mongodb(data_repository['wt_resultfile'])

    # main need tc_status and data_repository values to unpack
    return tc_status, data_repository
    def set_env_var(self,
                    var_key=None,
                    var_value=None,
                    filepath=None,
                    jsonkey="environmental_variables",
                    overwrite="yes"):
        """Create a temp environment variable, the value will only stay for the current Execution
        :Argument:
            var_key = key of the environment variable
            var_value = value of the environment variable
            filepath = Json file where Environmental variables are defined
            jsonkey = The key where all the ENV variable & values are defined
        With jsonkey arg, Users can call same file to set various ENV Variable
            overwrite = Yes-Will overwrite ENV variables set earlier via terminal or other means
                        No -Will not overwrite the ENV variables set earlier with the ones passed
                            through this keyword.

        Variable File :
        Sample environmental_variable file is available under
        Warriorspace/Config_file/Samples/Set_ENV_Variable_Sample.json
        """
        wDesc = "Create a temp environment variable, the value will only stay for the \
        current Execution"

        Utils.testcase_Utils.pNote(
            "KEYWORD: set_env_var | Description: {0}".format(wDesc))
        overwrite = overwrite.upper()
        status = False
        if not any([var_key, var_value, filepath]):
            print_error(
                'Either Provide values to arguments \"var_key\" & \"var_value\" or to '
                'argument \"filepath\"')
        if overwrite == "NO" and os.getenv(var_key):
            print_info("Using ENV variable {0} set earlier with "
                       "value '{1}'".format(var_key, os.getenv(var_key)))
        elif var_key is not None and var_value is not None and overwrite in [
                "YES", "NO"
        ]:
            os.environ[var_key] = var_value
            if os.environ[var_key] == var_value:
                print_info("Set ENV variable {0} with value '{1}'".format(
                    var_key, var_value))
                status = True
        else:
            print_error(
                'The attribute overwrite can only accept values either yes or no'
            )
        if filepath is not None:
            testcasefile_path = get_object_from_datarepository(
                'wt_testcase_filepath')
            try:
                filepath = getAbsPath(filepath,
                                      os.path.dirname(testcasefile_path))
                with open(filepath, "r") as json_handle:
                    get_json = json.load(json_handle)
                    if jsonkey in get_json:
                        env_dict = get_json[jsonkey]
                        for var_key, var_value in list(env_dict.items()):
                            if overwrite == "NO" and os.getenv(var_key):
                                print_info(
                                    'Using ENV variable {0} set earlier with value '
                                    '{1}'.format(var_key, os.getenv(var_key)))
                                status = True
                            elif overwrite in ["YES", "NO"]:
                                os.environ[var_key] = str(var_value)
                                if os.environ[var_key] == var_value:
                                    print_info(
                                        'Setting ENV variable {0} with value '
                                        '{1}'.format(var_key, var_value))
                                    status = True
                            else:
                                print_error(
                                    'The attribute overwrite can only accept values either '
                                    'yes or no')
                    else:
                        print_error(
                            'The {0} file is missing the key '
                            '\"environmental_variables\", please refer to '
                            'the Samples in Config_files'.format(filepath))
                        status = False
            except ValueError:
                print_error('The file {0} is not a valid json '
                            'file'.format(filepath))
                status = False
            except IOError:
                print_error('The file {0} does not exist'.format(filepath))
                status = False
            except Exception as error:
                print_error('Encountered {0} error'.format(error))
                status = False

        return status
    def store_in_repo(self,
                      datavar=None,
                      datavalue=None,
                      type='str',
                      filepath=None,
                      jsonkey="repo_variables",
                      bool_store_all=False):
        """Stores datavalue in datavar of datarepository
        :Argument:
            1. datavar = Key to be used to store datavalue in data_repository,
                         this could be dot separated to store in nested fashion
                            i.e., if var is k1.k2.k3 then the data value would be
                            stored as a value in datarepository[k1][k2][k3]
            2. datavalue = Value to be stored
            3. type = Type of datavalue(string/int/float)
            4. filepath = Json file where datarepository variables are defined.
                          It is to store multiple key,value pairs in datarepository.
            5. jsonkey = The key where all the REPO variables & values are
                         defined in the filepath
            6. bool_store_all = Set to True to store whole json file content to data repository.
                                Keys from the json file will be used as it is to store in repo
                                if this value is set to True.
                                default value is set to False

            Sample JSON file:
                 {
                     "repo_variables": {
                         "var1": {"type": "int", "value": "10"},
                         "var2.var3": {"value": "10"},
                         "var4.var5": "1"
                         },
                     "user_defined_tag":{
                         "var6" : {"type": "int", "value": "40"}
                         }
                 }
            All three formats in the above sample block are allowed. If 'type'
            is not provided, value will be converted as string by default.
        """
        wDesc = "Stores the values to the data_repository"
        Utils.testcase_Utils.pNote(
            "KEYWORD: store_in_repo | Description: {0}".format(wDesc))
        status = False
        pass_msg = "Value: {0} is stored in a Key: {1} of Warrior data_repository"

        if datavar is not None and datavalue is not None:
            if type == 'int':
                datavalue = int(datavalue)
            elif type == 'float':
                datavalue = float(datavalue)
            dict_to_update = Utils.dict_Utils.get_dict_to_update(
                datavar, datavalue)
            update_datarepository(dict_to_update)
            print_info(pass_msg.format(datavalue, datavar))
            status = True

        if filepath is not None:
            testcasefile_path = get_object_from_datarepository(
                'wt_testcase_filepath')
            try:
                filepath = getAbsPath(filepath,
                                      os.path.dirname(testcasefile_path))
                with open(filepath, "r") as json_handle:
                    json_doc = json.load(json_handle)
                #if bool_store_all is set to True, all content of given json file will be
                #stored in data repository
                if isinstance(bool_store_all, bool) and bool_store_all is True:
                    print_info(
                        "bool_store_all is set to True, all content of given"
                        " json file will be stored in data repository")
                    update_datarepository(json_doc)
                    print_info("{0} dictionary stored in Warrior data_repository".\
                        format(json_doc))
                    status = True
                elif not isinstance(bool_store_all, bool):
                    print_error("invalid value : {0} given for bool_store_all,"
                                "valid value: boolean True or False".format(
                                    bool_store_all))
                    status = False
                elif jsonkey in json_doc:
                    dict_to_update = {}
                    repo_dict = json_doc[jsonkey]
                    for var_key, var_value in list(repo_dict.items()):
                        if isinstance(var_value, dict):
                            if var_value.get('type') == 'int':
                                value = int(var_value['value'])
                            elif var_value.get('type') == 'float':
                                value = float(var_value['value'])
                            else:
                                value = str(var_value['value'])
                        else:
                            value = str(var_value)
                        build_dict = Utils.dict_Utils.get_dict_to_update(
                            var_key, value)
                        Utils.dict_Utils.verify_key_already_exists_and_update\
                           (orig_dict=dict_to_update, new_dict=build_dict)
                    update_datarepository(dict_to_update)
                    print_info("{0} dictionary stored in Warrior data_repository".\
                        format(dict_to_update))
                    status = True
                else:
                    print_error('The {0} file is missing the key '
                                '\"repo_variables\", please refer to '
                                'the Samples in Config_files'.format(filepath))
                    status = True
            except ValueError:
                print_error('The file {0} is not a valid json '
                            'file'.format(filepath))
            except IOError:
                print_error('The file {0} does not exist'.format(filepath))
            except Exception as error:
                print_error('Encountered {0} error'.format(error))

        if (type is None or datavalue is None) and filepath is None:
            print_error('Either Provide values to arguments \"datavar\" & '
                        '\"datavalue\" or to argument \"filepath\"')

        return status
示例#24
0
 def p_skip(self, level, text=""):
     """Report a skip """
     print_info("{0} STATUS:SKIPPED".format(text))
     #print_info("SKIPPED: %s\n" % text)
     self.p_status("SKIPPED", level)
示例#25
0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import os
from warrior.Framework.Utils.print_Utils import print_info, print_warning
from warriorgnmi.ClassUtils import WNetwork, ssh_utils_class
from warrior.WarriorCore.Classes.warmock_class import mocked
from warrior.WarriorCore.Classes.war_cli_class import WarriorCliClass

try:
    import pexpect
except ImportError:
    print_info("{0}: pexpect module is not installed".format(
        os.path.abspath(__file__)))
    print_info(
        "Warrior framework by default uses pexpect for all cli related activites"
    )
    print_info("All default methods/functions that use cli will fail"
               "without pexpect module. Users can however create"
               "their own custom libraries for cli interaction \n")


def pexpect_spawn_with_env(pexpect_obj,
                           command,
                           timeout,
                           escape=False,
                           env=None):
    """ spawn a pexpect object with environment variable """
示例#26
0
 def p_exception(self, level, text=""):
     """Report a exception """
     print_info("{0} STATUS:EXCEPTION".format(text))
     #print_info("EXCEPTION: %s\n" % text)
     self.p_status("EXCEPTION", level)
def print_testcase_details_to_console(testcase_filepath, data_repository, steps_tag="Steps"):
    """Prints the testcase details to the console """
    framework_detail.warrior_framework_details()
    print_info("===============================  TC-DETAILS  ===================================="
               "==============")
    print_info("Title: %s" % data_repository['wt_title'])
    print_info("Results directory: %s" % data_repository['wt_resultsdir'])
    print_info("Logs directory: %s" % data_repository['wt_logsdir'])
    print_info("Defects directory: {0}".format(data_repository["wt_defectsdir"]))
    print_info("Datafile: %s" % data_repository['wt_datafile'])
    #to print testwrapperfile details to console
    if data_repository['wt_testwrapperfile']:
        print_info("Testwrapperfile: %s" % data_repository['wt_testwrapperfile'])
    print_info("Expected Results: %s" % data_repository['wt_expResults'])
    if steps_tag == "Steps":
        report_testcase_requirements(testcase_filepath)
    print_info("==================================================================================="
               "=============")
    time.sleep(2)
示例#28
0
 def p_error(self, level, text=""):
     """Report a error """
     print_info("{0} STATUS:ERROR".format(text))
     #print_error("ERROR: %s\n" % text)
     self.p_status("ERROR", level)
def main(testcase_filepath, data_repository={}, tc_context='POSITIVE',
         runtype='SEQUENTIAL_KEYWORDS', tc_parallel=False, auto_defects=False, suite=None,
         tc_onError_action=None, iter_ts_sys=None, queue=None, jiraproj=None, jiraid=None):

    """ Executes a testcase """
    tc_start_time = Utils.datetime_utils.get_current_timestamp()
    if Utils.file_Utils.fileExists(testcase_filepath):
        try:
            Utils.config_Utils.set_datarepository(data_repository)
            if Utils.testrandom_utils.get_generic_datafile(testcase_filepath, data_repository):
                init_datarepository = copy.deepcopy(data_repository)
                exec_tag = data_repository.get("gen_exec_tag", 'default')
                print_info("Execution tag : {}".format(exec_tag))
                generic_data_dict = Utils.testrandom_utils.get_iterations_from_generic_data(testcase_filepath, data_repository)
                tc_status = True
                for iter_number, _ in enumerate(generic_data_dict):
                    gentc_start_time = Utils.datetime_utils.get_current_timestamp()
                    print_info("testcase execution starts with variables : {}"\
                            .format(generic_data_dict[iter_number]))
                    Utils.data_Utils.update_datarepository({"gen_iter_number" : iter_number})
                    tc_data_repository = copy.deepcopy(init_datarepository)
                    gen_tc_status, gen_data_repository = execute_testcase(testcase_filepath,\
                                            tc_data_repository, tc_context, runtype,\
                                            tc_parallel, queue, auto_defects, suite,\
                                            jiraproj, tc_onError_action, iter_ts_sys)
                    tc_status = tc_status and gen_tc_status
                    warrior_cli_driver.update_jira_by_id(jiraproj, jiraid, os.path.dirname(\
                                tc_data_repository['wt_resultsdir']), gen_tc_status)
                    email.compose_send_email("Test Case: ", testcase_filepath,\
                                 tc_data_repository['wt_logsdir'],\
                                 tc_data_repository['wt_resultsdir'], gen_tc_status)
                    data_repository["xml_results_dir"] = os.path.dirname(os.path.dirname(\
                            tc_data_repository['wt_logsdir']))
                    gen_tc_duration = Utils.datetime_utils.get_time_delta(gentc_start_time)
                    dict_to_update_in_db = generic_data_dict[iter_number]
                    dict_to_update_in_db["result"] = "PASS" if gen_tc_status else "FAIL"
                    dict_to_update_in_db["duration_in_seconds"] = gen_tc_duration
                    dict_to_update_in_db["log_file"] = tc_data_repository['wt_logsdir']
                    Utils.testrandom_utils.update_generic_database(exec_tag, testcase_filepath, [dict_to_update_in_db])
                report_file = Utils.testrandom_utils.generate_report_from_generic_db(exec_tag, testcase_filepath,
                                                                                     data_repository)
                print_info("Report file : {}".format(report_file))
            else:
                tc_status, data_repository = execute_testcase(testcase_filepath,\
                                                        data_repository, tc_context, runtype,\
                                                        tc_parallel, queue, auto_defects, suite,\
                                                        jiraproj, tc_onError_action, iter_ts_sys)
        except Exception as exception:
            print_exception(exception)
            tc_status = False

    else:
        print_error("Testcase xml file does not exist in provided path: {0}"
                    .format(testcase_filepath))
        tc_status = False
        if tc_parallel:
            queue.put(('ERROR', str(testcase_filepath), 'IMPACT', '0'))

    tc_duration = Utils.datetime_utils.get_time_delta(tc_start_time)

    return tc_status, tc_duration, data_repository
示例#30
0
def execute_project(project_filepath, auto_defects, jiraproj, res_startdir, logs_startdir,
                    data_repository):
    """
    - Takes a list of testsuite locations input.
    - Iterates over the list and sends each testsuite
    location to testsuite_driver for execution.
    - Gets the status of the testsuite from the
    Warrior and computes the project_status based on the impact value
    of the testsuite.
    - If the testsuite fails, handles the failure using
    the default or specific  onError action,value.
    - Finally reports the project status to the result file.

    Arguments:
    1. testsuite_list        = (list) list of testsuite locations
    2. testsuite_driver      = (module loader) module loader of the testsuite_driver
    3. project_repository    = (dict) dictionary containing all data of the project under execution
    """
    project_start_time = Utils.datetime_utils.get_current_timestamp()
    print_info("[{0}] Project execution starts".format(project_start_time))
    project_title = Utils.xml_Utils.getChildTextbyParentTag(project_filepath, 'Details', 'Title')
    project_repository = get_project_details(project_filepath, res_startdir, logs_startdir,
                                             data_repository)
    project_repository['project_title'] = project_title
    testsuite_list = common_execution_utils.get_step_list(project_filepath,
                                                          "Testsuites", "Testsuite")
    # Prints the path of result summary file at the beginning of execution
    if data_repository['war_file_type'] == "Project":
        filename = os.path.basename(project_filepath)
        html_filepath = os.path.join(project_repository['project_execution_dir'],
                                     Utils.file_Utils.getNameOnly(filename))+'.html'
        print_info("HTML result file: {0}".format(html_filepath))

    # project_resultfile = project_repository['project_resultfile']

    project_name = project_repository['project_name']
    wp_results_execdir = project_repository['wp_results_execdir']
    data_repository['wp_results_execdir'] = wp_results_execdir

    data_repository['jiraproj'] = jiraproj

    pj_junit_object = junit_class.Junit(filename=project_name, timestamp=project_start_time,
                                        name=project_name, display="True")

    pj_junit_object.update_attr("resultsdir",
                                project_repository['project_execution_dir'],
                                "pj", project_start_time)
    pj_junit_object.update_attr("title", project_repository['project_title'], "pj",
                                project_start_time)
    pj_junit_object.add_property("resultsdir", project_repository['project_execution_dir'], "pj",
                                 project_start_time)

    # adding the resultsdir as attribute, need to be removed after making it
    # a property
    pj_junit_object.add_project_location(project_filepath)
    if "jobid" in data_repository:
        pj_junit_object.add_jobid(data_repository["jobid"])
        del data_repository["jobid"]
    data_repository['wt_junit_object'] = pj_junit_object

    data_repository["war_parallel"] = False

    execution_type = Utils.xml_Utils.getChildAttributebyParentTag(project_filepath, 'Details',
                                                                  'type', 'exectype')

    # for backward compatibility(when exectype is not provided)
    if execution_type is False:
        execution_type = "sequential_suites"

    if execution_type.upper() == 'PARALLEL_SUITES':
        pj_junit_object.remove_html_obj()
        data_repository["war_parallel"] = True
        Utils.config_Utils.data_repository = data_repository
        print_info("Executing suites in parallel")
        project_status = parallel_testsuite_driver.main(testsuite_list, project_repository,
                                                        data_repository, auto_defects,
                                                        ts_parallel=True)
    elif execution_type.upper() == 'SEQUENTIAL_SUITES':
        print_info("Executing suites sequentially")
        project_status = sequential_testsuite_driver.main(testsuite_list, project_repository,
                                                          data_repository, auto_defects)
    else:
        print_error("unexpected project_type received...aborting execution")
        project_status = False

    project_end_time = Utils.datetime_utils.get_current_timestamp()
    print_info("[{0}] Project execution completed".format(project_end_time))
    project_duration = Utils.datetime_utils.get_time_delta(project_start_time)
    hms = Utils.datetime_utils.get_hms_for_seconds(project_duration)
    print_info("Project duration= {0}".format(hms))

    report_project_result(project_status, project_repository)
    pj_junit_object.update_attr("status", str(project_status), "pj", project_start_time)
    pj_junit_object.update_attr("time", str(project_duration), "pj", project_start_time)

    pj_junit_object.output_junit(wp_results_execdir)

    # Save JUnit/HTML results of the Project in MongoDB server
    if data_repository.get("db_obj") is not False:
        pj_junit_xml = project_repository['wp_results_execdir'] +\
            os.sep + pj_junit_object.filename + "_junit.xml"
        data_repository.get("db_obj").add_html_result_to_mongodb(pj_junit_xml)

    return project_status, project_repository