def checkdir_create_file(self, inpdir, dirname, colocate=False):
        """Check if dir is present, if dir present create subdir nd files
        if dir not present try to create dir, subdir and files
        if not able to create dir use Warrior frameworks default dir structure."""

        dir_status = file_Utils.check_and_create_dir(
            inpdir)  # creates tc_results dir
        if dir_status:
            try:
                if colocate:
                    execdir = self.results_execdir
                else:
                    execdir = file_Utils.createDir_addtimestamp(
                        inpdir, self.nameonly)
                rfile = self.get_exec_file_by_type(dirname, execdir)
            except OSError:
                dir_status = False
            except Exception as exception:
                print_exception(exception)
                dir_status = False
        if dir_status is False:
            print_warning(
                "Creating directory/file(s) in provided path {0} failed. "
                "\n Hence Warrior Framework's default directory structure will be used "
                "for this execution.".format(inpdir))
            execdir = self.create_def_exec_dir()  # proj_exec_dir
            rfile = self.get_exec_file_by_type(dirname, execdir)
        return rfile, execdir
 def get_jira_system_creds(datafile, system_name, list_my_info):
     """Returns a python dictionary containing key value pairs of
     requested info and their values for the provided system name from the datafile """
     if system_name is not None:
         element = xml_Utils.getElementWithTagAttribValueMatch(
             datafile, 'system', 'name', system_name)
     else:
         element = xml_Utils.getElementWithTagAttribValueMatch(
             datafile, 'system', 'default', "true")
         if element is None:
             node_value = xml_Utils.getNodeValuebyAttribute(
                 datafile, 'system', 'name')
             element = xml_Utils.getElementWithTagAttribValueMatch(
                 datafile, 'system', 'name', node_value)
     if element is not None and element is not False:
         output_dict = {}
         for item in list_my_info:
             output_dict[item] = xml_Utils.get_text_from_direct_child(
                 element, item)
         return output_dict
     else:
         msg = ("There is no project with name: '{0}' in the jira config "
                "file: '{1}'".format(system_name,
                                     "Tools/jira/jira_config.xml"))
         print_warning(msg)
         return False
    def __init__(self, details_dict=False):
        """ constructor """

        self.status = False
        if details_dict is not False:
            try:
                self.pymongo = __import__('pymongo')
                self.conn = self.connect_mongodb(details_dict)
                self.dbname = details_dict['dbname']
                if self.conn is not False:
                    # no need to check the existence of database when the
                    # purpose is to store results, new database will be
                    # created if it is not there in the server
                    if details_dict['server_type'] == 'resultservers':
                        self.status = True
                    else:
                        if self.dbname in self.conn.database_names():
                            # print_info("database - '{}' is found in MongoDB "
                            #            "server".format(self.dbname))
                            self.status = True
                        else:
                            print_warning("database - '{}' is not in MongoDB "
                                          "server".format(self.dbname))
                    self.db = self.conn[self.dbname]
            except ImportError:
                print_warning("pymongo module is not installed and Warrior "
                              "Framework uses it for establishing "
                              "connection with MongoDB server")
    def connect_mongodb(self, details_dict):
        """ Establish connection with the mongodb server.
        URI or IP/port combination is supported in mongodb config file,
        URI will have higher precedence over IP/Port """

        conn = False
        try:
            if details_dict:
                if details_dict['uri'] is not False:
                    conn = self.pymongo.MongoClient(details_dict['uri'])
                else:
                    ip = details_dict['host'] if details_dict['host'] \
                        is not False else "localhost"
                    port = details_dict['port'] if details_dict['port'] \
                        is not False else "27017"
                    conn = self.pymongo.MongoClient(ip, port)
                # This will raise ServerSelectionTimeoutError when no server
                # is available for an operation
                conn.server_info()
                # print_info("Connection to MongoDB server - '{}' is "
                #            "successful".format(details_dict['dbsystem']))
        except Exception as e:
            conn = False
            print_warning("Unable to establish connection with MongoDB server "
                          "- '{0}' : {1}".format(details_dict['dbsystem'], e))
        return conn
    def check_get_datatype(self, datafile):
        """Check and get the datatype for testcase
        """

        data_type = xml_Utils.getChildTextbyParentTag(self.filepath, 'Details',
                                                      'Datatype')
        if str(datafile).upper().strip() == 'NO_DATA':
            data_type = 'CUSTOM'
            print_debug('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
Esempio n. 6
0
    def __check_dir_exists(cls, filepath, dirtag):
        """ Verify that the directory exists in the path provided.

        Arguments:
              1. filepath: file path will be parsed as input for checking
                 directories
              2. dirtag: directory tag that used to get directory path
        """

        dirt = xml_Utils.getChildTextbyParentTag(filepath, 'Details', dirtag)
        directory = file_Utils.getAbsPath(dirt, os.path.dirname(filepath))

        if directory is not False and directory is not None:
            print_info("{0} path {1}".format(dirtag, directory))
            if not os.path.exists(directory):
                print_warning("Directory does not exist in location {0}."\
                "\nWarrior framework will try to create the directory, if creation "\
                "fails then default warriorspace will be used to collect logs/results"\
                .format(directory))
        else:
            if dirtag is 'Resultsdir':
                print_info(
                    "Default directory in Warriorspace will be used to collect results"
                )
            else:
                print_info(
                    "Default directory in Warriorspace will be used to collect logs"
                )
def wait_for_timeout(wait_time, unit="SECONDS", notify_count=4):
    """
    Warrior, Wait till the time is a generic wait. The Wait is informed to the user as a countdown.

    :Arguments:
        1.wait_time: Time for Warrior wait.
        2.unit: The unit of Time supported are
                  1. Second (default)
                  2. Minute
                  3. Hour
                  4. Day
                  5. Month (30 days is assumed for one Month)
                  6. Year (365 days is assumed for one Year)
        3.notify_count: number of times, the user needs to be notified
                        during wait time. Default value is 4.
                        Ex: If the notify_count=4 and timeout=400
                        the timeout is divided into 4 partitions
                        each as 100 and notified to user as
                        100(25%),200(50%),300(75%),400(100%)
    :return:
        Status = Bool
    """
    try:
        wait_time = float(wait_time)
        if unit.upper() in ["SECOND", "SECONDS", "SEC", "SECS"]:
            seconds = wait_time
        elif unit.upper() in ["MINUTE", "MINUTES", "MIN", "MINS"]:
            seconds = 60 * wait_time
        elif unit.upper() in ["HOUR", "HOURS"]:
            seconds = 60 * 60 * wait_time
        elif unit.upper() in ["DAY", "DAYS"]:
            seconds = 24 * 60 * 60 * wait_time
        elif unit.upper() in ["MONTH", "MONTHS"]:
            seconds = 30 * 24 * 60 * 60 * wait_time
        elif unit.upper() in ["YEAR", "YEARS"]:
            seconds = 365 * 24 * 60 * 60 * wait_time
        else:
            print_warning('The supported unit of seconds is Seconds/Minutes/Hours/Months/Years'
                          'The default unit of Seconds would be used')
        # To notify user on the wait time, based on the notify value provided,
        # Default notify value is 4
        notify_count = int(notify_count)
        notify_sec = seconds/notify_count
        print_without_logging("Wait time of {0}s will be notified every {1}s"
                              .format(seconds, notify_sec))
        for count in range(notify_count):
            print_without_logging("Remaining wait time: {:.1f}s"
                                  .format(seconds-(count*notify_sec)))
            time.sleep(notify_sec)
        print_without_logging("End of {0}s wait time".format(seconds))
        return True
    except TypeError:
        print_warning('Unable to parse wait_time value, Please use int/float as wait_time value.')
        return False
    except Exception as e:
        print_error('Encountered unexpected error {0} Unable to wait as requested'.format(e))
        return False
    def convert_arg_to_datatype(self):
        """Parses the input argument to find the data type requested by the user

        This is based on the starting letters of the argument name
        If arg_name starts with:
        1. str_ = string
        2. int_ = integer
        3. float_ = float
        4. bool_ = boolean
        5. list_ = list
        6. tuple_ = tuple
        7. dict_ = dict

        Default: if none of the above naming convention matches then the argument value
        will be treated as a string
        """
        self.datatype = None
        if self.arg_name.startswith('str_'):
            return self.arg_value
        elif self.arg_name.startswith('int_'):
            self.datatype = int
        elif self.arg_name.startswith('float_'):
            self.datatype = float
        elif self.arg_name.startswith('bool_'):
            self.datatype = bool
            if self.arg_value.lower() == "true":
                self.arg_value = "True"
            elif self.arg_value.lower() == "false":
                self.arg_value = "False"
        elif self.arg_name.startswith('list_'):
            self.datatype = list
        elif self.arg_name.startswith('tuple_'):
            self.datatype = tuple
        elif self.arg_name.startswith('dict_'):
            self.datatype = dict
        elif self.arg_name.startswith('file_'):
            self.datatype = IOBase
            tc_path = config_Utils.tc_path
            fname = file_Utils.getAbsPath(self.arg_value, tc_path)
            try:
                self.arg_value = open(fname)
            except IOError:
                print_warning("given file {} does not exist, please check, it "
                              "should be relative to testcase path {}".format(
                                  fname, tc_path))
        else:
            # User has not specified any data type with the argument, but it can be
            # given a proper type through wtag or will be treated as string (default)
            return self.arg_value
        if self.datatype is not None:
            convert_msg = "Input argument {0} will be converted to a {1}".format(
                self.arg_name, self.datatype)
            print_debug(convert_msg)

        result = self.convert_string_to_datatype()
        return result
Esempio n. 9
0
 def send_command(cls, *args, **kwargs):
     """
         Get response from the processed response dict
     """
     print_warning(
         "This method is obsolete and will be deprecated soon. Please"
         " use 'send_command' method of 'PexpectConnect' class "
         "in 'warrior/Framework/ClassUtils/WNetwork/warrior_cli_class.py'"
     )
     return MockUtils.warrior_cli_class.send_command(*args, **kwargs)
    def get_result_files(self):
        """Get execution results dir and files """

        if self.res_startdir is not None:
            try:
                if not os.path.exists(self.res_startdir):
                    print_warning(
                        "Given output dir does not exists, creating output dir at {0}"
                        .format(self.res_startdir))
                    os.makedirs(self.res_startdir)
                elif os.path.exists(self.res_startdir):
                    if not (os.access(self.res_startdir, os.R_OK)
                            and os.access(self.res_startdir, os.W_OK) and
                            os.access(self.res_startdir, os.X_OK | os.W_OK)):
                        raise Exception("Permission Denied")
            except Exception as e:
                print_error(
                    str(e) + ": Can not create an output dir " +
                    self.res_startdir)
                exit(1)
            else:
                results_execdir = file_Utils.createDir_addtimestamp(
                    self.res_startdir, self.nameonly)
                rfile = self.get_exec_file_by_type("Results", results_execdir)
        elif self.res_startdir is None:
            results_location = xml_Utils.getChildTextbyParentTag(
                self.filepath, 'Details', 'Resultsdir')

            # get default results directory
            # default_xml = Tools.__path__[0] + os.sep + 'w_settings.xml'
            default_xml = os.getenv(
                "WAR_TOOLS_DIR") + os.sep + 'w_settings.xml'
            default_resultsdir = get_credentials(default_xml, 'def_dir',
                                                 ['Resultsdir'], 'Setting')
            # use the default directory if user didn't define it in test case/test suite/project
            if results_location is None or results_location is False:
                if default_resultsdir['Resultsdir'] is not None:
                    results_location = default_resultsdir['Resultsdir']

            if results_location is None or results_location is False \
                    or str(results_location).strip() == "":
                results_execdir = self.create_def_exec_dir()  # proj_exec_dir
                rfile = self.get_exec_file_by_type("Results", results_execdir)

            elif results_location is not None and results_location is not False:
                results_location_rel = str(results_location).strip()
                results_location = file_Utils.getAbsPath(
                    results_location_rel, os.path.dirname(self.filepath))
                rfile, results_execdir = self.checkdir_create_file(
                    results_location, "Results")

        # print "printing results_execdir: ", results_execdir
        resultfile = file_Utils.getNewExtension(rfile, "xml")
        resultsdir = os.path.dirname(resultfile)
        return resultfile, resultsdir, results_execdir
def compute_status(element, status_list, impact_list, status, impact):
    """
        This function computes the overall status in case/suite/project
        execution
    """
    runmode, _, _ = get_runmode_from_xmlfile(element)
    if runmode is None:
        status_list.append(status)
        impact_list.append(impact)
    else:
        if element.find('runmode').get('status') not in [
                None, '', 'last_instance', 'expected'
        ]:
            print_warning(
                "Unsupported value for status. Please provide a valid value. "
                "Using the Default value for execution")
            element.find('runmode').set('status', '')
        if runmode.upper() == "RMT":
            status_list.append(status)
            impact_list.append(impact)
        elif runmode.upper() == "RUP":
            if element.find('runmode').get('status') is None or \
                 element.find('runmode').get('status') == '':
                status_list.append(status)
                impact_list.append(impact)
            elif element.find('runmode').get('status') == 'last_instance' or \
                    element.find('runmode').get('status') == 'expected':
                if status is True or \
                    (element.find('runmode').get('attempt') ==
                     element.find('runmode').get('runmode_val')):
                    status_list.append(status)
                    impact_list.append(impact)
        elif runmode.upper() == "RUF":
            if element.find('runmode').get('status') is None or \
                 element.find('runmode').get('status') == "":
                status_list.append(status)
                impact_list.append(impact)
            elif element.find('runmode').get('status') == 'last_instance':
                if status is False or \
                    (element.find('runmode').get('attempt') ==
                     element.find('runmode').get('runmode_val')):
                    status_list.append(status)
                    impact_list.append(impact)
            elif element.find('runmode').get('status') == 'expected':
                if status is False:
                    status_list.append(True)
                    impact_list.append(impact)
                elif status is not False and \
                    (element.find('runmode').get('attempt') ==
                     element.find('runmode').get('runmode_val')):
                    status_list.append(False)
                    impact_list.append(impact)
    return status_list, impact_list
Esempio n. 12
0
def connect_telnet(ip,
                   port="23",
                   username="",
                   password="",
                   logfile=None,
                   timeout=60,
                   prompt=".*(%|#|\$)",
                   conn_options="",
                   custom_keystroke="",
                   escape="",
                   **kwargs):
    """
    Initiates Telnet connection via a specific port. Creates log file.

    :Arguments:
        1. ip = destination ip
        2. port(string) = telnet port
        3. username(string) = username
        4. password(string) = password
        5. logfile(string) = logfile name
        6. timeout(int) = timeout duration
        7. prompt(string) = destination prompt
        8. conn_options(string) = extra arguments that will be used when
                                  sending the ssh/telnet command
        9. custom_keystroke(string) = keystroke(to be given after initial timeout)
        10. escape(string) = true/false(to set TERM as dump)

    :Returns:
        1. session_object(pexpect session object)
        2. conn_string(pre and post login message)
    """
    print_warning(
        "This method is obsolete and will be deprecated soon. Please"
        " use 'connect_telnet' method of 'PexpectConnect' class "
        "in 'warrior/Framework/ClassUtils/WNetwork/warrior_cli_class.py'")

    wc_obj = WNetwork.warrior_cli_class.WarriorCli()
    session_object, conn_string = wc_obj.connect_telnet(
        ip=ip,
        port=port,
        username=username,
        password=password,
        logfile=logfile,
        timeout=timeout,
        prompt=prompt,
        conn_options=conn_options,
        custom_keystroke=custom_keystroke,
        escape=escape)

    return session_object, conn_string
    def set_jira_issue_status(self, jiraid, status):
        """
        Change the status of the jiraid
        :Arguments:
            1. jiraid(str) - Jira issue ID
            2. status(str/boolean) - Transition status(Ex. Resolved/Closed/Reopened)
        :Returns:
            1. oper_status(Boolean) - True/False
        """
        oper_status = True
        postdata = None
        headers = {"Content-Type": "application/json"}
        issue_trans_url = self.server + '/rest/api/2/issue/' + jiraid + "/transitions"
        resp_get_trans = requests.get(issue_trans_url, auth=self.auth)
        transitions = resp_get_trans.json()['transitions']
        for trans in transitions:
            if trans["to"]["name"].lower() == status.lower():
                postdata = """
                            {
                                "transition":{
                                    "id":""" + trans["id"] + """
                                }
                            }
                            """
        if postdata is None:
            print_warning("Cannot change status to " + str(status))
            available_statuses = str(
                [trans["to"]["name"] for trans in transitions])
            print_warning(
                "The available statuses are: {}".format(available_statuses))
            oper_status = False

        if oper_status is True:
            # Change the Jira issue status
            resp_change_trans = requests.post(issue_trans_url,
                                              auth=self.auth,
                                              headers=headers,
                                              data=postdata)
            if resp_change_trans and resp_change_trans.status_code == 204:
                print_info("Successfully changed the Jira issue status to "
                           "'{0}'".format(trans["to"]["name"]))
            else:
                print_error("Error while changing Jira issue status")
                print_error("JIRA Error code: ({0}), Error message: "
                            "({1})".format(resp_change_trans.status_code,
                                           resp_change_trans.reason))
                oper_status = False

        return oper_status
def get_runtype_from_xmlfile(element):
    """Gets the runtype value of a testcase from the testsuite.xml file """

    runtype = xml_Utils.get_text_from_direct_child(element, 'runtype')
    if runtype is None or runtype is False:
        runtype = 'sequential_keywords'
    elif runtype is not None and runtype is not False:
        runtype = runtype.strip()
        supported_values = ['sequential_keywords', 'parallel_keywords']
        if runtype.lower() not in supported_values:
            print_warning("unsupported value '{0}' provided for runtype, "
                          "supported values are '{1}', case-insensitive"
                          .format(runtype, supported_values))
            print_info("Hence using default value for runtype which is 'sequential_keywords'")
            runtype = 'sequential_keywords'
    return runtype
Esempio n. 15
0
def disconnect_telnet(child):
    """Disconnects a telnet session """
    print_warning(
        "This method is obsolete and will be deprecated soon. Please"
        " use 'disconnect_telnet' method of 'PexpectConnect' class "
        "in 'warrior/Framework/ClassUtils/WNetwork/warrior_cli_class.py'")

    if isinstance(child, WNetwork.warrior_cli_class.WarriorCli):
        child = child.disconnect_telnet()
    elif isinstance(child, pexpect.spawn):
        wc_obj = WNetwork.warrior_cli_class.WarriorCli()
        wc_obj.conn_obj = WNetwork.warrior_cli_class.PexpectConnect()
        wc_obj.conn_obj.target_host = child
        wc_obj.disconnect_telnet()

    return child
def get_exectype_from_xmlfile(filepath):
    """Gets the exectype values for testcases from the testsuite.xml file """

    exectype = xml_Utils.getChildAttributebyParentTag(filepath, 'Details', 'type', 'exectype')
    if exectype is None or exectype is False:
        exectype = 'sequential_testcases'
    elif exectype is not None and exectype is not False:
        exectype = exectype.strip()
        supported_values = ['sequential_testcases', 'parallel_testcases', 'run_until_fail', 'run_multiple', 'run_until_pass', "iterative_sequential",
                            "iterative_parallel"]
        if exectype.lower() not in supported_values:
            print_warning("unsupported value '{0}' provided for exectype, "
                          "supported values are '{1}', case-insensitive"
                          .format(exectype, supported_values))
            print_info("Hence using default value for exectype which is 'sequential_testcases'")
            exectype = 'sequential_testcases'
    return exectype
    def join_thread(self, timeout=30, retry=1):
        """
        Call join method of Thread class to block caller thread until
        the current_thread terminates or until the retry counter expires
        """
        if self.current_thread is not None and retry > 0:
            try:
                self.current_thread.join(timeout)
            except Exception as err_msg:
                print_warning("Joining thread failed : {}".format(err_msg))
                self.stop_thread_err_msg += str(err_msg) + "\n"

            retry -= 1
            if self.thread_status() is True and retry > 0:
                print_warning("Thread is still alive, retry joining thread."
                              "Remaining retrial attempts: {}".format(retry))
                self.join_thread(timeout, retry)
def get_runmode_from_xmlfile(element):
    """Get 'runmode:type' & 'runmode:value' of a step/testcase from the
    testcase.xml/testsuite.xml file. Supported values - 'ruf, rup, rmt',
    these values can not be combined with other values

    Argument : The Step xml object.

    Return:
    rtype : The runmode type RUP/RUF/RMT/NONE
    rt_value : Maximum attempts value for runmode rerun
    runmode_timer : The waittime between each runmode rerun attempts
    """
    rt_type = None
    rt_value = 1
    runmode_timer = None
    runmode = element.find("runmode")
    if runmode is not None:
        rt_type = runmode.get("type").strip().upper()
        rt_value = runmode.get("value")
        runmode_timer = runmode.get("runmode_timer")
        rt_type = None if rt_type in ("", "STANDARD") else rt_type
        if rt_value is not None and rt_type is not None:
            if runmode_timer is None or runmode_timer == "":
                runmode_timer = None
            else:
                try:
                    runmode_timer = float(runmode_timer)
                except ValueError:
                    print_warning(
                        "The value for Runmode interval is {0}, please provide seconds to"
                        " wait in numerals".format(runmode_timer))
                    runmode_timer = None

            if rt_type not in ['RUF', 'RUP', 'RMT']:
                print_warning("Unsupported value '{0}' provided for 'runmode:"
                              "type' tag. Supported values : 'ruf, rup & rmt' "
                              "and these values can not be combined with other"
                              " values".format(rt_type))
                return (None, 1, None)
            try:
                rt_value = int(rt_value)

                if rt_value < 1:
                    rt_value = 1
                    print_warning("Value provided for 'runmode:value' tag "
                                  "'{0}' is less than '1', using default value"
                                  " 1 for execution".format(rt_value))
            except ValueError:
                print_warning(
                    "Unsupported value '{0}' provided for 'runmode:"
                    "value' tag, please provide an integer, using "
                    "default value '1' for execution".format(rt_value))
                rt_value = 1

    return (rt_type, rt_value, runmode_timer)
Esempio n. 19
0
def _send_cmd(obj_session, **kwargs):
    """method to send command based on the type of object """

    if isinstance(obj_session, WNetwork.warrior_cli_class.WarriorCli):
        result, response = obj_session._send_cmd(**kwargs)
    elif isinstance(obj_session, pexpect.spawn):
        wc_obj = WNetwork.warrior_cli_class.WarriorCli()
        wc_obj.conn_obj = WNetwork.warrior_cli_class.PexpectConnect()
        wc_obj.conn_obj.target_host = obj_session
        result, response = wc_obj._send_cmd(**kwargs)
    elif isinstance(obj_session, ssh_utils_class.SSHComm):
        command = kwargs.get('command')
        result, response = obj_session.get_response(command)
        print_info(response)
    else:
        print_warning('session object type is not supported')

    return result, response
Esempio n. 20
0
    def get_impact_from_xmlfile(self, element):
        """Gets the impact value of a step/testcase/suite
        from the testcase.xml/testsuite.xml/project.xml file """

        impact = self.xml_utils().get_text_from_direct_child(element, 'impact')
        if impact is None or impact is False:
            impact = 'IMPACT'
        elif impact is not None and impact is not False:
            impact = str(impact).strip()
            supported_values = ['impact', 'noimpact']
            if impact.lower() not in supported_values:
                print_warning("unsupported value '{0}' provided for impact,"\
                              "supported values are '{1}',"\
                              "case-insensitive".format(impact, supported_values))
                print_info(
                    "Hence using default value for impact which is 'impact'")
                impact = 'IMPACT'
        return impact
def main(node,
         def_on_error_action,
         def_on_error_value,
         exec_type=False,
         skip_invoked=True,
         current_step_number=None):
    """Takes a xml element (steps/step codntion / testcase/ tesuite)
    as input and return the action to be performed for failure
    conditions """

    if WarriorCliClass.mock:
        # If it is in trialmode and has error, always run next step
        return False

    error_handle = {}
    action, value = getErrorHandlingParameters(node, def_on_error_action,
                                               def_on_error_value, exec_type,
                                               current_step_number)

    call_function = {
        'NEXT': next,
        'GOTO': goto,
        'ABORT': abort,
        'ABORT_AS_ERROR': abortAsError,
        'EXECUTE_AND_RESUME': execute_and_resume
    }.get(action.upper())

    if skip_invoked:
        error_handle = call_function(action, value, error_handle)
    else:
        if value:
            print_warning(
                "Overriding on error {0}={1} since this is an Invoked "
                "Step.".format(action, value))
        else:
            print_warning(
                "Overriding on error {0} since this is an Invoked Step.".
                format(action))
        error_handle = next(action,
                            value,
                            error_handle,
                            skip_invoked=skip_invoked)
    result = get_failure_results(error_handle)
    return result
Esempio n. 22
0
    def get_context_from_xmlfile(self, element):
        """Gets the context value of a step/testcase/suite
        from the testcase.xml/testsuite.xml/project.xml file """

        context = self.xml_utils().get_text_from_direct_child(
            element, 'context')
        if context is None or context is False:
            context = 'POSITIVE'
        elif context is not None and context is not False:
            context = str(context).strip()
            supported_values = ['positive', 'negative']
            if context.lower() not in supported_values:
                print_warning("unsupported value '{0}' provided for context,"\
                              "supported values are '{1}',"\
                              "case-insensitive".format(context, supported_values))
                print_info(
                    "Hence using default value for context which is 'positive'"
                )
                context = 'POSITIVE'
        return context
Esempio n. 23
0
def get_robot_xml_files(input_list):
    """
    Find robot xml files from the list of files.
    :Arguments:
        1. input_list(list) - list of file names
    :Return:
        1. output_list(list) - list of robot xml files
    """

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

    return output_list
 def check_get_runtype(self):
     """Check and get the runtype for testcase
     """
     if xml_Utils.nodeExists(self.filepath, 'Runtype'):
         run_type = xml_Utils.getChildTextbyParentTag(
             self.filepath, 'Details', 'Runtype')
         if run_type is not None and run_type is not False:
             run_type = str(run_type).strip()
             supported_values = ['sequential_keywords', 'parallel_keywords']
             if run_type.lower() not in supported_values:
                 print_warning("unsupported value '{0}' provided for run_type,"
                               "supported values are " \
                               "'{1}' and case-insensitive".format(run_type, supported_values))
                 print_info(
                     "Hence using default value for run_type which is 'sequential_keywords'"
                 )
                 run_type = 'SEQUENTIAL_KEYWORDS'
     else:
         run_type = "SEQUENTIAL_KEYWORDS"
     return run_type
def compute_runmode_status(global_status_list, runmode, global_xml):
    """ Computes the status of runmode execution when runmode is provided in
       global level (Details section)
    """
    if global_xml.find('runmode').get('status') not in [
            None, '', 'last_instance', 'expected'
    ]:
        print_warning(
            "Unsupported value for status. Please provide a valid value. "
            "Using the Default value for execution")
        global_xml.find('runmode').set('status', '')
    if global_xml.find('runmode').get('status') is None or \
        global_xml.find('runmode').get('status') == "" or \
            runmode.upper() == "RMT":
        if "FALSE" in global_status_list or False in global_status_list:
            status_value = False
        elif "RAN" in global_status_list:
            status_value = "RAN"
        elif "ERROR" in global_status_list:
            status_value = "ERROR"
        else:
            status_value = True
    elif runmode.upper() == "RUP":
        if global_xml.find('runmode').get('status') == 'last_instance':
            status_value = global_status_list.pop()
        elif global_xml.find('runmode').get('status') == 'expected' and \
            (global_status_list[-1] is True or
             global_status_list[-1] == "TRUE"):
            status_value = True
        else:
            status_value = global_status_list.pop()
    elif runmode.upper() == "RUF":
        if global_xml.find('runmode').get('status') == 'last_instance':
            status_value = global_status_list.pop()
        elif global_xml.find('runmode').get('status') == 'expected' and \
            (global_status_list[-1] is False or
             global_status_list[-1] == "FALSE"):
            status_value = True
        else:
            status_value = global_status_list.pop()
    return status_value
Esempio n. 26
0
    def get_defonerror_fromxml_file(self, filepath):
        """Gets the default on error value of a step/testcase/suite
        from the testcase.xml/testsuite.xml/project.xml file """

        def_on_error_action = self.xml_utils().getChildAttributebyParentTag(filepath, 'Details',\
                                                                     'default_onError', 'action')

        if def_on_error_action is None or def_on_error_action is False:
            def_on_error_action = 'NEXT'

        elif def_on_error_action is not None and def_on_error_action is not False:
            supported_values = ['next', 'goto', 'abort', 'abort_as_error']
            if not str(def_on_error_action).lower() in supported_values:
                print_warning("unsupported option '{0}' provided for default_onError"\
                              "action, supported values are {1}".format(def_on_error_action,
                                                                        supported_values))
                print_info(
                    "Hence using default value for default_onError action which is 'next'"
                )
                def_on_error_action = 'NEXT'
        return def_on_error_action
def create_defects(auto_defects, data_repository):
    """Creates the defects json files for the testcase executed
    If auto_defects = True create bugs in jira for the associated project provided in jira
    config file
    """
    defect_obj = DefectsDriver(data_repository)
    json_status = defect_obj.create_failing_kw_json()

    if json_status:
        if auto_defects:
            print_info("auto-create defects ")
            defects_json_list = defect_obj.get_defect_json_list()
            if len(defects_json_list) == 0:
                print_warning("No defect json files found in defects directory '{0}' of this "
                              "testcase".format(data_repository['wt_defectsdir']))
            elif len(defects_json_list) > 0:
                connect = defect_obj.connect_warrior_jira()
                if connect is True:
                    defect_obj.create_jira_issues(defects_json_list)
        else:
            print_info("auto-create defects was Not requested")
Esempio n. 28
0
    def get_setup_on_error(self, filepath):
        """Gets the setup on error value
        from the wrapperfile.xml file """

        setup_on_error_action = self.xml_utils().getChildAttributebyParentTag(filepath, 'Details',\
                                                                     'setup_onError', 'action')

        if setup_on_error_action is None or setup_on_error_action is False:
            setup_on_error_action = 'abort'

        elif setup_on_error_action is not None and setup_on_error_action is not False:
            supported_values = ['next', 'abort']
            if not str(setup_on_error_action).lower() in supported_values:
                print_warning("unsupported option '{0}' provided for setup_onError"\
                              "action, supported values are {1}".format(setup_on_error_action,
                                                                        supported_values))
                print_info(
                    "Hence using default value for setup_onError action which is 'abort'"
                )
                setup_on_error_action = 'abort'
        return setup_on_error_action
Esempio n. 29
0
    def check_url(self, url):
        """
        To check whether the user provided url is valid or not.

        DISCLAIMER: This function internally opens the url to assert the validity of the url.

        Returns:
            1. status(bool)= True / False.(Whether the url can be reached)
            2. url : The actual url itself
        """
        status = True
        try:
            url_open = urllib.request.urlopen(url)
            get_status_code = url_open.code
            pattern = re.compile('^2[0-9][0-9]$')
            if not pattern.match(
                    str(get_status_code)) and get_status_code is not None:
                print_info("The Status code for url : {} is {}".format(
                    url, get_status_code))
                status = False
        except urllib.error.HTTPError as http_error:
            print_warning("URLError: {} reason: ({}) status code: {}".format(
                url, http_error.reason, http_error.code))
            status = False
        except urllib.error.URLError as url_err:
            status = False
            print_warning("URLError: {} reason: ({})".format(
                url, url_err.reason))
        except Exception as err:
            print_warning("Exception: {0}".format(err))
            status = False
        return status, url
Esempio n. 30
0
def send_command(session_object,
                 start_prompt,
                 end_prompt,
                 command,
                 timeout=60):
    """
    Sends command to warrior_cli_class session object(pexpect/paramiko)
    and returns the status of the command sent.
    - Checks for the availability of the start_prompt.
    - if start prompt was available sends the command
    - if failure response is not None and failure response found in
    response then returns False.
    - else if failure response was not found
    and end prompt also not found returns False.
    - else if failure response was not found and end prompt found,
    then returns true.
    """
    print_warning(
        "This method is obsolete and will be deprecated soon. Please"
        " use 'send_command' method of 'PexpectConnect' class "
        "in 'warrior/Framework/ClassUtils/WNetwork/warrior_cli_class.py'")

    if isinstance(session_object, WNetwork.warrior_cli_class.WarriorCli):
        status, response = session_object.send_command(start_prompt,
                                                       end_prompt, command,
                                                       timeout)
    elif isinstance(session_object, pexpect.spawn):
        wc_obj = WNetwork.warrior_cli_class.WarriorCli()
        wc_obj.conn_obj = WNetwork.warrior_cli_class.PexpectConnect()
        wc_obj.conn_obj.target_host = session_object
        status, response = wc_obj.send_command(start_prompt, end_prompt,
                                               command, timeout)
    else:
        status, response = "ERROR", ""
        print_warning(
            "Unable to send the command since the session_object is not an "
            "instance of warrior_cli_class, status will be marked as ERROR. "
            "Please use warrior_cli_class for session establishment.")

    return status, response