def get_messages(self, get_all_messages=False, **kwargs):
        """
        Get messages from consumer.
        Arguments:
          get_all_messages(bool): set this to True to get all the messages, seeks to the beginning.
                                   Defaults to False.
          timeout(int): timeout in milliseconds
          max_records(int): maximum messages to fetch
        Returns:
          messages(list): messages from the consumer
        """
        timeout_ms = kwargs.get("timeout", 0)
        max_records = kwargs.get("max_records", None)
        messages = []
        msg_pack = {}
        print_info("get messages published to subscribed topics")
        try:
            if get_all_messages:
                self.kafka_consumer.seek_to_beginning()
            msg_pack = self.kafka_consumer.poll(timeout_ms, max_records)
        except KafkaError as exc:
            print_error("Exception occured in get_messages - {}".format(exc))

        for topic, message_list in msg_pack.items():
            for message in message_list:
                messages.append(message.value)
        return messages
Esempio n. 2
0
def decide_createsuite_actions(w_cli_obj, namespace):
    """Decide the actions for -createsuite tag """
    filepath = namespace.filepath

    # already check namespace.create here, no need to double check
    if namespace.filepath is not None and len(namespace.filepath) == 0:
        namespace.filepath = None

    if all([namespace.suitename, namespace.filepath]):
        filepath = w_cli_obj.examine_create_suite(namespace)
        print_info("suite created in ", filepath[0])
        exit(0)

    if all([namespace.suitename, namespace.cat]):
        filepath = w_cli_obj.examine_create_suite(namespace)
        print_info("suite created in ", filepath[0])
        exit(0)

    elif not namespace.cat and not all(
        [namespace.suitename, namespace.filepath]):
        print_error("Invalid combination... Use -createsuite with -suitename, "
                    "filepath(s) (i.e. list of testcase xml files. "
                    "Use -h or --help for more command line options")
        exit(1)
    elif namespace.cat and not namespace.suitename:
        print_error("Invalid combination... Use -creatsuite + -category "
                    "with -suitename")
        exit(1)

    return filepath
    def check_tag(self, category_list, dirlist):
        """return list of valid testcase xml
        files with the correct category tag"""
        result = []
        cur_dir = os.path.abspath(os.getcwd())
        if dirlist is None:
            dirlist = [cur_dir]

        for folder in dirlist:
            os.chdir(cur_dir)
            folder = Utils.file_Utils.getAbsPath(folder, os.curdir)
            if os.path.isdir(folder):
                all_files = [
                    Utils.file_Utils.getAbsPath(f, folder)
                    for f in os.listdir(folder)
                ]
                is_xml_files = self.check_xml(all_files)
                for xmlfile in is_xml_files:
                    root = Utils.xml_Utils.getRoot(xmlfile)
                    detail = root.find('Details')
                    if detail is not None:
                        if detail.find('Category') is not None:
                            cat_text = detail.find('Category').text.strip()
                            cat_text = cat_text.split(",")
                            if len(set(category_list) & set(cat_text)) > 0:
                                result.append(xmlfile)
            else:
                print_error(str(folder) + "is not a directory")
        print_info("Number of matching testcases: {0}".format(len(result)))
        return result
Esempio n. 4
0
    def _make_browser(self,
                      browser_name,
                      desired_capabilities=None,
                      profile_dir=None,
                      webdriver_remote_url=None,
                      **kwargs):
        """method to open a browser, calls other sepcific/generic
        make browser methods to open a browser """
        browser_methods = {
            'ff': self._make_ff,
            'firefox': self._make_ff,
            'chrome': self._make_chrome
        }
        creation_method = browser_methods.get(browser_name, None)

        if creation_method is None:
            print_error("{} is not a supported browser. Please use firefox or chrome".\
                             format(browser_name))
            browser = None
        else:
            kwargs["browser_name"] = browser_name
            browser = creation_method(webdriver_remote_url,
                                      desired_capabilities, profile_dir,
                                      **kwargs)
            if browser is not None:
                print_info("The {} browser version is {}".format(
                    browser_name, self.get_browser_version(browser)))
            else:
                print_error(
                    "Unable to create browser for: {}".format(browser_name))

        return browser
