def _execute_current_step(self):
     """
     This function actually executes a given step and returns necessary details about that step.
     """
     try:
         result = step_driver.main(self.current_step,
                                   self.current_step_number,
                                   self.data_repository,
                                   self.system_name,
                                   skip_invoked=self.skip_invoked)
         step_status = result[0]
         kw_resultfile = result[1]
         step_impact = result[2]
     except Exception as e:
         print_error('unexpected error %s' % str(e))
         step_status = False
         kw_resultfile = None
         step_impact = Utils.testcase_Utils.get_impact_from_xmlfile(
             self.current_step)
         print_error('unexpected error {0}'.format(traceback.format_exc()))
     self.go_to_step_number = False
     self.step_status_list, self.step_impact_list = \
         common_execution_utils.compute_status(self.current_step,
                                               self.step_status_list,
                                               self.step_impact_list,
                                               step_status, step_impact)
     self.kw_resultfile_list.append(kw_resultfile)
     return step_status
 def __get_list(self, string):
     """
         Get the list of variable from the string (can have multiple ${list} )
     :param string:
     :return:
         a dictionary
         if nothing wrong with list range
             return a dict with orignal list/range as key "1..4,5,6..7:0.5"
             parsed list as value [1,2,3,4,5,6,6.5,7]
         if invalid range found
             return a dict {'Error':False}
         if no list/range found
             return a dict {'False':False}
     """
     return_value = string
     result = {}
     check = self.end_pat
     match = self.__find_match(return_value[:return_value.find(check) +
                                            len(check)])
     while match is not None:
         try:
             parsed_value = self.__parse_list(self.get_value(
                 match.group(2)))
         except (ValueError, TypeError, AttributeError):
             print_error("Invalid list range found")
             return {'Error': False}
         if parsed_value:
             result[match.group(2)] = parsed_value
         return_value = return_value.replace(
             return_value[:return_value.find(check) + len(check)], '')
         match = self.__find_match(return_value[:return_value.find(check) +
                                                len(check)])
     if result == {}:
         return {'False': False}
     return result
Example #3
0
 def verify_data(self, expected, object_key, type='str', comparison='eq'):
     """Verify value in 'object_key' in the data repository matches
     with expected
     :Argument:
         expected = the value to be compared with
         object_key = the object in the data repository to be compared
         type = the type of this expected (str/int/float)
         comparison = actual comparison (eq/ne/gt/ge/lt/le)
             eq - check if both are same(equal)
             ne - check if both are not same(not equal)
             gt - check if object_key is greater than expected
             ge - check if object_key is greater than or equal to expected
             lt - check if object_key is lesser than expected
             le - check if object_key is lesser than or equal to expected
     :Returns:
         status (boolean)
     """
     wDesc = "Verify if value of object_key in data_repository "
     "matches with expected"
     Utils.testcase_Utils.pNote(wDesc)
     result, value = Utils.data_Utils.verify_data(expected, object_key,
                                                  type, comparison)
     if result not in ["FALSE", "TRUE"]:
         return result
     elif result == "FALSE":
         print_error("Expected: {0} {1} {2} but found {0}={3}".format(
             object_key, comparison, expected, value))
         return False
     elif result == "TRUE":
         print_info("Expected: {0} {1} {2} found the same".format(
             object_key, comparison, expected, value))
         return True
    def get_messages(self, get_all_messages=False, **kwargs):
        """
        Get messages from consumer.
        Arguments:
          get_all_messages(bool): set this to True to get all the messages, seeks to the beginning.
                                   Defaults to False.
          timeout(int): timeout in milliseconds
          max_records(int): maximum messages to fetch
        Returns:
          messages(list): messages from the consumer
        """
        timeout_ms = kwargs.get("timeout", 0)
        max_records = kwargs.get("max_records", None)
        messages = []
        msg_pack = {}
        print_info("get messages published to subscribed topics")
        try:
            if get_all_messages:
                self.kafka_consumer.seek_to_beginning()
            msg_pack = self.kafka_consumer.poll(timeout_ms, max_records)
        except KafkaError as exc:
            print_error("Exception occured in get_messages - {}".format(exc))

        for topic, message_list in msg_pack.items():
            for message in message_list:
                messages.append(message.value)
        return messages
 def create_topics(self, topic_sets, **kwargs):
     """
     create topics for the producer or consumer to use
     Arguments:
      topic_sets(list) : list of
      ['topic_name', 'num_partitions', 'replication_factor'] lists
      example : ['topic1',1,1]
      timeout(int): time in milliseconds
     Returns:
       result(bool) : False if exception occures, True otherwise
      None.
     """
     timeout = kwargs.get("timeout", None)
     validate = kwargs.get("validate", False)
     new_topics = [NewTopic(name=tup[0], num_partitions=tup[1],\
                   replication_factor=tup[2]) for tup in topic_sets]
     print_info("creating topics")
     try:
         self.kafka_client.create_topics(new_topics=new_topics,
                                         timeout_ms=timeout,
                                         validate_only=validate)
         result = True
     except KafkaError as exc:
         print_error("Exception during creating topics - {}".format(exc))
         result = False
     return result
