def get_time_delta(self, start_time, end_time=None, time_diff="time_diff"):
        """Returns time difference between two timestamps in seconds.
           :Arguments:
                1. start_time = start time key in the data repository,
                                  value should be datetime object in data repo.
                                  Ex: 'timestamp1'

                2. end_time(optional) = end time key in the data repository,
                                          value should be datetime object in data repo.
                                          Ex: 'timestamp2'

                  3. time_diff(optional) = time diff key in the data repository

           :Returns:
                  1. status(boolean)
                  2. time_diff (dict element) : name = time_diff, value = difference between the
                     given start time and end time in seconds (ex: 212342.0)

        """
        wdesc = "To get time difference between two timestamps"
        Utils.testcase_Utils.pNote(wdesc)
        start_time = Utils.data_Utils.get_object_from_datarepository(
            start_time)
        if end_time:
            end_time = Utils.data_Utils.get_object_from_datarepository(
                end_time)
        time_delta = datetime_utils.get_time_delta(start_time=start_time,
                                                   end_time=end_time)
        print_info(
            "delta between given timestamps : {0} seconds".format(time_delta))
        output_dict = {time_diff: time_delta}
        status = True
        return status, output_dict
    def generate_timestamp_delta(self, stored_delta_key, timestamp_key,
                                 desired_status):
        """
            test keyword created for runmode_timer
            Generate a delta from comparing current time with store timestamp
            save the delta and current timestamp in repo for keyword verify_delta
        :Argument:
            stored_delta_key = key name to store the list of delta
            timestamp_key = key name to store the timestamp
            desired_status = user desired status
                input pass->true, fail->false and everything else ->exception
        """
        cur_ts = datetime_utils.get_current_timestamp()
        result_dict = {timestamp_key: cur_ts}
        status = self.local_data_test(desired_status)

        previous_time = data_Utils.get_object_from_datarepository(
            timestamp_key)
        stored_delta = data_Utils.get_object_from_datarepository(
            stored_delta_key)
        if previous_time:
            delta = datetime_utils.get_time_delta(previous_time, cur_ts)
            if stored_delta:
                stored_delta.append(delta)
                result_dict.update({stored_delta_key: stored_delta})
            else:
                result_dict.update({stored_delta_key: [delta]})
        return status, result_dict
Exemple #3
0
    def get_time_delta(self, start_time, end_time=None, time_diff="time_diff", max_time_diff=None):
        """Returns time difference between two timestamps in seconds.
           :Arguments:
                1. start_time = start time key in the data repository,
                                  value should be datetime object in data repo.
                                  Ex: 'timestamp1'

                2. end_time(optional) = end time key in the data repository,
                                          value should be datetime object in data repo.
                                          Ex: 'timestamp2'

                3. time_diff(optional) = time diff key in the data repository

                4. max_time_diff(optional) = maximum cutoff time.

           :Returns:
                  1. status(boolean)
                  2. time_diff (dict element) : name = time_diff, value = difference between the
                     given start time and end time in seconds (ex: 212342.0)

        """
        wdesc = "To get time difference between two timestamps"
        Utils.testcase_Utils.pNote(wdesc)
        start_time = Utils.data_Utils.get_object_from_datarepository(start_time)
        if end_time:
            end_time = Utils.data_Utils.get_object_from_datarepository(end_time)
        time_delta = datetime_utils.get_time_delta(start_time=start_time, end_time=end_time)
        print_info("delta between given timestamps : {0} seconds".format(time_delta))
        output_dict = {time_diff: time_delta}
        if max_time_diff:
            if time_delta > int(max_time_diff):
                print_error("The time difference is greater than max time difference so failing the step !")
                status = False
                return status, output_dict
        status = True
        return status, output_dict