Esempio n. 5
0
    def save_screenshot(self,
                        browser_instance=None,
                        filename=None,
                        directory=None):
        """
            Save screenshot of the specified/current browser
        """
        status = True
        if browser_instance is None:
            browser_instance = self.current_browser

        if filename is None:
            current_datetime = str(get_current_timestamp())
            current_datetime = current_datetime.replace(" ", "_")
            current_datetime = current_datetime.replace(":", "-")
            filename = "screenshot_" + current_datetime + ".png"
        else:
            filename += ".png"

        print_info(
            "Screenshot will be saved by the name {0} in directory {1}".format(
                filename, directory))

        directory = os.path.join(directory, filename)
        try:
            browser_instance.save_screenshot(directory)
            sleep(10)
        except Exception as e:
            print_error("Could not save screenshot {0}".format(e))
            status = False

        return status
    def verify_response(self, command, exp_string, fail_resp, timeout=None):
        """Execute a command using the paramiko SSH object and returns
           the response string

           :Arguments:
               1. command - command to be executed
               2. exp_string - String to be expected
               3. fail_resp - Failure response to be expected
               4. timeout - wait for response

          :Returns:
               1. status(bool)= True / False
               2. out/err = response string
        """
        out, stderr = self.ssh_exec(command, timeout)
        err = stderr.read()
        if out and ((exp_string in out) and (fail_resp not in out)):
            print_info("Output:", out)
            return True, out
        elif out and ((exp_string not in out) or (fail_resp in out)):
            print_info("Error:", out)
            return False, out
        else:
            print_error("Error:", err)
            return False, err
def get_testwrapper_file_details(testsuite_filepath, data_repository):
    """retuns testwrapperfile to use if specified, else returns False"""
    if 'ow_testwrapperfile' in 'data_repository':
        testwrapperfile = data_repository['ow_testwrapperfile']

    else:
        if Utils.xml_Utils.nodeExists(testsuite_filepath, "TestWrapperFile"):
            testwrapperfile = Utils.xml_Utils.getChildTextbyParentTag\
                (testsuite_filepath, 'Details', 'TestWrapperFile')
        else:
            return [False, False, False, 'abort']
    abs_cur_dir = os.path.dirname(testsuite_filepath)
    abs_testwrapperfile = Utils.file_Utils.getAbsPath(testwrapperfile,
                                                      abs_cur_dir)
    Utils.xml_Utils.getRoot(abs_testwrapperfile)
    if not data_repository.get('suite_data_file', False):
        print_error(
            "Input data file must be specified in test suite global details section"
        )
        exit(0)
    j_data_type = common_execution_utils.check_get_datatype(
        abs_testwrapperfile, data_repository['suite_data_file'])
    j_runtype = common_execution_utils.check_get_runtype(abs_testwrapperfile)
    setup_on_error_action = Utils.testcase_Utils.get_setup_on_error(
        abs_testwrapperfile)
    return [abs_testwrapperfile, j_data_type, j_runtype, setup_on_error_action]
 def verify_data(self, expected, object_key, type='str', comparison='eq'):
     """Verify value in 'object_key' in the data repository matches
     with expected
     :Argument:
         expected = the value to be compared with
         object_key = the object in the data repository to be compared
         type = the type of this expected (str/int/float)
         comparison = actual comparison (eq/ne/gt/ge/lt/le)
             eq - check if both are same(equal)
             ne - check if both are not same(not equal)
             gt - check if object_key is greater than expected
             ge - check if object_key is greater than or equal to expected
             lt - check if object_key is lesser than expected
             le - check if object_key is lesser than or equal to expected
     :Returns:
         status (boolean)
     """
     wDesc = "Verify if value of object_key in data_repository "
     "matches with expected"
     Utils.testcase_Utils.pNote(
         "KEYWORD: verify_data | Description: {0}".format(wDesc))
     result, value = Utils.data_Utils.verify_data(expected, object_key,
                                                  type, comparison)
     if result not in ["FALSE", "TRUE"]:
         return result
     elif result == "FALSE":
         print_error("Expected: {0} {1} {2} but found {0}={3}".format(
             object_key, comparison, expected, value))
         return False
     elif result == "TRUE":
         print_info("Expected: {0} {1} {2} found the same".format(
             object_key, comparison, expected, value))
         return True
 def _execute_current_step(self):
     """
     This function actually executes a given step and returns necessary details about that step.
     """
     try:
         result = step_driver.main(self.current_step,
                                   self.current_step_number,
                                   self.data_repository,
                                   self.system_name,
                                   skip_invoked=self.skip_invoked)
         step_status = result[0]
         kw_resultfile = result[1]
         step_impact = result[2]
     except Exception as e:
         print_error('unexpected error %s' % str(e))
         step_status = False
         kw_resultfile = None
         step_impact = Utils.testcase_Utils.get_impact_from_xmlfile(
             self.current_step)
         print_error('unexpected error {0}'.format(traceback.format_exc()))
     self.go_to_step_number = False
     self.step_status_list, self.step_impact_list = \
         common_execution_utils.compute_status(self.current_step,
                                               self.step_status_list,
                                               self.step_impact_list,
                                               step_status, step_impact)
     self.kw_resultfile_list.append(kw_resultfile)
     return step_status