Example #6
0
def decide_overwrite_var(namespace):
    """options provided in cli get preference over the ones provided inside tests
    """
    overwrite = {}
    if namespace.datafile:
        if namespace.datafile[0] != os.sep: 
            namespace.datafile = os.getcwd() + os.sep + namespace.datafile
        overwrite['ow_datafile'] = namespace.datafile

    if namespace.resultdir:
        if namespace.resultdir[0] != os.sep: 
            namespace.resultdir = os.getcwd() + os.sep + namespace.resultdir
        overwrite['ow_resultdir'] = namespace.resultdir
    if namespace.logdir:
        if namespace.logdir[0] != os.sep: 
            namespace.logdir = os.getcwd() + os.sep + namespace.logdir
        overwrite['ow_logdir'] = namespace.logdir
    if namespace.outputdir:
        if namespace.outputdir[0] != os.sep: 
            namespace.outputdir = os.getcwd() + os.sep + namespace.outputdir
        overwrite['ow_resultdir'] = namespace.outputdir
        overwrite['ow_logdir'] = namespace.outputdir
    if all([namespace.outputdir, any([namespace.resultdir, namespace.logdir])]):
        print_error("outputdir shouldn't be used with resultdir or logdir")
        exit(1)
    if namespace.jobid:
        overwrite['jobid'] = "http://pharlap.tx.fnc.fujitsu.com/share/logs/"+str(namespace.jobid)
    return overwrite
Example #7
0
    def report_status(self, status, text="", level='Keyword'):
        """
        Reports the status to the testcase xml result file base on the received status
        On receiving a True reports keyword status as Passed
        On receiving a False reports keyword status as Failed
        On receiving a Skip reports keyword status as Skipped
        On receiving a Exception reports keyword status as Exception
        On receiving a Error reports Keyword status as Error
        On receiving a RAN reports Keyword status as RAN 

        :Arguments:
            1. status = (bool) True or False
            2. text = (string) any useful description
            3. level = (string) only supported value currently is Keyword

        :Returns:
            None
        """

        status = {
            'TRUE': self.p_pass,
            'FALSE': self.p_fail,
            'SKIP': self.p_skip,
            'EXCEPTION': self.p_exception,
            'ERROR': self.p_error,
            'RAN': self.p_ran
        }.get(str(status).upper())
        if status is None:
            print_error(
                "unexpected or no value received, expecting TRUE/FALSE/SKIP")
            self.p_error(level, text)
        else:
            status(level, text)
