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 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 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_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
Example #4
0
def main(node, def_on_error_action, def_on_error_value, exec_type=False, skip_invoked=True):
    """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)

    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
Example #5
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
    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"
                )
Example #7
0
    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
Example #8
0
    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 getErrorHandlingParameters(node, def_on_error_action, def_on_error_value, exec_type):
    """Takes a xml element at input and returns the values for on_error action , value
    If no value is available in the node then returns the default values """

    if exec_type:
        exec_node = node.find('Execute')
        def_on_error_action = 'NEXT'
        def_on_error_value = ''
        ex_rule_param = exec_node.find('Rule').attrib
        action = ex_rule_param['Else']
        if ex_rule_param['Else'].upper() == 'GOTO':
            value = ex_rule_param['Elsevalue']
        else:
            value = ''

    else:
        action = Utils.xml_Utils.get_attributevalue_from_directchildnode(node, 'onError', 'action')
        value = Utils.xml_Utils.get_attributevalue_from_directchildnode(node, 'onError', 'value')

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

    elif action is not None and action is not False:
        supported_values = ['next', 'goto', 'abort', 'abort_as_error']
        action = str(action).strip()
        if action.lower() not in supported_values:
            print_warning("unsupported option '{0}' provided for onError action, supported values are {1}".format(action, supported_values))
            print_info("Hence using default_onError action")
            action = def_on_error_action

    if value is None or value is False:
        value = def_on_error_value

    return action, value
Example #10
0
    def inner(*args, **kwargs):
        """
            Call corresponding mock method
        """
        # If warrior is not in mock or sim mode
        # or if warrior is in sim mode but it's a VERIFY_ONLY function
        # return the original function
        from WarriorCore.Classes.war_cli_class import WarriorCliClass
        if (not WarriorCliClass.mock and not WarriorCliClass.sim) or\
           (WarriorCliClass.sim and func.__name__ in VERIFY_ONLY):
            return func(*args, **kwargs)

        # If warrior is in simulator mode, this function will also parse the simresp
        # and parse response file
        if func.__name__ == "get_command_details_from_testdata":
            if WarriorCliClass.sim and args[0] is not None and args[0] != "":
                from Framework.Utils.data_Utils import cmd_params
                cmd_params.update({"sim_response_list": "simresp"})
                get_response_file(args[0])
            return func(*args, **kwargs)

        # link the command with its simresp value into a dict
        if func.__name__ == "_get_cmd_details":
            result = func(*args, **kwargs)
            pNote("The non-substituted commands:")
            for index, cmd in enumerate(result["command_list"]):
                pNote("#{}: {}".format(index + 1, cmd))
                if WarriorCliClass.sim:
                    if cmd in MockUtils.cli_Utils.response_reference_dict and \
                        MockUtils.cli_Utils.response_reference_dict[cmd] is not None:
                        pNote("Command: {} is already linked to simresp: {}"\
                              .format(cmd, MockUtils.cli_Utils.response_reference_dict[cmd]))
                    else:
                        MockUtils.cli_Utils.response_reference_dict[cmd] = \
                        result["sim_response_list"][index]
            return result

        # Print extra info
        # pNote("Util {} is mocked".format(func.__name__), "WARNING")
        # for value in [str(x) + ": " + str(y) for x, y in zip(inspect.getargspec(func)[0], args)]:
        #     pNote(value)
        # for key, value in kwargs.items():
        #     pNote(str(key) + ": " + str(value))

        # mapping function to mocked function
        func_name = func.__name__
        func_module = func.__module__.split(".")[-1]
        if func_module in dir(MockUtils):
            func_module = getattr(MockUtils, func_module)
            if func_name in dir(func_module):
                function = getattr(func_module, func_name)
            else:
                print_warning("Cannot locate {} in {}".format(
                    func_name, dir(func_module)))
                function = func
        else:
            print_warning("Cannot locate {} in {}".format(
                func_module, dir(MockUtils)))
            function = func
        return function(*args, **kwargs)
Example #11
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 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_info(convert_msg)

        result = self.convert_string_to_datatype()
        return result
def wait_for_timeout(wait_time, unit="SECONDS"):
    """
    Warrior, Wait till the time is a generic wait. The Wait is informed to the user in 10 intervals
    equally divided from the over all wait.

    :param wait_time: Time for Warrior wait.
    :param 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)
    :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')
        print_info('Starting to wait for {} Seconds'.format(seconds))
        wait_seconds = seconds
        print_interval = wait_seconds / 10
        print_info('Remaining wait time will be notified every {} secs'.format(
            print_interval))
        for count in range(10):
            print_info('Remaining Wait Time is {:.1f} seconds'.\
                format(wait_seconds-count*print_interval))
            time.sleep(print_interval)
        print_info('Ending Wait time of {} Seconds'.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 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
Example #15
0
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
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
Example #17
0
def disconnect(child):
    """
    - Disconnects a pexpect session
    - Returns session object(same child)
    """
    print_warning("This method is obsolete and will be deprecated soon. Please"
                  " use 'disconnect' method of 'PexpectConnect' class "
                  "in 'warrior/Framework/ClassUtils/warrior_connect_class.py'")

    if child.isalive():
        if child.ignore_sighup:
            child.ignore_sighup = False
        child.close()
    return child
Example #18
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/warrior_connect_class.py'")

    time.sleep(2)
    child.sendcontrol(']')
    time.sleep(2)
    child.expect('telnet> ')
    time.sleep(2)
    child.sendline('q')
    time.sleep(2)
    child.close()
    return child
Example #19
0
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 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
Example #21
0
    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 == "" or rt_type == "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)
Example #23
0
 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
Example #24
0
    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
Example #25
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 _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
def get_steps_list(testcase_filepath):
    """Takes the location of any Testcase xml file as input
    Returns a list of all the step elements present in the Testcase

    :Arguments:
        1. testcase_filepath    = full path of the Testcase xml file
    """
    step_list = []
    root = Utils.xml_Utils.getRoot(testcase_filepath)
    Steps = root.find('Steps')
    if Steps is None:
        print_warning("Case: '{}' has no Steps/Keywords "
                      "to be executed".format(testcase_filepath))
    else:
        step_list = []
        new_step_list = Steps.findall('step')
        #execute step multiple times
        for index, step in enumerate(new_step_list):
            runmode, value = common_execution_utils.get_runmode_from_xmlfile(
                step)
            retry_type, _, _, retry_value, _ = common_execution_utils.get_retry_from_xmlfile(
                step)
            if runmode is not None and value > 0:
                go_next = len(step_list) + value + 1
                for i in range(0, value):
                    copy_step = copy.deepcopy(step)
                    copy_step.find("runmode").set("value", go_next)
                    copy_step.find("runmode").set("attempt", i + 1)
                    step_list.append(copy_step)
            if retry_type is not None and retry_value > 0:
                go_next = len(step_list) + retry_value + 1
                if runmode is not None:
                    get_runmode = step.find('runmode')
                    step.remove(get_runmode)
                for i in range(0, retry_value):
                    copy_step = copy.deepcopy(step)
                    copy_step.find("retry").set("count", go_next)
                    copy_step.find("retry").set("attempt", i + 1)
                    step_list.append(copy_step)
            if retry_type is None and runmode is None:
                step_list.append(step)
        return step_list
def get_robot_xml_files(input_list):
    """
    Find robot xml files from the list of files.
    :Arguments:
        1. input_list(list) - list of file names
    :Return:
        1. output_list(list) - list of robot xml files
    """

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

    return output_list
Example #29
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
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")