Esempio n. 10
0
    def report_status(self, status, text="", level='Keyword'):
        """
        Reports the status to the testcase xml result file base on the received status
        On receiving a True reports keyword status as Passed
        On receiving a False reports keyword status as Failed
        On receiving a Skip reports keyword status as Skipped
        On receiving a Exception reports keyword status as Exception
        On receiving a Error reports Keyword status as Error
        On receiving a RAN reports Keyword status as RAN

        :Arguments:
            1. status = (bool) True or False
            2. text = (string) any useful description
            3. level = (string) only supported value currently is Keyword

        :Returns:
            None
        """

        status = {
            'TRUE': self.p_pass,
            'FALSE': self.p_fail,
            'SKIP': self.p_skip,
            'EXCEPTION': self.p_exception,
            'ERROR': self.p_error,
            'RAN': self.p_ran
        }.get(str(status).upper())
        if status is None:
            print_error(
                "unexpected or no value received, expecting TRUE/FALSE/SKIP")
            self.p_error(level, text)
        else:
            status(level, text)
Esempio n. 11
0
    def report_warning(self, status, text="", level='subStep'):
        """
        Reports the status to the testcase xml result file based on the received status
        On receiving a True reports keyword status as Passed
        On receiving a False reports keyword status as Warning
        On receiving a Skip reports keyword status as Skipped
        On receiving a Exception reports keyword status as Exception
        On receiving a Error reports Keyword status as Error

        :Arguments:
            1. status = (bool) True or False
            2. text = (string) any useful description
            3. level = (string) only supported value currently is Keyword

        :Returns:
            None
        """
        from warrior.WarriorCore.Classes.war_cli_class import WarriorCliClass
        if WarriorCliClass.mock:
            if str(status).upper() == 'TRUE' or str(status).upper() == 'FALSE':
                status = 'RAN'
        status = {
            'TRUE': self.p_pass,
            'FALSE': self.p_warn,
            'SKIP': self.p_skip,
            'EXCEPTION': self.p_exception,
            'ERROR': self.p_error,
            'RAN': self.p_ran
        }.get(str(status).upper())
        if status is None:
            print_error(
                "unexpected or no value received, expecting TRUE/FALSE/SKIP")
            self.p_error(level, text)
        else:
            status(level, text)
 def __get_list(self, string):
     """
         Get the list of variable from the string (can have multiple ${list} )
     :param string:
     :return:
         a dictionary
         if nothing wrong with list range
             return a dict with orignal list/range as key "1..4,5,6..7:0.5"
             parsed list as value [1,2,3,4,5,6,6.5,7]
         if invalid range found
             return a dict {'Error':False}
         if no list/range found
             return a dict {'False':False}
     """
     return_value = string
     result = {}
     check = self.end_pat
     match = self.__find_match(return_value[:return_value.find(check) +
                                            len(check)])
     while match is not None:
         try:
             parsed_value = self.__parse_list(self.get_value(
                 match.group(2)))
         except (ValueError, TypeError, AttributeError):
             print_error("Invalid list range found")
             return {'Error': False}
         if parsed_value:
             result[match.group(2)] = parsed_value
         return_value = return_value.replace(
             return_value[:return_value.find(check) + len(check)], '')
         match = self.__find_match(return_value[:return_value.find(check) +
                                                len(check)])
     if result == {}:
         return {'False': False}
     return result