def get_key(encoded_key):
    """
    Function that returns enc instance using
    secret key, passed to this
    function or read from secret.key file

    Args:
        encoded_key - False or base64 secrety key for encryption

    Return:
        IV - Random seed used to enc
        CIPHER - Enc instance used to for encryption
    """
    IV = None
    CIPHER = None
    if encoded_key is False:
        try:
            MYFILE = Tools.__path__[0]+os.sep+"admin"+os.sep+'secret.key'
            with open(MYFILE, 'r') as myfileHandle:
                encoded_key = myfileHandle.read()
        except IOError:
            print_error("Could not find the secret.key file in Tools/Admin!")
    try:
        IV = Random.new().read(AES.block_size)
        CIPHER = AES.new(base64.b64decode(encoded_key), AES.MODE_CFB, IV)
    except Exception as e:
        print_exception("Some problem occured: {0}".format(e))

    return IV, CIPHER
    def p_note_level(self, txt, print_type="info", level=None, ptc=True):
        """Create Note at the provided level"""
        write_locn = self.get_write_locn(str(level).upper())
        print_util_types = [
            "-D-", "", "-I-", "-E-", "-W-", "\033[1;31m-E-\033[0m"
        ]
        p_type = {
            'INFO': print_info,
            'DEBUG': print_debug,
            'WARN': print_warning,
            'WARNING': print_warning,
            'ERROR': print_error,
            'EXCEPTION': print_exception,
            'SUB': print_sub,
            'NOTYPE': print_notype
        }.get(str(print_type).upper(), print_info)
        txt = self.rem_nonprintable_ctrl_chars(str(txt))
        if write_locn is None:
            write_locn = self.current_pointer
        if ptc and print_type not in print_util_types:
            p_type(txt)
        # self.current_pointer may be None,which is not a intended behavior
        if write_locn is not None:
            doc = ET.SubElement(write_locn, "Note")
            doc.text = txt
            self.print_output()
        # The below elif is bypasses the else below. As we may want to
        # print items (banners) before we have a handle to write
        elif print_type == "notype":
            pass

        elif print_type not in print_util_types:
            print_error("Unable to write to location in result file, the "
                        "message is logged in terminal but not in result file")
Example #10
0
    def verify_response(self, command, exp_string, fail_resp, timeout=None):
        """Execute a command using the paramiko SSH object and returns
           the response string

           :Arguments:
               1. command - command to be executed
               2. exp_string - String to be expected
               3. fail_resp - Failure response to be expected
               4. timeout - wait for response

          :Returns:
               1. status(bool)= True / False
               2. out/err = response string
        """
        out, stderr = self.ssh_exec(command, timeout)
        err = stderr.read()
        if out and ((exp_string in out) and (fail_resp not in out)):
            print_info("Output:", out)
            return True, out
        elif out and ((exp_string not in out) or (fail_resp in out)):
            print_info("Error:", out)
            return False, out
        else:
            print_error("Error:", err)
            return False, err
Example #11
0
    def _make_browser(self,
                      browser_name,
                      desired_capabilities=None,
                      profile_dir=None,
                      webdriver_remote_url=None,
                      **kwargs):
        """method to open a browser, calls other sepcific/generic
        make browser methods to open a browser """
        browser_methods = {
            'ff': self._make_ff,
            'firefox': self._make_ff,
            'chrome': self._make_chrome
        }
        creation_method = browser_methods.get(browser_name, None)

        if creation_method is None:
            print_error("{} is not a supported browser. Please use firefox or chrome".\
                             format(browser_name))
            browser = None
        else:
            kwargs["browser_name"] = browser_name
            browser = creation_method(webdriver_remote_url,
                                      desired_capabilities, profile_dir,
                                      **kwargs)
            if browser is not None:
                print_info("The {} browser version is {}".format(
                    browser_name, self.get_browser_version(browser)))
            else:
                print_error(
                    "Unable to create browser for: {}".format(browser_name))

        return browser
