def collect_log(self, session):
        """
        Collects the response from a connected session
        till the tread is stopped

        This function currently collects response from
        a connected pexpect spawn object using the
        pexpect read_nonblocking method
        """
        response = " "
        while not self.stop_thread_flag:
            try:
                # default timeout for pexpect-spawn object is 30s
                string = session.read_nonblocking(1024, timeout=30)
                if isinstance(string, bytes):
                    string = string.decode("utf-8")
                response = response + string
                time.sleep(0.5)
                self.data = response
            # continue reading data from 'session' until the thread is stopped
            except pexpect.TIMEOUT:
                continue
            except Exception as exception:
                print_exception(exception)
                break
Example #2
0
 def diff_json_files(self, json_file1, json_file2):
     """ Takes two json files as inputs and calculates the difference between them.
     :Note: This method does an unsorted (or raw) comparison of the input json files
            For a sorted comparison use compare_json_files.
     :Returns:
         Returns a status and a comparison result(tuple or None)
         1. No difference between two json objects.
            - status = True
            - comparison result = None.
         2. Difference found between two json objects.
            - status=False
            - comparison result = a tuple of two lists
                                  list1= items in json1  but not json2
                                      list2= items in json2 but not json1
         3. If any exception encountered during comparison:
             - status=False
             - comaprison result = None
     """
     try:
         json_object1 = json.load(open(json_file1, 'r'))
         json_object2 = json.load(open(json_file2, 'r'))
         result, result_list = self.diff_json_objects(
             json_object1, json_object2)
     except Exception as exception:
         print_exception(exception)
         result = False
         result_list = None
     return result, result_list