def main(step, skip_invoked=True):
    """
        Entry function for execute nodes in a step
        Handle checking and call the logical decision functions
        combine the final result and return
        :param:
            step: the step Element
        :return:
            decision: Whether the step should be executed or not
            trigger_action: When decision failed, what kind of action to perform
    """
    exec_node = step.find("Execute")
    if exec_node is None:
        return True, None

    trigger_action = None
    exec_type = exec_node.get("ExecType", "")
    if exec_type.upper() == 'IF' or exec_type.upper() == 'IF NOT':
        decision, trigger_action = decision_maker(exec_node)
    elif exec_type.upper() == 'NO':
        decision = False
        trigger_action = "SKIP"
    elif exec_type.upper() == 'YES':
        decision = True
    elif exec_type.upper() == "INVOKED":
        decision = not skip_invoked
        trigger_action = "SKIP_INVOKED"
    else:
        decision = False
        supported_values = ['no', 'yes', 'if', 'if not', "invoked"]
        print_error(
            "Unsupported value used for ExecType, supported values are:"
            "{0} and case-insensitive".format(supported_values))

    return decision, trigger_action
Esempio n. 14
0
    def open_tab(self,
                 browser_instance=None,
                 url=None,
                 browser_type="firefox"):
        """Opens a new tab in the browser"""
        status = True
        if browser_instance is None:
            browser_instance = self.current_browser

        # only when firefox version < 47, open new window
        if browser_type == "firefox" and\
           LooseVersion(self.get_browser_version(browser_instance)) < LooseVersion("47.0.0"):
            element = browser_instance.find_element_by_tag_name("body")
            element.send_keys(Keys.LEFT_CONTROL, 'n')
        elif browser_type == "firefox" or (browser_type == "chrome" and\
             LooseVersion(self.get_browser_version(browser_instance)) > LooseVersion("60.0.0")):
            # If FF version > 47, this action is not supported
            print_error("Firefox (47 or above) and Chrome with chromedriver (2.32 or above)"\
                        "doesn't support opening new tab. Open tab may not function correctly")
            status = False
        else:
            # If it is chrome ver < 60, actually open a new tab
            element = browser_instance.find_element_by_tag_name("body")
            element.send_keys(Keys.LEFT_CONTROL, 't')
        sleep(1)
        browser_instance.switch_to.window(browser_instance.window_handles\
                                          [len(browser_instance.window_handles) - 1])

        if url is not None:
            self.go_to(url, browser_instance)
            sleep(1)

        return status