Exemple #4
0
def send_command(session_object,
                 start_prompt,
                 end_prompt,
                 command,
                 timeout=60):
    """
    Send an command to pexpect session object and resturns 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 fond in
    response then returns False.
    - else if failure repsonse 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/warrior_connect_class.py'")

    tmout = {None: 60, "": 60, "none": 60}.get(timeout, str(timeout).lower())
    session_object.timeout = int(tmout)
    pNote("Command timeout: {0}".format(session_object.timeout))
    response = ""
    msg = ""
    end_time = False
    status = False
    cmd_timedout = False
    #time_format = "%Y-%b-%d %H:%M:%S"
    try:
        boolprompt = session_object.expect(start_prompt)
    except Exception as exception:
        pNote(
            "Could not find the start_prompt '{0}'!! exiting!!".format(
                str(start_prompt)), "error")
        boolprompt = -1
    if boolprompt == 0:
        start_time = datetime_utils.get_current_timestamp()
        pNote("[{0}] Sending Command: {1}".format(start_time, command))
        _send_cmd_by_type(session_object, command)
        try:
            while True:
                result = session_object.expect([end_prompt, pexpect.EOF, pexpect.TIMEOUT]) if end_prompt\
                else -1
                end_time = datetime_utils.get_current_timestamp()
                if result == 0:
                    curr_time = datetime_utils.get_current_timestamp()
                    msg1 = "[{0}] Command completed successfully".format(
                        end_time)
                    msg2 = "[{0}] Found end prompt '{1}' after command had timed out".format(
                        curr_time, end_prompt)
                    status = {True: "ERROR", False: True}.get(cmd_timedout)
                    msg = {True: msg2, False: msg1}.get(cmd_timedout)
                    break
                elif result == -1:
                    pNote("[{0}] end prompt not provided".format(end_time),
                          "error")
                    status = "ERROR"
                    break
                elif result == 1:
                    msg = "[{0}] EOF encountered".format(end_time)
                    status = "ERROR"
                    break
                elif result == 2:
                    tmsg1 = "[{0}] Command timed out, command will be marked as error".format(
                        end_time)
                    tmsg2 = "Will wait 60 more seconds to get end prompt '{0}'".format(
                        end_prompt)
                    tmsg3 = "Irrespective of whether end prompt is received or not command will "\
                           "be marked as error because command had timed out once."
                    if not cmd_timedout:
                        session_object.timeout = 1
                        pNote(tmsg1, "debug")
                        pNote(tmsg2, "debug")
                        pNote(tmsg3, "debug")
                        tstamp = datetime_utils.get_current_timestamp()
                    cmd_timedout = True
                    status = "ERROR"
                    tdelta = datetime_utils.get_time_delta(tstamp)
                    if int(tdelta) >= 60:
                        msg = "[{0}] Did not find end prompt '{1}' even after 60 seconds post"\
                              "command time out".format(datetime_utils.get_current_timestamp(),
                                                        end_prompt)
                        break
                    else:
                        continue
        except Exception as exception:
            print_exception(exception)
        else:
            response = session_object.before
            response = str(response) + str(session_object.after)
            if session_object.env is not None and 'TERM' in session_object.env and session_object.env[
                    'TERM'] == 'dumb':
                escape_seq = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
                response = escape_seq.sub('', response)
            pNote("Response:\n{0}\n".format(response))
            pNote(msg, "debug")
            if status is True:
                duration = datetime_utils.get_time_delta(start_time, end_time)
                pNote("Command Duration: {0} sec".format(duration))
    return status, response
def create_case_junit(robot_tests):
    """ Add robot test results into Warrior Junit XML object
    :Argument:
        1. robot_tests(list) - Robot test xml elements
    """

    data_repository = config_Utils.data_repository
    tc_junit_object = data_repository['wt_junit_object']
    for test_elem in robot_tests:
        test_name = test_elem.get('name')

        tc_start_time = xml_Utils.get_attributevalue_from_directchildnode(
         test_elem, 'status', 'starttime')
        tc_start_time = datetime.datetime.strptime(
         tc_start_time, "%Y%m%d %H:%M:%S.%f").replace(microsecond=0)
        tc_timestamp = str(tc_start_time)
        tc_end_time = xml_Utils.get_attributevalue_from_directchildnode(
         test_elem, 'status', 'endtime')
        tc_end_time = datetime.datetime.strptime(
         tc_end_time, "%Y%m%d %H:%M:%S.%f").replace(microsecond=0)
        tc_duration = datetime_utils.get_time_delta(tc_start_time, tc_end_time)
        tc_status = xml_Utils.get_attributevalue_from_directchildnode(test_elem, 'status','status')

        tc_junit_object.create_testcase(location="from testsuite", timestamp=tc_timestamp,
                                        ts_timestamp=data_repository['wt_ts_timestamp'],
                                        classname=data_repository['wt_suite_name'],
                                        name=test_name,
                                        testcasefile_path=data_repository['wt_testcase_filepath'])
        tc_junit_object.add_property("resultsdir",
                                     os.path.dirname(data_repository['wt_resultsdir']),
                                    "tc", tc_timestamp)
        tc_junit_object.add_property("logsdir", os.path.dirname(data_repository['wt_logsdir']),
                                    "tc", tc_timestamp)
        tc_junit_object.update_attr("title", test_name, "tc", tc_timestamp)

        string_status = {"PASS": "******", "FAIL": "FALSE"}
        # Convert robot test results
        if str(tc_status).upper() in list(string_status.keys()):
            tc_status = string_status[str(tc_status).upper()]
        tc_junit_object.update_count(tc_status, "1", "ts", data_repository['wt_ts_timestamp'])
        tc_junit_object.update_count("tests", "1", "ts", data_repository['wt_ts_timestamp'])
        tc_junit_object.update_count("tests", "1", "pj", "not appicable")
        tc_junit_object.update_attr("status", str(tc_status), "tc", tc_timestamp)
        tc_junit_object.update_attr("time", str(tc_duration), "tc", tc_timestamp)
        tc_junit_object.add_testcase_message(tc_timestamp, tc_status)

        keywords = test_elem.getchildren()
        step_num = 1
        for kw_elem in keywords:
            if kw_elem.tag == "kw":
                kw_name = kw_elem.get('name')
                kw_start_time = xml_Utils.get_attributevalue_from_directchildnode(
                 kw_elem, 'status', 'starttime')
                kw_start_time = datetime.datetime.strptime(
                 kw_start_time, "%Y%m%d %H:%M:%S.%f").replace(microsecond=0)
                kw_end_time = xml_Utils.get_attributevalue_from_directchildnode(
                 kw_elem, 'status', 'endtime')
                kw_end_time = datetime.datetime.strptime(
                 kw_end_time, "%Y%m%d %H:%M:%S.%f").replace(microsecond=0)
                kw_duration = datetime_utils.get_time_delta(kw_start_time, kw_end_time)

                kw_status = xml_Utils.get_attributevalue_from_directchildnode(
                 kw_elem, 'status', 'status')

                kw_desc = xml_Utils.get_text_from_direct_child(kw_elem, 'doc')
                if kw_desc is False:
                    kw_desc = "No doc/desc provided"

                # Convert robot keyword results
                if str(kw_status).upper() in list(string_status.keys()):
                    kw_status = string_status[str(kw_status).upper()]

                add_keyword_result(tc_junit_object, tc_timestamp, step_num,
                                   kw_name, kw_status, kw_start_time,
                                   kw_duration, "skipped", "Impact", "Next", kw_desc)
                step_num += 1