Example #3
0
 def compare_json_objects(self,
                          json_object1,
                          json_object2,
                          case_conversion=False,
                          write_diff_to_console=True,
                          check_for_subset=False):
     """Compares two json objects and returns true or false
     This method recursively sorts all the lists and dictionaries in the
     json objects and then performs the comparison
     If user selects check_for_subset as True, then checks whether json_object2
     is a subset of json_object1 or not by recursively sorting the json objects
     """
     print_info("compare two json objects")
     result = False
     try:
         if case_conversion == True:
             json_object1 = self.case_conversion_json(json_object1)
             json_object2 = self.case_conversion_json(json_object2)
         if check_for_subset:
             json_object1 = self.sort_json_object(json_object1)
             json_object2 = self.sort_json_object(json_object2)
             result = all(item in list(json_object1.items())
                          for item in list(json_object2.items()))
         else:
             result = self.sort_json_object(
                 json_object1) == self.sort_json_object(json_object2)
         if not result and write_diff_to_console:
             self.diff_json_objects(json_object1, json_object2)
     except Exception as exception:
         print_exception(exception)
     return result
    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 cs_get_topo_details(self, topology_path):
        """To get the Cloudshell topology details for a given path

        :Datafile usage:
             NA
        :Arguments:
            1. topology_path(string) = Specify the full topology name. Include
               the full path from the root to the topology, separated by slashes.
               For example: FolderName/Topologies/TopologyName

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To get the Cloudshell topology details for a given path"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        testcase_Utils.pNote("cs_get_topo_details, cs obj-{}".\
                             format(cloud_shell), "info")
        try:
            xml_resp = cloud_shell.GetTopologyDetails(topology_path)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Get Topolopy \"%s\" successfull\n"\
                                     % (topology_path), "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Get Topolopy \"%s\" failed\n"\
                                     % (topology_path), "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
Example #6
0
def get_action_dirlist(driverpath):
    """ Get the list of action directories """
    actions_package_list = []
    try:
        if os.path.isfile(driverpath):
            lines = []
            with open(driverpath, 'r') as fobj:
                lines = fobj.readlines()
            lines_as_string = ''.join(lines)
            search_string = re.compile(r'package_list.*=.*\]',
                                       re.DOTALL | re.MULTILINE)
            match = re.search(search_string, lines_as_string)

            if match:
                match_string = match.group()
                actions_package_list = match_string.split('[')[1].split(
                    ']')[0].split(',')

            return actions_package_list
        else:
            print_error(("file {0} does not exist".format(driverpath)))
            return actions_package_list
    except Exception as exception:
        print_exception(exception)
    return actions_package_list
    def cs_create_route_in_reservation(self, system_name, reservation_name,
                                       source_resource_full_path,
                                       target_resource_full_path,
                                       override_active_routes, mapping_type,
                                       max_hops, route_alias, is_shared):
        """Creates routes between the specified source and target resources.

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. source_resource_full_path(string) = Specify the source resource
                full path
            4. target_resource_full_path(string) = Specify the target resource
                full path
            5. mapping_type(string) = Specify bi-directional or uni-directional
               as the mapping type
            6. max_hops(integer) = The maximum number of allowed hops.
            7. route_alias(string) = Specify the route alias
            8. override_active_routes(bool) = Specify whether the new route
                can override existing routes.
            9. is_shared(bool) = Specify whether these routes are shared.
        :Returns:
            1. status(bool) = True/False
        """

        wdesc = "Create Route In Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote(
            "cs_create_route_in_reservation, cs obj-{}".format(cloud_shell),
            "info")

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository(
            system_name + "_" + reservation_name + "_reservationId")
        try:
            xml_resp = cloud_shell.CreateRouteInReservation(
                cs_res_id, source_resource_full_path,
                target_resource_full_path, override_active_routes,
                mapping_type, int(max_hops), route_alias, is_shared)

            if xml_resp is not None:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Create Route In"
                    " Reservation successfull for \"{}\"\n".format(
                        reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Create Route In"
                    " Reservation failed for \"{}\"".format(reservation_name),
                    "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
Example #8
0
 def rem_nonprintable_ctrl_chars(self, txt):
     """Remove non_printable ascii control characters """
     #Removes the ascii escape chars
     try:
         txt = re.sub(r'[^\x20-\x7E|\x09-\x0A]', '', txt)
         # remove non-ascii characters
         # txt = repr(txt)[1:-1]
     except Exception as exception:
         print_exception(exception)
     return txt
Example #9
0
 def close_browser(self, browser_instance=None):
     """closes a browser session """
     status = True
     try:
         if browser_instance is not None:
             browser_instance.quit()
         else:
             self.current_browser.quit()
     except Exception as exception:
         print_exception(exception)
         status = False
     return status
Example #10
0
 def close_window(self, browser_instance=None):
     """close the current window """
     status = True
     try:
         if browser_instance is not None:
             browser_instance.close()
         else:
             self.current_browser.close()
     except Exception as exception:
         print_exception(exception)
         status = False
     return status
    def cs_add_users_to_reservation(self, system_name, reservation_name,
                                    list_of_usernames):
        """Add one or more permitted users to the specified reservation.

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. list_of_usernames(list) = list of usernames to permit access to
               reservation.
               For example: To add many users to access the reservation
                            list_of_usernames = ['user1','user2','userx']

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "Add one or more permitted users to the reservation"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_add_users_to_reservation, cs obj-{}".\
                             format(cloud_shell), "info")

        usernames = list_of_usernames[0:]
        testcase_Utils.pNote("cs_add_users_to_reservation, res_name-{},"\
                             "users-{}".format(reservation_name, usernames))

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                    (system_name+"_"+reservation_name+"_reservationId")
        try:
            xml_resp = cloud_shell.AddPermittedUsersToReservation(cs_res_id,\
                                                                  usernames)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Cloudshell Add users \"{}\" to"
                                     "reservation successfull".\
                                     format(usernames), "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Add users \"{}\" to"
                    "Reservation failed".format(usernames), "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def cs_remove_route_from_reservation(self, system_name, reservation_name,
                                         first_endpoint, second_endpoint,
                                         mapping_type):
        """Disconnects two endpoints and removes the mapped route between
           them

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. first_endpoint(str) = The first endpoint of the two end points
            4. second_endpoint(str) = The second endpoint of the two end points
            5. mapping_type(string) = Specify bi-directional or uni-directional
               as the mapping type
        :Returns:
            1. status(bool) = True/False
        """

        wdesc = "Remove Route From Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote(
            "cs_remove_route_from_reservation, cs obj-{}".format(cloud_shell),
            "info")

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository(
            system_name + "_" + reservation_name + "_reservationId")
        list_of_endpoints = [first_endpoint, second_endpoint]
        try:
            xml_resp = cloud_shell.RemoveRoutesFromReservation(
                cs_res_id, list_of_endpoints, mapping_type)
            if xml_resp is not None:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Remove Route From"
                    " Reservation successfull for \"{}\"\n".format(
                        reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote(
                    "\n\n *** Cloudshell Remove Route From"
                    " Reservation failed for \"{}\"".format(reservation_name),
                    "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def connect_target_via_host(self,
                                target,
                                user,
                                auth,
                                invoke_shell=False,
                                log=None):
        """Forward the SSH connection to another target client
           :Argument:
             1. target(string) - Name/ip target machine to be connected
             2. user - username to connect
             3. auth - password for the user
             4. invoke_shell - open shell for passing commands

           :Returns:
             1. target_session - Session object for target connection
             2. status(bool)= True / False

        """
        target_session = SSHComm(target, uid=user, pid=auth, logfile=log)
        status = False
        try:
            ssh_transport = self.sshobj.get_transport()

            channel = ssh_transport.open_channel("direct-tcpip", (target, 22),
                                                 ('localhost', 0))
            print_info("Connecting to target: {}".format(target))
            target_session.sshobj.set_missing_host_key_policy(\
                                       self.param.AutoAddPolicy())
            target_session.sshobj.connect(target,
                                          port=22,
                                          username=user,
                                          password=auth,
                                          sock=channel)
            if target_session.logfile:
                target_session.log = open(self.logfile, 'w')
            print_info("Connection to target: {}successful".format(target))
            if invoke_shell:
                print_info("Opening shell for {}".format(target))
                target_session.invoke_shell()

            status = True

        except self.param.SSHException as exception:
            print_exception(exception)

        except Exception as exception:
            print_exception(exception)

        return target_session, status
Example #14
0
    def execute_method_for_keyword(self):
        """Executes a method corresponding to keyword """

        kwargs, kw_status = self.get_argument_as_keywords()
        print_info(
            "The Arguments passed for the current Step is: '{0}'".format(
                kwargs))
        if kw_status:
            # Execute the corresponding method
            try:
                """

                Hi there, major issue here

                """
                # print(dir(self.exec_obj))
                # print(self.exec_obj.__class__)
                # print(self.exec_obj.__module__)
                keyword_result = self.exec_obj(**kwargs)
            except Exception as exception:
                trcback = print_exception(exception)
                keyword_result = ("EXCEPTION", trcback)

            self.data_repository = self.update_data_repository(
                self.keyword, keyword_result, self.data_repository)
        return self.data_repository
Example #15
0
 def compare_json_files(self, json_file1, json_file2):
     """Compares two json files and returns true or false
     This method recursively sorts all the lists and dictionaries in the
     json files into a sorted json object and then performs the comparison"""
     print_info("compare two json files")
     result = False
     try:
         json_object1 = json.load(open(json_file1, 'r'))
         json_object2 = json.load(open(json_file2, 'r'))
         result = self.sort_json_object(
             json_object1) == self.sort_json_object(json_object2)
         if not result:
             self.diff_json_objects(json_object1, json_object2)
     except Exception as exception:
         print_exception(exception)
     return result
Example #16
0
    def diff_json_objects(self,
                          json_object1,
                          json_object2,
                          case_conversion=False):
        """ Takes two json objects as inputs and calculates the difference between them.
        :Returns:
            Returns a status and a comparison result(tuple or None)
            1. No difference between two json objects.
               - status = True
               - comparison result = None.
            2. Difference found between two json objects.
               - status=False
               - comparison result = a tuple of two lists
                                     list1= items in json1  but not json2
                                         list2= items in json2 but not json1
            3. If any exception encountered during comparison:
                - status=False
                - comaprison result = None
        """
        result = False
        try:
            if case_conversion == True:
                json_object1 = self.case_conversion_json(json_object1)
                json_object2 = self.case_conversion_json(json_object2)

            json_object1 = self.nested_json_object(json_object1)
            json_object2 = self.nested_json_object(json_object2)

            list1 = list(json_object1.difference(json_object2))
            list2 = list(json_object2.difference(json_object1))

            if list1 or list2:
                print_info("Items in json 1 but not json 2: {0}".format(
                    str(list1)))
                print_info("\nItems in json 2 but not json 1: {0} ".format(
                    str(list2)))
                result_list = (list1, list2)
            else:
                result, result_list = (True, None)
        except Exception as exception:
            print_exception(exception)
            result_list = None
        return result, result_list
    def cs_disconnect_routes(self, system_name, reservation_name,
                             first_endpoint, second_endpoint):
        """Disconnects the routes in the cloud shell

        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. first_endpoint(str) = The first endpoint of the two end points
            4. second_endpoint(str) = The second endpoint of the two end points
        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "Disconnect Routes in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_disconnect_routes, cs obj-{}".\
                             format(cloud_shell), "info")

        endpoints = [first_endpoint, second_endpoint]

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                (system_name+"_"+reservation_name+"_reservationId")
        try:
            xml_resp = cloud_shell.DisconnectRoutesInReservation(
                cs_res_id, endpoints)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Cloudshell Disconnect Routes"
                                     " successfull for \"{}\"\n".\
                                     format(reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Cloudshell Disconnect Routes"
                                     " failed for \"{}\"".\
                                     format(reservation_name), "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
 def start_thread(self, session):
     """
     Starts a thread using the value self.function
     if self.function is false throws an error that
     self.function is not available.
     """
     value = False
     try:
         if session:
             self.current_thread = threading.Thread(target=self.collect_log,
                                                    args=(session, ))
             self.current_thread.start()
         else:
             print_error("Need a valid session to start collecting logs")
     except Exception as exception:
         print_exception(exception)
     else:
         value = True
     return value
    def cs_end_reservation(self, system_name, reservation_name, unmap):
        """End the reservation in Cloudshell

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.
            3. unmap(string) = true or false, Unmap resources - Specify whether to keep mappings
               or release mapped resources when deleting the reservation.
        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "End Reservation in CloudShell API Host"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        testcase_Utils.pNote("cs_end_reservation, cs obj-{}".\
                             format(cloud_shell), "info")

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                   (system_name+"_"+reservation_name+"_reservationId")
        try:
            unmap = unmap.lower()
            xml_resp = cloud_shell.EndReservation(cs_res_id, unmap)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Cloudshell End reservation"
                                     " successfull for \"{}\"\n".\
                                     format(reservation_name), "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Cloudshell End Reservation"
                                     " failed for \"{}\"".\
                                     format(reservation_name), "warning")

        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