Esempio n. 15
0
 def get_firefox_version(self, binary):
     """
         Use firefox binary to find out firefox version
         before launching firefox in selenium
     """
     command = ""
     # If the platform is Linux,
     # If Binary - None: default binary is set as "firefox".
     # else the binary path passed through datafile is considered.
     # If the platform is Windows,
     # If Binary - None: default binary is set to Program Files path.
     # else the binary path passed through datafile is considered.
     if platform.system() in "Linux":
         if binary in [False, None]:
             binary = "firefox"
         command = [binary, "-v"]
     elif platform.system() in "Windows":
         if binary in [False, None]:
             binary = self.ff_binary_object._default_windows_location()
         command = "%s -v | more" % (binary)
     print_info("Platform: {0} Firefox binary path: {1}".format(
         platform.system(), binary))
     version = False
     try:
         raw_version = check_output(command).decode("utf-8")
         match = re.search(r"\d+\.\d+", raw_version)
         if match is not None:
             version = LooseVersion(match.group(0))
         else:
             print_info(
                 "Cannot parse Firefox version: {}".format(raw_version))
     except CalledProcessError:
         print_error("Cannot find firefox version, will not launch browser")
     return version
Esempio n. 16
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
Esempio n. 17
0
    def testcase_prerun(self, tc_filepath, check_files_dict=None):
        """Executes prerun of a testcase file """
        print_debug('\n')
        print_debug('=' * 40)
        print_debug("Validating Test case xml")
        print_debug('=' * 40)

        testcase_xsd_fullpath = self.xsd_dir + os.sep + 'warrior_testcase.xsd'
        #print_info("Test case_xsd_location: {0}".format(testcase_xsd_fullpath))

        tc_status = self.xml_to_xsd_validation(tc_filepath,
                                               testcase_xsd_fullpath)

        if tc_status:
            data_file_valid = self.check_tc_input_datafile(
                tc_filepath, check_files_dict)
            tc_status &= data_file_valid
            steps_field_valid = self.check_steps(tc_filepath)
            tc_status &= steps_field_valid
        else:
            print_error("Incorrect xml format")
        time.sleep(5)
        status = testcase_Utils.convertLogic(tc_status)
        print_info('TC STATUS: {0}ED'.format(status))

        return tc_status
    def check_jira_issue(self, issue_summary):
        """
            check jira server for any existing issue with the same summary(title)
            :Arguments,:
                1. issue_summary(str) - issue title
            :Returns:
                1. issue_id(str/boolean) - existing issue key or False if not found
        """
        issue_id = False
        parsed_summary = issue_summary.replace("[", "\\\\[")
        parsed_summary = parsed_summary.replace("]", "\\\\]")
        postdata_url = (self.server + '/rest/api/2/search/?jql=summary~' +
                        '\"' + parsed_summary + '\"')
        response = requests.get(postdata_url, auth=self.auth)

        if response:
            resp_dict = response.json()
            for issue in resp_dict["issues"]:
                if issue_summary[:-2].strip(
                ) == issue["fields"]["summary"].strip():
                    issue_id = issue["key"]
                else:
                    # partially match title
                    pass
        else:
            print_error("Problem checking JIRA issues with same issue summary")
            print_error("JIRA Error code: ({0}), Error message: ({1})".format(
                response.status_code, response.reason))
        return issue_id
    def upload_logfile_to_jira_issue(self,
                                     issue_id,
                                     logfile,
                                     attachment_name="Log file"):
        """
        Function to attach logs to jira Ticket using JIRA rest API
        :Arguments:
            1. issue_id(str) - Jira issue ID
            2. logfile(str) - File(path) to be attached
            3. attachment_name(str) - Name of the file to be attached
        """

        status = False
        postdata_url = self.server + '/rest/api/2/issue/' + issue_id + '/attachments'
        print_info("logfile is : {0}".format(logfile))
        fileobj = open(logfile, 'rb').read()
        logfile_name = os.path.basename(logfile)
        headers = {"X-Atlassian-Token": "nocheck"}
        files = {"file": (logfile_name, fileobj)}
        response = requests.post(postdata_url,
                                 auth=self.auth,
                                 files=files,
                                 headers=headers)

        if response:
            status = True
            print_info("{0} - '{1}' uploaded to Jira issue '{2}'".format(
                attachment_name, logfile_name, issue_id))
        else:
            print_error(
                "Problem attaching logs to Jira issue '{0}'".format(issue_id))
            print_error("JIRA Error code: ({0}), Error message: ({1})".format(
                response.status_code, response.reason))
        return status
 def get_list_direct(self, string):
     """
         entry function for __get_list
     :param string:
     :return:
         a dictionary
         if nothing wrong with list range
             return a dict with orignal list/range as key "1..4,5,6..7:0.5"
             parsed list as value [1,2,3,4,5,6,6.5,7]
         if invalid range found
             return a dict {'Error':False}
         if no list/range found
             return a dict {'False':False}
     """
     return_value = string
     result = {}
     check = self.end_pat
     match = self.__find_match(return_value[:return_value.find(check) +
                                            len(check)])
     while match is not None:
         try:
             parsed_value = self.__parse_list("{" + match.group(2) + "}")
         except (ValueError, TypeError, AttributeError):
             print_error("Invalid list range found")
             return {'Error': False}
         if parsed_value:
             result[match.group(2)] = parsed_value
         return_value = return_value.replace(
             return_value[:return_value.find(check) + len(check)], '')
         match = self.__find_match(return_value[:return_value.find(check) +
                                                len(check)])
     if result == {}:
         return {'False': False}
     return result
