Esempio n. 1
0
 def close(self, system_name=None, external_system=None, external_system_session=None):
     """
     close the gnmi streaming or polling
     :param system_name:
     :param external_system:
     :param external_system_session:
     :return:
     """
     status = False
     if system_name:
         __gnmi_obj = data_Utils.get_object_from_datarepository(str(system_name)+"_gnmi_session")
         if __gnmi_obj:
             gnmi_obj = __gnmi_obj
         else:
             gnmi_obj = None
     else:
         session_id = data_Utils.get_session_id(external_system, external_system_session)
         gnmi_obj = data_Utils.get_object_from_datarepository(session_id)
     gnmi_obj.sendcontrol('C')
     try:
         gnmi_obj.expect([pexpect.EOF, '.*(%|#|\$)'], timeout=2)
     except:
         testcase_Utils.pNote("Sending Ctrl+C")
     if "client had error while displaying results" not in gnmi_obj.before:
         if system_name:
             result = gnmi_obj.before.strip().strip("^C")
             testcase_Utils.pNote(result)
         else:
             result = gnmi_obj.after.strip().strip("^C")
             testcase_Utils.pNote(result)
         status = True
     return status, result
Esempio n. 2
0
 def scp_client_ca(self, cmd_string, passwd, external_system=None, external_system_session=None):
     """
     Perform scp/sftp operation
     :param cmd_string: scp/sftp command string
     :param passwd: remote system password
     :param external_system: external system mentioned in the data file
     :param external_system_session: external system session if any
     :return: True or False
     """
     status = False
     if external_system == None:
         child = pexpect.spawn(cmd_string)
     else:
         session_id = data_Utils.get_session_id(external_system, external_system_session)
         child = data_Utils.get_object_from_datarepository(session_id)
         child.sendline(cmd_string)
     while 1:
         try:
             u_index = child.expect(['password', 'Permission denied', pexpect.EOF,
                                     'want to continue connecting', '.*100%.*(%|#|\$)',
                                     'Connection reset by peer', pexpect.TIMEOUT], timeout=20)
             if u_index == 0:
                 child.sendline(passwd)
                 testcase_Utils.pNote(child.before+child.match.group(0))
             if u_index == 1:
                 status = False
                 testcase_Utils.pNote(child.before+child.match.group(0)+child.after)
                 break
             if u_index == 2:
                 testcase_Utils.pNote(child.before)
                 if "100%" in child.before:
                     status = True
                 break
             if u_index == 4:
                 testcase_Utils.pNote(child.before+child.match.group(0))
                 if "100%" in child.before+child.match.group(0):
                     status = True
                 break
             if u_index == 3:
                 testcase_Utils.pNote(child.before+child.match.group(0)+child.after)
                 child.sendline('yes')
             if u_index == 5:
                 testcase_Utils.pNote(child.before+child.match.group(0))
                 status = False
                 break
         except:
             testcase_Utils.pNote("File Copy Failed", "error")
             status = False
             break
     if status:
         testcase_Utils.pNote("Client certificate copied Successfully.")
     else:
         testcase_Utils.pNote("Client certificate copy Failed.", "error")
     return status
Esempio n. 3
0
def _get_obj_session(details_dict, obj_session, kw_system_name, index):
    """If system name is provided in testdata file
    get the session of that system name and use it or
    use the current obj_session"""

    value = False
    kw_system_nameonly, _ = data_Utils.split_system_subsystem(kw_system_name)
    td_sys = details_dict["sys_list"][index]
    # To get the session name if it is provided as part of sys tag in td
    td_sys_split = td_sys.split('.') if isinstance(td_sys, str) else []
    if len(td_sys_split) == 2:
        td_sys = td_sys_split[0]
        session = td_sys_split[1]
    else:
        session = details_dict["session_list"][index]

    td_sys = td_sys.strip() if isinstance(td_sys, str) else td_sys
    td_sys = {None: False, False: False, "": False}.get(td_sys, td_sys)
    session = session.strip() if isinstance(session, str) else session
    session = {None: None, False: None, "": None}.get(session, session)
    if td_sys:
        system_name = kw_system_nameonly + td_sys if td_sys.startswith("[") \
        and td_sys.endswith("]") else td_sys
        session_id = data_Utils.get_session_id(system_name, session)
        obj_session = data_Utils.get_object_from_datarepository(session_id)
        if not obj_session:
            pNote("Could not find a valid connection for "\
                  "system_name={}, session_name={}".format(system_name, session), "error")
            value = False
        else:
            value = obj_session
            # details_dict =
            # _update_details_dict(system_name, datafile, details_dict, var_sub)

    else:
        # print obj_session
        value = obj_session
        system_name = kw_system_name

    pNote("System name\t: {0}".format(system_name))

    if details_dict["sys_list"][index] is not None:
        kw_system_name = details_dict["sys_list"][index]

    return value, kw_system_name, details_dict