Example #12
0
    def __check_input_datafile(cls, filepath, testname, check_files_dict):
        """ Verify that the input data file exists in the path provided.
            If path not provided verify the default data file

        Arguments:
              1. filepath: filepath will be parsed as input for checking
                 Input data
              3. testname: to mention whether it is Testcase/Testsuite datafile
              2. check_files_dict: a dict element to check the status of files
                 whether it has been verified already or not

        Return:
              1. result(bool): if the Datafiles exist, returns True: else False
              2. check_files_dict: a dict element to check the status of files
                 whether it has been verified already or not
        """

        result = []

        input_data_file = xml_Utils.getChildTextbyParentTag(filepath, 'Details',
                                                            'InputDataFile')
        if input_data_file is not False and input_data_file is not None:
            if testname is 'Testsuite':
                check_files_dict['check_datafile'] = True
            input_data_file = str(input_data_file).strip()
            if str(input_data_file).upper() == 'NO_DATA':
                print_info('No_Data option selected for this testcase')
                result.append(True)

            elif 'NO_DATA' not in str(input_data_file).upper():

                data_file_path = file_Utils.getAbsPath(input_data_file,
                                                       os.path.dirname(filepath))
                print_info("{0} input data_file_path: {1}".format(testname, data_file_path))
                if os.path.exists(data_file_path):
                    print_info("{0} Input datafile is present "\
                                "in location {1}".format(testname, data_file_path))
                    result.append(True)
                else:
                    print_error("{0} Input datafile is NOT "\
                                 "present in location {1}".format(testname, data_file_path))
                    result.append(False)

        elif input_data_file is None or input_data_file is False:
            if testname is 'Testcase':
                print_info("InputDataFile is not provided,"\
                           "checking if default InputDataFile exists....")
                default_datafilepath = execution_files_class.get_default_xml_datafile(\
                    filepath)
                print_debug("default_datafile_path: {0}".format(default_datafilepath))
                if os.path.exists(default_datafilepath):
                    print_info("Default input datafile for the Testcase is available")
                    result.append(True)
                else:
                    print_error("Default input datafile for the Testcase is NOT available")
                    result.append(False)
            else:
                check_files_dict['check_datafile'] = False

        return result, check_files_dict
Example #13
0
 def _make_ff(self, webdriver_remote_url, desired_capabilites, profile_dir,
              binary, gecko_path):
     """Create an instance of firefox browser"""
     try:
         if webdriver_remote_url:
             browser = self._create_remote_web_driver(
                     webdriver.DesiredCapabilities.FIREFOX,
                     webdriver_remote_url, desired_capabilites,
                     profile_dir)
         else:
             ff_capabilities = webdriver.DesiredCapabilities.FIREFOX
             if ff_capabilities['marionette']:
                 ff_capabilities['acceptInsecureCerts'] = True
                 ffbinary = FirefoxBinary(binary)
                 browser = webdriver.Firefox(firefox_binary=ffbinary,
                                             firefox_profile=profile_dir,
                                             executable_path=gecko_path)
             else:
                 browser = webdriver.Firefox(firefox_profile=profile_dir)
         return browser
     except WebDriverException as e:
         if "executable needs to be in PATH" in str(e):
             print_error("Please provide path for geckodriver executable")
         elif "Expected browser binary location" in str(e):
             print_error("Please provide path of firefox executable")
def main(exectype_elem_node):
    exec_node = exectype_elem_node.find('Execute')
    if exec_node is None or exec_node is False:
        return True, None

    exec_params = exec_node.attrib
    exec_type = exec_params['ExecType']

    try:
        if exec_type.upper() == 'IF' or exec_type.upper() == 'IF NOT':
            exec_rule_param = exec_node.find('Rule').attrib
            exec_condition = exec_rule_param['Condition']
            exec_cond_var = exec_rule_param['Condvalue']
            arg_datatype_object = ArgumentDatatype(exec_condition,
                                                   exec_cond_var)
            exec_cond_var = arg_datatype_object.convert_arg_to_datatype()
            if exec_rule_param['Else'].upper() == 'GOTO':
                exec_next = exec_rule_param['Elsevalue']
            supported_prefix = [
                "bool_", "str_", "int_", "float_", "list_", "tuple_", "dict_"
            ]
            if any([exec_condition.startswith(i) for i in supported_prefix]):
                exec_condition = exec_condition[exec_condition.find('_') + 1:]

    except KeyError, err:
        print_error("Incorrect condition key used: {0}".format(err.message))