Esempio n. 21
0
 def _check_property(self, element, **kwargs):
     """
     check property
     """
     status = True
     if element is not None:
         attribute_name = kwargs.get('attribute_name')
         property_name = kwargs.get('property_name')
         attr_properties = element.get_attribute(attribute_name)
         if attr_properties is not None:
             if property_name in attr_properties:
                 print_info("{0} has a property called {1}. Verification "
                            "success!".format(attribute_name,
                                              property_name))
             else:
                 print_error("{0} does not have a property called {1}. "
                             "Verification failed!".format(
                                 attribute_name, property_name))
                 status = False
         else:
             print_error("Could not find attribute '{0}', hence could not "
                         "retrieve its properties.".format(attribute_name))
             status = False
     else:
         status = False
     return status
 def create_topics(self, topic_sets, **kwargs):
     """
     create topics for the producer or consumer to use
     Arguments:
      topic_sets(list) : list of
      ['topic_name', 'num_partitions', 'replication_factor'] lists
      example : ['topic1',1,1]
      timeout(int): time in milliseconds
     Returns:
       result(bool) : False if exception occures, True otherwise
      None.
     """
     timeout = kwargs.get("timeout", None)
     validate = kwargs.get("validate", False)
     new_topics = [NewTopic(name=tup[0], num_partitions=tup[1],\
                   replication_factor=tup[2]) for tup in topic_sets]
     print_info("creating topics")
     try:
         self.kafka_client.create_topics(new_topics=new_topics,
                                         timeout_ms=timeout,
                                         validate_only=validate)
         result = True
     except KafkaError as exc:
         print_error("Exception during creating topics - {}".format(exc))
         result = False
     return result