Esempio n. 4
0
def start_threads(started_thread_for_system, thread_instance_list, same_system,
                  unique_log_verify_list, system_name):
    """ This function iterates over unique_log_verify_list which consists of unique values
    gotten from monitor attributes and verify_on attributes

    If a system_name has a * against it, it indicates that the system is the
    same as the one on which the testcase is running. Thread would not be
    started for that system.

    :Returns:

    started_thread_for_system (list[str]) = Stores the system names for which
    threads were succesfully created

    thread_instance_list (list[str]) = stores the instances of thread created
    for corresponding system in the started_thread_for_system list,

    same_system (list[str]) = stores the system name which was the same as the
    system on which the TC is running without the trailing *,

    """
    started_thread_for_system = []
    thread_instance_list = []
    same_system = []
    for i in range(0, len(unique_log_verify_list)):
        if unique_log_verify_list[i] == system_name:
            temp_list = unique_log_verify_list[i].split(".")
            if len(temp_list) > 1:
                unique_log_verify_list[i] = data_Utils.get_session_id(
                    temp_list[0], temp_list[1])
            else:
                unique_log_verify_list[i] = data_Utils.get_session_id(
                    temp_list[0])
            same_system.append(unique_log_verify_list[i])
        else:
            if unique_log_verify_list[i]:
                temp_list = unique_log_verify_list[i].split(".")
                if len(temp_list) > 1:
                    unique_log_verify_list[i] = data_Utils.get_session_id(
                        temp_list[0], temp_list[1])
                else:
                    unique_log_verify_list[i] = data_Utils.get_session_id(
                        temp_list[0])
                datarep_obj = get_object_from_datarepository(
                    unique_log_verify_list[i])
                if datarep_obj is False:
                    print_info("{0} does not exist in data repository".format(
                        unique_log_verify_list[i]))
                else:
                    try:
                        new_thread = ThreadedLog()
                        new_thread.start_thread(datarep_obj)
                        print_info("Collecting response from: {0}".format(
                            unique_log_verify_list[i]))
                        started_thread_for_system.append(
                            unique_log_verify_list[i])
                        thread_instance_list.append(new_thread)
                    except:
                        print_info(
                            "Unable to collect response from: {0}".format(
                                unique_log_verify_list[i]))
    return started_thread_for_system, thread_instance_list, same_system