def set_secret_key(plain_text_key):
    encoded_key = False
    # Checks the length of the plain text secret key
    if not len(plain_text_key) == 16:
        print_error("The secret key needs to be exactly 16 characters in length"
                    ". {0} is {1} characters in length."
                    .format(plain_text_key, len(plain_text_key)))
        status = False
    else:
        # Gets base 64 encoding for the plain text secret key
        encoded_key = base64.b64encode(plain_text_key)

        # Gets path to Tools
        path = Tools.__path__[0]

        # creates admin directory if that does not exist
        path = file_Utils.createDir(path, "admin")

        # creates secret.key file if it does not exists. Writes the base 64
        # encoded key to it.
        path = os.path.join(path, "secret.key")
        with open(path, 'w') as f:
            f.write(encoded_key)

        status = True
    return status, encoded_key
Example #16
0
def get_testwrapper_file_details(testsuite_filepath, data_repository):
    """retuns testwrapperfile to use if specified, else returns False"""
    if data_repository.has_key('ow_testwrapperfile'):
        testwrapperfile = data_repository['ow_testwrapperfile']
    else:
        if Utils.xml_Utils.nodeExists(testsuite_filepath, "TestWrapperFile"):
            testwrapperfile = Utils.xml_Utils.getChildTextbyParentTag\
                (testsuite_filepath, 'Details', 'TestWrapperFile')
        else:
            return [False, False, False, 'abort']
    abs_cur_dir = os.path.dirname(testsuite_filepath)
    abs_testwrapperfile = Utils.file_Utils.getAbsPath(testwrapperfile,
                                                      abs_cur_dir)
    Utils.xml_Utils.getRoot(abs_testwrapperfile)
    jfile_obj = execution_files_class.ExecFilesClass(abs_testwrapperfile, "ts",
                                                     None, None)
    if not data_repository.get('suite_data_file', False):
        print_error(
            "Input data file must be specified in test suite global details section"
        )
        exit(0)
    j_data_type = jfile_obj.check_get_datatype(
        data_repository['suite_data_file'])
    j_runtype = jfile_obj.check_get_runtype()
    setup_on_error_action = Utils.testcase_Utils.get_setup_on_error(
        abs_testwrapperfile)
    return [abs_testwrapperfile, j_data_type, j_runtype, setup_on_error_action]
Example #17
0
def decide_createsuite_actions(w_cli_obj, namespace):
    """Decide the actions for -createsuite tag """
    filepath = namespace.filepath

    # already check namespace.create here, no need to double check
    if namespace.filepath is not None and len(namespace.filepath) == 0:
        namespace.filepath = None

    if all([namespace.suitename, namespace.filepath]):
        filepath = w_cli_obj.examine_create_suite(namespace)
        print_info("suite created in ", filepath[0])
        exit(0)

    if all([namespace.suitename, namespace.cat]):
        filepath = w_cli_obj.examine_create_suite(namespace)
        print_info("suite created in ", filepath[0])
        exit(0)

    elif not namespace.cat and not all([namespace.suitename, namespace.filepath]):
        print_error("Invalid combination... Use -createsuite with -suitename, "
                    "filepath(s) (i.e. list of testcase xml files. "
                    "Use -h or --help for more command line options")
        exit(1)
    elif namespace.cat and not namespace.suitename:
        print_error("Invalid combination... Use -creatsuite + -category "
                    "with -suitename")
        exit(1)

    return filepath
Example #18
0
    def upload_logfile_to_jira_issue(self, issue_id, logfile, attachment_name="Log file"):
        """
        Function to attach logs to jira Ticket using JIRA rest API
        :Arguments:
            1. issue_id(str) - Jira issue ID
            2. logfile(str) - File(path) to be attached
            3. attachment_name(str) - Name of the file to be attached
        """

        status = False
        postdata_url = self.server + '/rest/api/2/issue/' + issue_id + '/attachments'
        print_info("logfile is : {0}".format(logfile))
        fileobj = open(logfile, 'rb').read()
        logfile_name = os.path.basename(logfile)
        headers = {"X-Atlassian-Token": "nocheck"}
        files = {"file": (logfile_name, fileobj)}
        response = requests.post(postdata_url, auth=self.auth,
                                 files=files, headers=headers)

        if response:
            status = True
            print_info("{0} - '{1}' uploaded to Jira issue '{2}'"
                       .format(attachment_name, logfile_name, issue_id))
        else:
            print_error("Problem attaching logs to Jira issue '{0}'".format(issue_id))
            print_error("JIRA Error code: ({0}), Error message: ({1})".
                        format(response.status_code, response.reason))
        return status
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):
    """ Executes a testcase """
    tc_start_time = Utils.datetime_utils.get_current_timestamp()
    if Utils.file_Utils.fileExists(testcase_filepath):

        try:
            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