Esempio n. 23
0
    def _perform_keypress(self, element, **kwargs):
        """
        This function expects to receive a browser instance through the
        "browser" argument and a key "keys" through the kwargs.

        The value for "keys" would be a list of keys tha need to pressed.

        """
        status = True
        flag = False
        keys = kwargs.get('keys')
        actions = ActionChains(element)
        for key in keys:
            try:
                selenium_key = KEYS[key.upper()]
            except KeyError:
                print_error("{0} is not supported by Selenium.".format(key))
                status = False
            else:
                flag = True
                actions.send_keys(selenium_key)
        if flag:
            actions.perform()
            sleep(2)

        return status
 def send_messages(self, topic, value=None, **kwargs):
     """
     Publish messages to the desired topic
     Arguments:
       topic(str): topic name to publish messages
       partition(int): partition nubmer
       key(str): key name
       value(str): message to publish
     Returns:
       result(bool) : False if exception occures, True otherwise
     """
     partition = kwargs.get("partition", None)
     headers = kwargs.get("headers", None)
     timestamp = kwargs.get("timestamp", None)
     key = kwargs.get("key", None)
     print_info("publishing messages to the topic")
     try:
         self.kafka_producer.send(topic=topic,
                                  value=value,
                                  partition=partition,
                                  key=key,
                                  headers=headers,
                                  timestamp_ms=timestamp)
         self.kafka_producer.flush()
         result = True
     except KafkaError as exc:
         print_error("Exception during publishing messages - {}".format(exc))
         result = False
     return result
 def __init__(self, **configs):
     """
     create a kafka client
     """
     print_info("Creating kafka client")
     try:
         self.kafka_client = KafkaAdminClient(**configs)
     except KafkaError as exc:
         print_error("kafka client - Exception during connecting to broker- {}".format(exc))
 def __init__(self, *topics, **configs):
     """
     Create Kafka Consumer object
     """
     print_info("creating kafka consumer")
     try:
         self.kafka_consumer = KafkaConsumer(*topics, **configs)
     except KafkaError as exc:
         print_error("Kafka consumer - Exception during connecting to broker - {}".format(exc))
def wait_for_timeout(wait_time, unit="SECONDS", notify_count=4):
    """
    Warrior, Wait till the time is a generic wait. The Wait is informed to the user as a countdown.

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

    if Utils.xml_Utils.getRoot(abs_filepath).tag == 'Testcase':
        default_repo['war_file_type'] = "Case"
        result, _, data_repository = testcase_driver.main(
            abs_filepath,
            data_repository=default_repo,
            runtype='SEQUENTIAL_KEYWORDS',
            auto_defects=a_defects,
            jiraproj=jiraproj,
            jiraid=jiraid)
        if not Utils.data_Utils.get_object_from_datarepository(
                'genericdatafile'):
            update_jira_by_id(
                jiraproj, jiraid,
                os.path.dirname(data_repository['wt_resultsdir']), result)
            email.compose_send_email("Test Case: ", abs_filepath,
                                     data_repository['wt_logsdir'],
                                     data_repository['wt_resultsdir'], result)
    elif Utils.xml_Utils.getRoot(abs_filepath).tag == 'TestSuite':
        default_repo['war_file_type'] = "Suite"
        result, suite_repository = testsuite_driver.main(
            abs_filepath,
            auto_defects=a_defects,
            jiraproj=jiraproj,
            data_repository=default_repo)
        update_jira_by_id(jiraproj, jiraid,
                          suite_repository['suite_execution_dir'], result)
        email.compose_send_email("Test Suite: ", abs_filepath,
                                 suite_repository['ws_logs_execdir'],
                                 suite_repository['ws_results_execdir'],
                                 result)
    elif Utils.xml_Utils.getRoot(abs_filepath).tag == 'Project':
        default_repo['war_file_type'] = "Project"
        result, project_repository = project_driver.main(
            abs_filepath,
            auto_defects=a_defects,
            jiraproj=jiraproj,
            data_repository=default_repo)
        update_jira_by_id(jiraproj, jiraid,
                          project_repository['project_execution_dir'], result)
        email.compose_send_email("Project: ", abs_filepath,
                                 project_repository['wp_logs_execdir'],
                                 project_repository['wp_results_execdir'],
                                 result)
    else:
        print_error("Unrecognized root tag in the input xml file ! exiting!!!")

    return result
Esempio n. 30
0
def main(step_list, data_repository, tc_status, system_name=None):
    """Executes the list of steps in parallel
    Computes and returns the testcase status"""
    try:
        testcase_status = execute_custom_parallel(step_list, data_repository,
                                                  tc_status, system_name)
    except Exception:
        testcase_status = False
        print_error('unexpected error {0}'.format(traceback.format_exc()))
    return testcase_status