Esempio n. 5
0
    def execute_robot_wrapper(self, system_name, session_name=None):
        """
        This keyword is to execute python scripts which internally calls robot scripts.
        :Arguments:
            1. system_name(string) - Name of the system/subsystem in the datafile
            2. session_name(string) - name of the session to the system
        :Returns:
            1. status(bool)= True/False
        :Datafile usage:
            Tags or attributes to be used in input datafile for the system/subsystem
            If both tag and attribute is provided the attribute will be used
            1. ip = IP address of the system where the python script will be executed
                Default value for ip type is ip, it can take any type of ip's
                to connect to (like ipv4, ipv6, dns etc)
                Users can provide tag/attribute for any ip_type under the
                system in the input datafile and specify the tag/attribute name
                as the value for ip_type argument, then the connection will be
                established using that value
            2. username = username for the session
            3. password = password for the session
            4. end_prompt = prompt expected when the command(python script) execution
                is successful, default value: .*(%|#|\$).
            5. remote = 'yes' when executed in remote system & 'no'(default)
                when executed in local system
            6. file_path = path of the python script to be executed
            7. output_dir = directory path used as outputdir for robot scripts
               available in the python script(in execution machine). All the
               Robot tests listed in the Python script should have same output directory.
            8. local_output_dir = path of the directory in the local system
                where the robot output files from remote system will be copied.
                If this tag is not available or left empty, results will be
                stored in 'home/<username>/robot_wrapper_opdir' directory.
            Note: Tags 1,2,3 & 8 are only required to copy the results from
             remote to local system  when remote(5) argument is set to 'yes'.
        """

        session_id = get_session_id(system_name, session_name)
        session_object = get_object_from_datarepository(session_id)

        credentials = get_credentials(self.datafile, system_name, [
            'ip', 'username', 'password', 'end_prompt', 'remote', 'file_path',
            'output_dir', 'local_output_dir'
        ])

        if not credentials['file_path'] or not credentials['output_dir']:
            pNote(
                "Please provide values for 'file_path & output_dir' "
                "tags in input data_file", 'warning')
            return False

        if credentials['end_prompt']:
            prompt = credentials['end_prompt']
        else:
            prompt = ".*(%|#|\$)"

        data_directory = os.path.dirname(self.datafile)
        abs_filepath = getAbsPath(credentials['file_path'], data_directory)
        abs_output_dir = getAbsPath(credentials['output_dir'], data_directory)

        current_time = time.time()
        if os.path.isfile(abs_filepath):
            command = "python " + abs_filepath
            status = session_object.send_command(".*", prompt, command)[0]
            if status is True:
                pNote("Robot_wrapper script: '{}' execution is successful".
                      format(abs_filepath))
            else:
                pNote(
                    "Robot_wrapper script: '{}' execution failed".format(
                        abs_filepath), 'warning')
        else:
            pNote(
                "Robot_wrapper script: '{}' does not exist".format(
                    abs_filepath), 'warning')
            status = False

        # When executed in remote machine
        if credentials['remote'] and credentials['remote'].upper() == "YES":

            if credentials['local_output_dir']:
                local_output_dir = getAbsPath(credentials['local_output_dir'],
                                              data_directory)
            else:
                local_output_dir = "~/robot_wrapper_opdir"
            get_file_from_remote_server(credentials['ip'],
                                        credentials['username'],
                                        credentials['password'],
                                        abs_output_dir, local_output_dir)
            abs_output_dir = local_output_dir + os.sep + os.path.basename(
                abs_output_dir)
        # Get the modified xml files in the output_dir
        modified_list = get_modified_files(abs_output_dir, current_time,
                                           ".xml")
        # Get the robot xml files from the modified list of files
        robot_xml_list = robot_wrapper_utils.get_robot_xml_files(modified_list)
        # Get results from robot xml files
        robot_test_results = robot_wrapper_utils.get_results_from_robot_xml(
            robot_xml_list)
        # Create junit for robot tests
        robot_wrapper_utils.create_case_junit(robot_test_results)

        return status
Esempio n. 6
0
 def execute(self, binary, cmd_string, uname, passwd, prompt, external_system=None,
             external_system_session=None, stop_after=None, gnmi_obj=None, script="No"):
     """
     Execute gnmi command using gnmi binary
     :param cmd_string:
     :param uname:
     :param passwd:
     :param external_system:
     :param external_system_session:
     :param stop_after:
     :param gnmi_obj:
     :param script:
     :return:
     """
     status = False
     result = None
     execute = False
     child = None
     cmd = binary + cmd_string
     testcase_Utils.pNote("********** Command to be Executed ********** \n {0}".format(cmd))
     if external_system == None:
         child = pexpect.spawn(cmd)
         child.maxread = 50000
     else:
         session_id = data_Utils.get_session_id(external_system, external_system_session)
         child = data_Utils.get_object_from_datarepository(session_id)
         child.sendline(cmd)
     if script.lower() == "no":
         credentials = {"username.*": uname, "password.*": passwd}
         for response, value in credentials.iteritems():
             index = child.expect([response, ".*error.*", pexpect.EOF, pexpect.TIMEOUT],
                                  timeout=5)
             if index == 0:
                 child.sendline(value)
                 testcase_Utils.pNote(child.match.group(0) + value)
                 execute = True
                 status = True
             else:
                 execute = False
                 break
     if execute or script.lower() == "yes":
         if stop_after == None and "poll" not in cmd_string.lower() \
                               and "stream" not in cmd_string.lower():
             j_index = child.expect([prompt, pexpect.EOF, pexpect.TIMEOUT], timeout=50)
             if j_index == 1 or j_index == 0:
                 if "client had error while displaying results" not in child.before and \
                         "could not create a gNMI client" not in child.before:
                     if j_index == 1:
                         sleep(5)
                         result = child.before
                         testcase_Utils.pNote(result)
                         #self.ju.pretty_print_json(result)
                     else:
                         result = child.after
                         testcase_Utils.pNote(result)
                     status = True
                 else:
                     status = False
                     result = child.before
                     testcase_Utils.pNote(child.before, "error")
         if stop_after: #For polling or streaming
             testcase_Utils.pNote("Will Kill the process after {}sec".format(stop_after))
             child.sendcontrol('C')
             try:
                 child.expect([pexpect.EOF, prompt], timeout=int(stop_after))
             except:
                 testcase_Utils.pNote("Sending Ctrl+Z")
             if "client had error while displaying results" not in child.before:
                 result = child.before.strip().strip("^Z")
                 testcase_Utils.pNote(result)
             status = True
     return status, result, child