Example #20
0
    def check_jira_issue(self, issue_summary):
        """
            check jira server for any existing issue with the same summary(title)
            :Arguments,:
                1. issue_summary(str) - issue title
            :Returns:
                1. issue_id(str/boolean) - existing issue key or False if not found
        """
        issue_id = False
        parsed_summary = issue_summary.replace("[", "\\\\[")
        parsed_summary = parsed_summary.replace("]", "\\\\]")
        postdata_url = (self.server + '/rest/api/2/search/?jql=summary~' +
                        '\"' + parsed_summary + '\"')
        response = requests.get(postdata_url, auth=self.auth)

        if response:
            resp_dict = response.json()
            for issue in resp_dict["issues"]:
                if issue_summary[:-2].strip() == issue["fields"]["summary"].strip():
                    issue_id = issue["key"]
                else:
                    # partially match title
                    pass
        else:
            print_error("Problem checking JIRA issues with same issue summary")
            print_error("JIRA Error code: ({0}), Error message: ({1})".
                        format(response.status_code, response.reason))
        return issue_id
Example #21
0
    def report_warning(self, status, text="", level='subStep'):
        """
        Reports the status to the testcase xml result file based on the received status
        On receiving a True reports keyword status as Passed
        On receiving a False reports keyword status as Warning
        On receiving a Skip reports keyword status as Skipped
        On receiving a Exception reports keyword status as Exception
        On receiving a Error reports Keyword status as Error

        :Arguments:
            1. status = (bool) True or False
            2. text = (string) any useful description
            3. level = (string) only supported value currently is Keyword

        :Returns:
            None
        """
        from WarriorCore.Classes.war_cli_class import WarriorCliClass
        if WarriorCliClass.mock:
            if str(status).upper() == 'TRUE' or str(status).upper() == 'FALSE':
                status = 'RAN'
        status = {
            'TRUE': self.p_pass,
            'FALSE': self.p_warn,
            'SKIP': self.p_skip,
            'EXCEPTION': self.p_exception,
            'ERROR': self.p_error,
            'RAN': self.p_ran
        }.get(str(status).upper())
        if status is None:
            print_error(
                "unexpected or no value received, expecting TRUE/FALSE/SKIP")
            self.p_error(level, text)
        else:
            status(level, text)
Example #22
0
    def save_screenshot(self, browser_instance=None, filename=None,
                        directory=None):
        """
            Save screenshot of the specified/current browser
        """
        status = True
        if browser_instance is None:
            browser_instance = self.current_browser

        if filename is None:
            current_datetime = str(get_current_timestamp())
            current_datetime = current_datetime.replace(" ", "_")
            current_datetime = current_datetime.replace(":", "-")
            filename = "screenshot_" + current_datetime + ".png"
        else:
            filename += ".png"

        print_info("Screenshot will be saved by the name {0} in directory {1}".format(filename, directory))

        directory = os.path.join(directory, filename)
        try:
            browser_instance.save_screenshot(directory)
            sleep(10)
        except Exception as e:
            print_error("Could not save screenshot {0}". format(e))
            status = False

        return status
 def send_messages(self, topic, value=None, **kwargs):
     """
     Publish messages to the desired topic
     Arguments:
       topic(str): topic name to publish messages
       partition(int): partition nubmer
       key(str): key name
       value(str): message to publish
     Returns:
       result(bool) : False if exception occures, True otherwise
     """
     partition = kwargs.get("partition", None)
     headers = kwargs.get("headers", None)
     timestamp = kwargs.get("timestamp", None)
     key = kwargs.get("key", None)
     print_info("publishing messages to the topic")
     try:
         self.kafka_producer.send(topic=topic,
                                  value=value,
                                  partition=partition,
                                  key=key,
                                  headers=headers,
                                  timestamp_ms=timestamp)
         self.kafka_producer.flush()
         result = True
     except KafkaError as exc:
         print_error("Exception during publishing messages - {}".format(exc))
         result = False
     return result