Example #20
0
    def maximize_browser_window(self,
                                browser_instance=None,
                                headless_mode=False):
        """Maximizes current browser window."""
        status = True
        try:
            if browser_instance is None:
                browser_instance = self.current_browser

            # Need to distinguish whether browser is in headless mode or not
            # as maximize_window doesn't work in headless mode
            if headless_mode:
                browser_instance.set_window_size(1920, 1080)
            else:
                browser_instance.maximize_window()

        except Exception as exception:
            print_exception(exception)
            status = False
        return status
Example #21
0
    def print_output(self):
        """ Prints the dump of the xml object to the file specified.
        This function can be used for debugging purpose and
        its called at the end of the functional calls.

        :Arguments:
            resultfile = Result File

        :Returns:
            None
        """

        try:
            import warrior.Framework.Utils.config_Utils as config_Utils
            resultfile = config_Utils.resultfile
            tree = ET.ElementTree(self.root)
            tree.write(resultfile)
        except UnicodeDecodeError as e:
            print_exception(e)
        except Exception as err:
            print_exception(err)
    def create_ws_execution(self):
        """Create execution dir in Warriorspace """
        # curr_file_locn = os.path.realpath(__file__)
        # war_locn = os.sep.join(curr_file_locn.split(os.sep)[:-3]) + os.sep + "Warrior"
        # warriorspace = os.path.dirname(war_locn) + os.sep + "Warriorspace"
        warriorspace = os.path.expanduser("~") + os.sep + "Warriorspace"
        # check_create_warriorspace(warriorspace)
        ws_execution = warriorspace + os.sep + "Execution"

        try:
            if not file_Utils.pathExists(ws_execution):
                os.makedirs(ws_execution)
            execution_dir = ws_execution
            self.ws_execution = file_Utils.createDir_addtimestamp(
                execution_dir, self.nameonly)
        except OSError as exception:
            print_error("Unable to create directory/file(s) under Warriorspace " \
                        "'{0}', hence aborting".format(ws_execution))
            print_exception(exception)
            exit(0)
        else:
            return self.ws_execution
    def cs_get_reservation_details(self, system_name, reservation_name):
        """Retrieves all details and parameters for a specified reservation

        :Datafile usage:
             NA
        :Arguments:
            1. system_name(string) = Name of the UAP system from the datafile
            2. reservation_name(string) = Specify the name of the reservation.

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To retrieve all details and parameters for a specified"\
                "reservation"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        cs_res_id = data_Utils.get_object_from_datarepository\
                    (system_name+"_"+reservation_name+"_reservationId")
        testcase_Utils.pNote("cs_get_reservation_details, cs obj-{}".\
                             format(cloud_shell), "info")
        try:
            xml_resp = cloud_shell.GetReservationDetails(cs_res_id)
            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Get reservation details for "
                                     "\"(%s)\" successfull\n" % (reservation_name),\
                                     "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Get reservation details for "
                                     "\"(%s)\" failed\n" % (reservation_name),\
                                     "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
    def download_remote_file_sftp(self, remotepath, localpath, filename, \
                                remotehost, username, password, port=22):
        """Downloads a remote file from the remote server to
        the localpath using SFTP

        :Arguments:
            1. remotepath (string) = the remote path to download the file from remotehost
            2. localpath (string) = the local path on the local host
            3. filename (string) = name of the remote file to download
            4. remotehost (string) = remote host
            5. username (string) = remote login username
            6. password (string) = remote login password

        :Returns:
            1. status(bool)
        """
        status = False
        transport = self.param.Transport((remotehost, port))
        transport.connect(username=username, password=password)
        sftp = self.param.SFTPClient.from_transport(transport)

        if filename:
            try:
                sftp.get(remotepath + filename, localpath + filename)
                if os.path.isfile(localpath + filename):
                    print_info(
                        "Downloading file from remote server successful")
                    status = True
                else:
                    print_info("Downloading file from remote server failed")
            except Exception as exception:
                print_exception(exception)

            finally:
                sftp.close()
                transport.close()

        return status
    def cs_get_current_reservation(self, reservation_owner):
        """Retrieves current reservations for the specified owner

        :Datafile usage:
             NA
        :Arguments:
            1. reservation_owner(string) = Specify the user name of the
               reservation owner.

        :Returns:
            1. status(bool)= True/False
        """

        wdesc = "To retrieve current reservations for the specified owner"
        testcase_Utils.pSubStep(wdesc)
        testcase_Utils.pNote(file_Utils.getDateTime())

        status = False
        testcase_Utils.pNote("cs_get_current_reservation, cs obj-{}".\
                             format(cloud_shell), "info")
        try:
            xml_resp = cloud_shell.GetCurrentReservations(reservation_owner)

            if xml_resp is not None:
                testcase_Utils.pNote("\n\n *** Get current reservation for "
                                     "\"(%s)\" successfull\n" % (reservation_owner),\
                                     "info")
                status = True
            else:
                testcase_Utils.pNote("\n\n *** Get current reservation for "
                                     "\"(%s)\" failed\n" % (reservation_owner),\
                                     "warning")
        except Exception as exception:
            print_exception(exception)

        testcase_Utils.report_substep_status(status)
        return status
Example #26
0
def get_key(encoded_key):
    """
    Function that returns enc instance using
    secret key, passed to this
    function or read from secret.key file

    Args:
        encoded_key - False or base64 secrety key for encryption

    Return:
        IV - Random seed used to enc
        CIPHER - Enc instance used to for encryption
    """
    IV = None
    CIPHER = None
    #MYFILE = Tools.__path__[0]+os.sep+"admin"+os.sep+'secret.key'
    MYFILE = os.getenv(
        "WAR_TOOLS_DIR") + os.sep + "admin" + os.sep + 'secret.key'
    try:
        if not encoded_key:
            with open(MYFILE, 'r') as myfileHandle:
                encoded_key = myfileHandle.read()
            if not encoded_key:
                raise IOError("encoded key is not present in secret.key file")
    except IOError:
        print_warning(
            "Could not find the secret.key file in Tools/Admin! or secret.key is empty"
            " use ./Warrior -encrypt anything -secretkey sixteenlenstring")
    else:
        try:
            IV = Random.new().read(AES.block_size)
            CIPHER = AES.new(base64.b64decode(encoded_key), AES.MODE_CFB, IV)
        except Exception as e:
            print_exception("Some problem occured: {0}".format(e))

    return IV, CIPHER
Example #27
0
    def execute_function_for_keyword(self):
        """Executes a function for a keyword"""
        kwargs, kw_status = self.get_argument_as_keywords()

        print_info(
            "The Arguments passed for the current Step is: '{0}'".format(
                kwargs))
        if kw_status:
            # Execute the corresponding function
            try:
                keyword_result = self.exec_obj(**kwargs)
            except Exception as exception:
                trcback = print_exception(exception)
                keyword_result = ("EXCEPTION", trcback)

            self.data_repository = self.update_data_repository(
                self.keyword, keyword_result, self.data_repository)

        return self.data_repository
def send_keyword_to_productdriver(driver_name, plugin_name, keyword,
                                  data_repository, args_repository, repo_name):
    """send the keyword to corresponding product driver for execution"""
    step_num = data_repository["step_num"]
    # driver_call = 'ProductDrivers.{0}'.format(driver_name)
    try:
        if plugin_name is not None:
            import_name = ".".join(["plugins", plugin_name, "bin",
                                    plugin_name[:-7]+'_driver'])
        else:
            #import_name = "user_repo.ProductDrivers.{0}".format(driver_name)
            try:
                import_name = "{0}.ProductDrivers.{1}".format(repo_name, driver_name)
                driver_call = __import__(import_name, fromlist=[driver_name])
            except Exception:
                    if repo_name == "warrior":
                        try:
                            WARRIORDIR = dirname(dirname(dirname(abspath(__file__))))
                            module_dir = "/warrior_modules/warrior_{0}".format("".join(driver_name.split("_")[:-1]).lower())
                            if WARRIORDIR+module_dir not in sys.path:
                                sys.path.append(WARRIORDIR+module_dir)
                            import_name = "warrior{0}.ProductDrivers.{1}".format("".join(driver_name.split("_")[:-1]).lower(), driver_name.lower())
                            driver_call = __import__(import_name, fromlist=[driver_name])
                        except:
                            raise
                    else:
                        raise
    except Exception:
        trcback = print_exception(Exception)
        data_repository['step-%s_status' % step_num] = 'ERROR'
        data_repository['step-%s_exception' % step_num] = trcback
        Utils.testcase_Utils.pStep()
        return data_repository
    # return eval(driver_call).main(keyword, data_repository, args_repository)
    else:
        return driver_call.main(keyword, data_repository, args_repository)
def main(testcase_filepath, data_repository={}, tc_context='POSITIVE',
         runtype='SEQUENTIAL_KEYWORDS', tc_parallel=False, auto_defects=False, suite=None,
         tc_onError_action=None, iter_ts_sys=None, queue=None, jiraproj=None, jiraid=None):

    """ Executes a testcase """
    tc_start_time = Utils.datetime_utils.get_current_timestamp()
    if Utils.file_Utils.fileExists(testcase_filepath):
        try:
            Utils.config_Utils.set_datarepository(data_repository)
            if Utils.testrandom_utils.get_generic_datafile(testcase_filepath, data_repository):
                init_datarepository = copy.deepcopy(data_repository)
                exec_tag = data_repository.get("gen_exec_tag", 'default')
                print_info("Execution tag : {}".format(exec_tag))
                generic_data_dict = Utils.testrandom_utils.get_iterations_from_generic_data(testcase_filepath, data_repository)
                tc_status = True
                for iter_number, _ in enumerate(generic_data_dict):
                    gentc_start_time = Utils.datetime_utils.get_current_timestamp()
                    print_info("testcase execution starts with variables : {}"\
                            .format(generic_data_dict[iter_number]))
                    Utils.data_Utils.update_datarepository({"gen_iter_number" : iter_number})
                    tc_data_repository = copy.deepcopy(init_datarepository)
                    gen_tc_status, gen_data_repository = execute_testcase(testcase_filepath,\
                                            tc_data_repository, tc_context, runtype,\
                                            tc_parallel, queue, auto_defects, suite,\
                                            jiraproj, tc_onError_action, iter_ts_sys)
                    tc_status = tc_status and gen_tc_status
                    warrior_cli_driver.update_jira_by_id(jiraproj, jiraid, os.path.dirname(\
                                tc_data_repository['wt_resultsdir']), gen_tc_status)
                    email.compose_send_email("Test Case: ", testcase_filepath,\
                                 tc_data_repository['wt_logsdir'],\
                                 tc_data_repository['wt_resultsdir'], gen_tc_status)
                    data_repository["xml_results_dir"] = os.path.dirname(os.path.dirname(\
                            tc_data_repository['wt_logsdir']))
                    gen_tc_duration = Utils.datetime_utils.get_time_delta(gentc_start_time)
                    dict_to_update_in_db = generic_data_dict[iter_number]
                    dict_to_update_in_db["result"] = "PASS" if gen_tc_status else "FAIL"
                    dict_to_update_in_db["duration_in_seconds"] = gen_tc_duration
                    dict_to_update_in_db["log_file"] = tc_data_repository['wt_logsdir']
                    Utils.testrandom_utils.update_generic_database(exec_tag, testcase_filepath, [dict_to_update_in_db])
                report_file = Utils.testrandom_utils.generate_report_from_generic_db(exec_tag, testcase_filepath,
                                                                                     data_repository)
                print_info("Report file : {}".format(report_file))
            else:
                tc_status, data_repository = execute_testcase(testcase_filepath,\
                                                        data_repository, tc_context, runtype,\
                                                        tc_parallel, queue, auto_defects, suite,\
                                                        jiraproj, tc_onError_action, iter_ts_sys)
        except Exception as exception:
            print_exception(exception)
            tc_status = False

    else:
        print_error("Testcase xml file does not exist in provided path: {0}"
                    .format(testcase_filepath))
        tc_status = False
        if tc_parallel:
            queue.put(('ERROR', str(testcase_filepath), 'IMPACT', '0'))

    tc_duration = Utils.datetime_utils.get_time_delta(tc_start_time)

    return tc_status, tc_duration, data_repository
Example #30
0
    from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
    from selenium.common.exceptions import WebDriverException

    KEYS = {
        1: Keys.NUMPAD1,
        2: Keys.NUMPAD2,
        3: Keys.NUMPAD3,
        4: Keys.NUMPAD4,
        5: Keys.NUMPAD5,
        6: Keys.NUMPAD6,
        7: Keys.NUMPAD7,
        8: Keys.NUMPAD8,
        9: Keys.NUMPAD9
    }
except ImportError as exception:
    print_exception(exception)
""" selenium browser management library"""


class BrowserManagement(object):
    """Browser management class"""
    def __init__(self, *args, **kwargs):
        """Browser management constructor """
        self.current_browser = None
        self.current_window = None
        self.ff_binary_object = FirefoxBinary()

    def open_browser(self,
                     browser_name='firefox',
                     webdriver_remote_url=False,
                     desired_capabilities=None,