Example #24
0
    def open_tab(self, browser_instance=None, url=None, browser_type="firefox"):
        """Opens a new tab in the browser"""
        status = True
        if browser_instance is None:
            browser_instance = self.current_browser

        # only when firefox version < 47, open new window
        if browser_type == "firefox" and\
           LooseVersion(self.get_browser_version(browser_instance)) < LooseVersion("47.0.0"):
            element = browser_instance.find_element_by_tag_name("body")
            element.send_keys(Keys.LEFT_CONTROL, 'n')
        elif browser_type == "firefox" or (browser_type == "chrome" and\
             LooseVersion(self.get_browser_version(browser_instance)) > LooseVersion("60.0.0")):
            # If FF version > 47, this action is not supported
            print_error("Firefox (47 or above) and Chrome with chromedriver (2.32 or above)"\
                        "doesn't support opening new tab. Open tab may not function correctly")
            status = False
        else:
            # If it is chrome ver < 60, actually open a new tab
            element = browser_instance.find_element_by_tag_name("body")
            element.send_keys(Keys.LEFT_CONTROL, 't')
        sleep(1)
        browser_instance.switch_to.window(browser_instance.window_handles\
                                          [len(browser_instance.window_handles) - 1])

        if url is not None:
            self.go_to(url, browser_instance)
            sleep(1)

        return status
    def check_tag(self, category_list, dirlist):
        """return list of valid testcase xml
        files with the correct category tag"""
        result = []
        cur_dir = os.path.abspath(os.getcwd())
        if dirlist is None:
            dirlist = [cur_dir]

        for folder in dirlist:
            os.chdir(cur_dir)
            folder = Utils.file_Utils.getAbsPath(folder, os.curdir)
            if os.path.isdir(folder):
                all_files = [
                    Utils.file_Utils.getAbsPath(f, folder)
                    for f in os.listdir(folder)
                ]
                is_xml_files = self.check_xml(all_files)
                for xmlfile in is_xml_files:
                    root = Utils.xml_Utils.getRoot(xmlfile)
                    detail = root.find('Details')
                    if detail is not None:
                        if detail.find('Category') is not None:
                            cat_text = detail.find('Category').text.strip()
                            cat_text = cat_text.split(",")
                            if len(set(category_list) & set(cat_text)) > 0:
                                result.append(xmlfile)
            else:
                print_error(str(folder) + "is not a directory")
        print_info("Number of matching testcases: {0}".format(len(result)))
        return result
Example #26
0
 def get_firefox_version(self, binary):
     """
         Use firefox binary to find out firefox version
         before launching firefox in selenium
     """
     command = ""
     # If the platform is Linux,
     # If Binary - None: default binary is set as "firefox".
     # else the binary path passed through datafile is considered.
     # If the platform is Windows,
     # If Binary - None: default binary is set to Program Files path.
     # else the binary path passed through datafile is considered.
     if platform.system() in "Linux":
         if binary in [False, None]:
             binary = "firefox"
         command = [binary, "-v"]
     elif platform.system() in "Windows":
         if binary in [False, None]:
             binary = self.ff_binary_object._default_windows_location()
         command = "%s -v | more" % (binary) 
     print_info("Platform: {0} Firefox binary path: {1}".format(platform.system(), binary))
     version = False
     try:
         raw_version = check_output(command) 
         match = re.search(r"\d+\.\d+", raw_version)
         if match is not None:
             version = LooseVersion(match.group(0))
         else:
             print_info("Cannot parse Firefox version: {}".format(raw_version))
     except CalledProcessError:
         print_error("Cannot find firefox version, will not launch browser")
     return version
 def get_list_direct(self, string):
     """
         entry function for __get_list
     :param string:
     :return:
         a dictionary
         if nothing wrong with list range
             return a dict with orignal list/range as key "1..4,5,6..7:0.5"
             parsed list as value [1,2,3,4,5,6,6.5,7]
         if invalid range found
             return a dict {'Error':False}
         if no list/range found
             return a dict {'False':False}
     """
     return_value = string
     result = {}
     check = self.end_pat
     match = self.__find_match(return_value[:return_value.find(check) +
                                            len(check)])
     while match is not None:
         try:
             parsed_value = self.__parse_list("{" + match.group(2) + "}")
         except (ValueError, TypeError, AttributeError):
             print_error("Invalid list range found")
             return {'Error': False}
         if parsed_value:
             result[match.group(2)] = parsed_value
         return_value = return_value.replace(
             return_value[:return_value.find(check) + len(check)], '')
         match = self.__find_match(return_value[:return_value.find(check) +
                                                len(check)])
     if result == {}:
         return {'False': False}
     return result
def main(step):
    """
        Entry function for execute nodes in a step
        Handle checking and call the logical decision functions
        combine the final result and return
        :param:
            step: the step Element
        :return:
            decision: Whether the step should be executed or not
            trigger_action: When decision failed, what kind of action to perform
    """
    exec_node = step.find("Execute")
    if exec_node is None:
        return True, None

    decision = True
    trigger_action = None
    exec_type = exec_node.get("ExecType", "")
    if exec_type.upper() == 'IF' or exec_type.upper() == 'IF NOT':
        decision, trigger_action = decision_maker(exec_node)
    elif exec_type.upper() == 'NO':
        decision = False
        trigger_action = "SKIP"
    elif exec_type.upper() == 'YES':
        decision = True
    else:
        decision = False
        supported_values = ['no', 'yes', 'if', 'if not']
        print_error("Unsupported value used for ExecType, supported values are:"
                    "{0} and case-insensitive".format(supported_values))

    return decision, trigger_action
    def testcase_prerun(self, tc_filepath, check_files_dict=None):
        """Executes prerun of a testcase file """
        print('\n')
        print_info('=' * 40)
        print_debug("Validating Test case xml")
        print_info('=' * 40)

        testcase_xsd_fullpath = self.xsd_dir + os.sep + 'warrior_testcase.xsd'
        #print_info("Test case_xsd_location: {0}".format(testcase_xsd_fullpath))

        tc_status = self.xml_to_xsd_validation(tc_filepath,
                                               testcase_xsd_fullpath)

        if tc_status:
            data_file_valid = self.check_tc_input_datafile(
                tc_filepath, check_files_dict)
            tc_status &= data_file_valid
            steps_field_valid = self.check_steps(tc_filepath)
            tc_status &= steps_field_valid
        else:
            print_error("Incorrect xml format")
        time.sleep(5)
        status = testcase_Utils.convertLogic(tc_status)
        print_info('TC STATUS: {0}ED'.format(status))

        return tc_status
Example #30
0
 def compare_json_using_jsonpath(self, response, list_of_jsonpath, list_of_expected_api_responses):
     """
         Will get each json_path in list of jsonpath and get the value of
         that jsonpath in json response
         Compares the value with the expected_api_response
         If all values matches returns True else False
     """
     status = True
     json_response = json.loads(response)
     for index, jsonpath in enumerate(list_of_jsonpath):
         json_path = jsonpath.strip("jsonpath=")
         value = self.get_value_for_nested_key(json_response, json_path)
         # Equality_match: Check if the expected response is equal to API response
         match = True if value == list_of_expected_api_responses[index] else False
         # Perform Regex_search if equality match fails
         if match is False:
             try:
                 # Regex_search: Check if the expected response pattern is in API response
                 match = re.search(list_of_expected_api_responses[index], value)
             except Exception:
                 print_warning("Python regex search failed, invalid "
                               "expected_response_pattern '{}' is "
                               "provided".format(list_of_expected_api_responses[index]))
         if not match:
             status = False
             print_error("For the given '{0}' the expected response value is '{1}'. "
                         "It doesn't match or available in the actual response value "
                         "'{2}'".format(jsonpath, list_of_expected_api_responses[index],
                                        value))
     return status