def get_setup_on_error(self, filepath):
        """Gets the setup on error value
        from the wrapperfile.xml file """

        setup_on_error_action = self.xml_utils().getChildAttributebyParentTag(filepath, 'Details',\
                                                                     'setup_onError', 'action')

        if setup_on_error_action is None or setup_on_error_action is False:
            setup_on_error_action = 'abort'

        elif setup_on_error_action is not None and setup_on_error_action is not False:
            supported_values = ['next', 'abort']
            if not str(setup_on_error_action).lower() in supported_values:
                print_warning("unsupported option '{0}' provided for setup_onError"\
                              "action, supported values are {1}".format(setup_on_error_action,
                                                                        supported_values))
                print_info(
                    "Hence using default value for setup_onError action which is 'abort'"
                )
                setup_on_error_action = 'abort'
        return setup_on_error_action
예제 #2
0
    def get_defonerror_fromxml_file(self, filepath):
        """Gets the default on error value of a step/testcase/suite
        from the testcase.xml/testsuite.xml/project.xml file """

        def_on_error_action = self.xml_utils().getChildAttributebyParentTag(
            filepath, 'Details', 'default_onError', 'action')

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

        elif def_on_error_action is not None and def_on_error_action is not False:
            supported_values = ['next', 'goto', 'abort', 'abort_as_error']
            if not str(def_on_error_action).lower() in supported_values:
                print_warning("unsupported option '{0}' provided for default_onError"\
                              "action, supported values are {1}".format(def_on_error_action,
                                                                        supported_values))
                print_info(
                    "Hence using default value for default_onError action which is 'next'"
                )
                def_on_error_action = 'NEXT'
        return def_on_error_action
def execute_custom(datatype, runtype, driver, data_repository, step_list):
    """
    Execute a custom testcase
    """
    print_info("{0} {1}".format(datatype, runtype))
    tc_status = False
    if data_repository.has_key("suite_exectype") and\
        data_repository["suite_exectype"].upper() == "ITERATIVE":
        print_info(
            "Testsuite execute type=iterative but the testcase datatype=custom. "
            "All testcases in a iterative testsuite should have datatype=iterative, "
            "Hence this testcase will be marked as failure.")
    elif runtype.upper() == 'SEQUENTIAL_KEYWORDS' or runtype.upper(
    ) == 'PARALLEL_KEYWORDS':
        tc_status = driver.main(step_list,
                                data_repository,
                                tc_status,
                                system_name=None)
    else:
        print_error("Unsuppored runtype found, please check testcase file")
    return tc_status
예제 #4
0
def sub_from_varconfigfile(string, varconfigfile, start_pat="${", end_pat="}"):
    """ """
    try:
        # when varconfigfile is an XMl object(root element) - this happens
        # only when varconfigfile is taken from database server
        if isinstance(varconfigfile, ElementTree.Element) is True:
            cfg_elem_obj = ConfigurationElement("Varconfig_from_database",
                                                start_pat, end_pat)
            cfg_elem_obj.parse_data(varconfigfile, elem_type="xml_object")
        else:
            cfg_elem_obj = ConfigurationElement(varconfigfile, start_pat,
                                                end_pat)
            cfg_elem_obj.parse_data(varconfigfile)
        newstring = cfg_elem_obj.expand_variables(string)
    except TypeError as exception:
        print_info(
            "At least one of the variables in command string is not found in  "
            + varconfigfile)
        #print_exception(exception)
        return False
    return newstring
예제 #5
0
    def store_in_repo(self, datavar, datavalue, type='str'):
        """For storing datavalue in datavar datarepository
        :Argument:
            datavar = var in data repository in which to store
                      this could be dot separated to store in nested fashion
                      i.e., if var is k1.k2.k3 then the data value would be
                      stored as a value in datarepository[k1][k2][k3]
            datavalue = the value to be stored
            type = type of datavalue (string/int/float)
        """
        def get_dict_to_update(var, val):
            """

            The function creates a dictionary with Variable and value. If Variable has "." seperated
            keys then the value is updated at appropriate level of the nested dictionary.
            :param var: Dictionary Key or Key seperated with "." for nested dict keys.
            :param val: Value for the Key.

            :return: Dictionary

            """
            dic = {}
            if '.' in var:
                [key, value] = var.split('.', 1)
                dic[key] = get_dict_to_update(value, val)
            else:
                dic[var] = val
            return dic

        if type == 'int':
            value = int(datavalue)
        elif type == 'float':
            value = float(datavalue)
        else:
            value = datavalue
        dict_to_update = get_dict_to_update(datavar, value)
        update_datarepository(dict_to_update)
        print_info("Value: {0} is stored in a Key:{1} of Warrior "
                   "data_repository ".format(datavalue, datavar))
        return True
    def testcase_prerun(self, tc_filepath, check_files_dict=None):
        """Executes prerun of a testcase file """
        print('\n')
        print_info('=' * 40)
        print_debug("Validating Test case xml")
        print_info('=' * 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
예제 #7
0
def print_suite_details_to_console(suite_repository, testsuite_filepath,
                                   junit_resultfile):
    """Prints the testsuite details to console """

    print_info("\n\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$  TESTSUITE-DETAILS  "
               "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n")

    print_info("Executing testsuite '{0}'".format(
        suite_repository['suite_name'].strip()))
    print_info("Title: {0}".format(suite_repository['suite_title'].strip()))
    print_info("Results directory: %s" %
               suite_repository['suite_execution_dir'])
    report_suite_requirements(suite_repository, testsuite_filepath)
    time.sleep(3)
예제 #8
0
def decide_overwrite_var(namespace):
    """options provided in cli get preference over the ones provided inside tests
    """
    overwrite = {}
    if namespace.datafile:
        if namespace.datafile[0] != os.sep:
            namespace.datafile = os.getcwd() + os.sep + namespace.datafile
        overwrite['ow_datafile'] = namespace.datafile
    #namespace for wrapperfile
    if namespace.wrapperfile:
        if namespace.wrapperfile[0] != os.sep:
            namespace.wrapperfile = os.getcwd() + os.sep + namespace.wrapperfile
        overwrite['ow_testwrapperfile'] = namespace.wrapperfile
    if namespace.resultdir:
        if namespace.resultdir[0] != os.sep:
            namespace.resultdir = os.getcwd() + os.sep + namespace.resultdir
        overwrite['ow_resultdir'] = namespace.resultdir
    if namespace.logdir:
        if namespace.logdir[0] != os.sep:
            namespace.logdir = os.getcwd() + os.sep + namespace.logdir
        overwrite['ow_logdir'] = namespace.logdir
    if namespace.outputdir:
        if namespace.outputdir[0] != os.sep:
            namespace.outputdir = os.getcwd() + os.sep + namespace.outputdir
        overwrite['ow_resultdir'] = namespace.outputdir
        overwrite['ow_logdir'] = namespace.outputdir
    if all([namespace.outputdir, any([namespace.resultdir, namespace.logdir])]):
        print_error("outputdir shouldn't be used with resultdir or logdir")
        exit(1)
    if namespace.jobid:
        settings_xml = Tools.__path__[0] + os.sep + 'w_settings.xml'
        job_url = get_credentials(settings_xml, 'job_url', ['url'], 'Setting')
        if job_url['url'] is not None:
            url = job_url['url']
        else:
            print_info("jobid is specified but no job url found in w_settings")
            print_info("Using jobid only in JUnit file")
            url = ""
        overwrite['jobid'] = url + str(namespace.jobid)
    return overwrite
    def __check_dir_exists(cls, filepath, dirtag):
        """ Verify that the directory exists in the path provided.

        Arguments:
              1. filepath: file path will be parsed as input for checking
                 directories
              2. dirtag: directory tag that used to get directory path
        """

        dirt = xml_Utils.getChildTextbyParentTag(filepath, 'Details', dirtag)
        directory = file_Utils.getAbsPath(dirt, os.path.dirname(filepath))

        if directory is not False and directory is not None:
            print_info("{0} path {1}".format(dirtag, directory))
            if not os.path.exists(directory):
                print_warning("Directory does not exist in location {0}."\
                "\nWarrior framework will try to create the directory, if creation "\
                "fails then default warriorspace will be used to collect logs/results"\
                .format(directory))
        else:
            if dirtag is 'Resultsdir':
                print_info(
                    "Default directory in Warriorspace will be used to collect results"
                )
            else:
                print_info(
                    "Default directory in Warriorspace will be used to collect logs"
                )
예제 #10
0
def update_jira_by_id(jiraproj, jiraid, exec_dir, status):
    """ If jiraid is provided, upload the log and result file to jira """
    if jiraid is not False:
        jira_obj = Jira(jiraproj)
        if jira_obj.status is True:
            # Get the current jira issue status
            issue_status = jira_obj.get_jira_issue_status(jiraid)
            isReopend = False
            # Reopen the jira issue if it is closed, to upload the execution logs
            if issue_status and issue_status.lower() == "closed":
                print_info("Reopening Jira issue '{0}' to upload warrior "
                           "execution logs".format(jiraid))
                jira_obj.set_jira_issue_status(jiraid, "Reopened")
                isReopend = True
            # Upload execution logs
            zip_file = shutil.make_archive(exec_dir, 'zip', exec_dir)
            jira_obj.upload_logfile_to_jira_issue(jiraid, zip_file)
            # Close the jira issue if it is reopened in the above if block
            if isReopend is True:
                print_info("Closing Jira issue '{0}' which was reopened "
                           "earlier".format(jiraid))
                jira_obj.set_jira_issue_status(jiraid, "Closed")
            # Update Jira issue based on warrior execution status
            jira_obj.update_jira_issue(jiraid, status)
    else:
        print_info("jiraid not provided, will not update jira issue")
def create_defects(auto_defects, data_repository):
    """Creates the defects json files for the testcase executed
    If auto_defects = True create bugs in jira for the associated project provided in jira
    config file
    """
    defect_obj = DefectsDriver(data_repository)
    json_status = defect_obj.create_failing_kw_json()

    if json_status:
        if auto_defects:
            print_info("auto-create defects ")
            defects_json_list = defect_obj.get_defect_json_list()
            if len(defects_json_list) == 0:
                print_warning(
                    "No defect json files found in defects directory '{0}' of this "
                    "testcase".format(data_repository['wt_defectsdir']))
            elif len(defects_json_list) > 0:
                connect = defect_obj.connect_warrior_jira()
                if connect is True:
                    defect_obj.create_jira_issues(defects_json_list)
        else:
            print_info("auto-create defects was Not requested")
예제 #12
0
 def _check_property(self, element, **kwargs):
     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
예제 #13
0
 def suite_summary(self, junit_file):
     """ To get the name, status and location of both test suite and test case"""
     tree = xml_Utils.get_tree_from_file(self.junit_file)
     file_type = self.get_file_type(junit_file)
     for values in tree.iter('testsuite'):
         suite_detail = values.attrib
         suite_name = suite_detail.get('name')
         suite_status = suite_detail.get('status')
         suite_location = suite_detail.get('suite_location')
         if suite_location != None:
             print_info("{0:10}{1:50}{2:10}{3:30}".format(
                 "Suites", suite_name, suite_status, suite_location))
         for value in tree.iter('testcase'):
             testcase_details = value.attrib
             testcase_status = testcase_details.get('status')
             suite_name_from_tc = testcase_details.get('classname')
             testcase_location = testcase_details.get('testcasefile_path')
             testcase_name = testcase_details.get('name') + ".xml"
             if suite_name == suite_name_from_tc:
                 print_info("{0:10}{1:50}{2:10}{3:30}".format(
                     "Testcase", testcase_name, testcase_status,
                     testcase_location))
예제 #14
0
    def project_prerun(self, project_filepath, root):
        """Executes prerun of a project file """

        print('\n')
        print_info('+'*40)
        print_debug("Validating Project xml")
        print_info('+'*40)
        project_xsd_fullpath = self.xsd_dir + os.sep + 'warrior_project.xsd'
        project_status = self.xml_to_xsd_validation(project_filepath, project_xsd_fullpath)
        if project_status:
            check_files_dict = self.check_proj_results_logsdir(project_filepath)
            for testsuite in root.iter('Testsuite'):
                testsuite_path_rel = testsuite_utils.get_path_from_xmlfile(testsuite)
                testsuite_path = file_Utils.getAbsPath(testsuite_path_rel,
                                                       os.path.dirname(project_filepath))

                if os.path.isfile(testsuite_path):
                    print('\n')
                    print_info("Testsuite_path: {0}, Testsuite"\
                               "file exists...".format(testsuite_path))
                    ts_root = xml_Utils.getRoot(testsuite_path)
                    tsuite_status = self.testsuite_prerun(testsuite_path, ts_root, check_files_dict)
                else:
                    print('\n')
                    tsuite_status = False
                    print_error('testsuite_path: {0},\
                                Testsuite file does not exist'.format(testsuite_path))
                    print_info('SUITE STATUS: {0}'.format('FAILED'))
                project_status &= tsuite_status

        else:
            print_error("Incorrect xml format")

        time.sleep(5)
        print('\n')
        status = testcase_Utils.convertLogic(project_status)
        print_info('PROJECT STATUS: {0}ED'.format(status))

        return project_status
예제 #15
0
def getErrorHandlingParameters(node, def_on_error_action, def_on_error_value,
                               exec_type):
    """Takes a xml element at input and returns the values for on_error action , value
    If no value is available in the node then returns the default values """

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

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

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

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

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

    return action, value
 def subscribe_to_topics(self, topics, **kwargs):
     """
     Subscribe to list of specified topics.
     Arguments:
       topics(list): list of topic names to subscribe
       pattern(list): list of topic name patterns to subscribe
       listener(func): callback function
     Returns:
       result(bool) : False if exception occures, True otherwise
     """
     pattern = kwargs.get("pattern", None)
     listener = kwargs.get("listener", None)
     print_info("subscribe to topics {}".format(topics))
     try:
         self.kafka_consumer.subscribe(topics=topics,
                                       pattern=pattern,
                                       listener=listener)
         result = True
     except KafkaError as exc:
         print_error("Exception during subscribing to topics - {}".format(exc))
         result = False
     return result
예제 #17
0
    def open_browser(self, browser_name='firefox', webdriver_remote_url=False,
                     desired_capabilities=None, binary=None, gecko_path=None,
                     **kwargs):
        """Open a browser session"""

        profile_dir = kwargs.get('profile_dir', None)

        if webdriver_remote_url:
            print_debug("Opening browser '{0}' through remote server at '{1}'"\
                        .format(browser_name, webdriver_remote_url))
        else:
            print_debug("Opening browser '%s'" % (browser_name))
        browser_name = browser_name
        browser = self._make_browser(browser_name, desired_capabilities,
                                     profile_dir, webdriver_remote_url,
                                    binary=binary, gecko_path=gecko_path)
        print_info("The Selenium Webdriver version is '{0}'".format(webdriver.__version__))
        if browser:
            browser_detail_dict = self.get_browser_details(browser)
            for details, value in browser_detail_dict.items():
                print_info("The Browser '{0}' {1} is '{2}'".format(browser_name, details, value))
        return browser
예제 #18
0
def get_testsuite_list(project_filepath):
    """Takes the location of any Project.xml file as input
    Returns a list of all the Testsuite elements present in the Project"""

    testsuite_list_new = []
    root = Utils.xml_Utils.getRoot(project_filepath)
    testsuites = root.find('Testsuites')
    if testsuites is None:
        print_info('Testsuite is empty: tag <Testsuites> not "\
                   "found in the input file ')
    else:
        testsuite_list = testsuites.findall('Testsuite')
        for ts in testsuite_list:
            runmode, value = common_execution_utils.\
                get_runmode_from_xmlfile(ts)
            retry_type, _, _, retry_value, _ = common_execution_utils.\
                get_retry_from_xmlfile(ts)
            if runmode is not None and value > 0:
                # more than one suite in suite list, insert new suite
                go_next = len(testsuite_list_new) + value + 1
                for i in range(0, value):
                    copy_ts = copy.deepcopy(ts)
                    copy_ts.find("runmode").set("value", go_next)
                    copy_ts.find("runmode").set("attempt", i + 1)
                    testsuite_list_new.append(copy_ts)
            if retry_type is not None and retry_value > 0:
                if len(testsuite_list) > 1:
                    go_next = len(testsuite_list_new) + retry_value + 1
                    if runmode is not None:
                        get_runmode = ts.find('runmode')
                        ts.remove(get_runmode)
                    for i in range(0, retry_value):
                        copy_ts = copy.deepcopy(ts)
                        copy_ts.find("retry").set("count", go_next)
                        copy_ts.find("retry").set("attempt", i + 1)
                        testsuite_list_new.append(copy_ts)
            if retry_type is None and runmode is None:
                testsuite_list_new.append(ts)
        return testsuite_list_new
예제 #19
0
    def wait_for_timeout(self, timeout, notify_count=4):
        """waits (sleeps) for the time provided

        :Arguments:
            1. timeout= time to wait in seconds
            2. 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%)
        :Returns:
            1. status (bool)
        """

        WDesc = "Waits for the timeout provided"
        Utils.testcase_Utils.pSubStep(WDesc)
        print_info("Command timeout for {0} seconds".format(timeout))
        status = datetime_utils.wait_for_timeout(timeout, notify_count=notify_count)
        pNote('********Below Testing occured after Timeout *********')
        Utils.testcase_Utils.report_substep_status(status)
        return status
예제 #20
0
    def create_jira_issue(self, issue_summary, issue_description, issue_type='Bug'):
        """
        Function to Create jira Ticket using JIRA rest API
        :Arguments:
            1. issue_summary(str) - Jira issue ID
            2. issue_description(str) - warrior execution status
            3. issue_type(str) - Jira issue type(Ex. Story/Bug/Task)
        :Returns:
            1. issue_id(str/boolean) - (a) issue_key if created
                                       (b) False if not created
                                       (c) issue_key if already exists and the append_log is True
                                       (d) False if already exists and the append_log is not True
        """
        issue_id = False
        issue_summary = issue_summary.replace('"', " ")
        issue_description = issue_description.replace('"', "-")
        postdata_url = self.server + '/rest/api/2/issue/'
        headers = {"Content-Type": "application/json"}
        postdata = """
        {
            "fields": {
                "project":
                {
                    "key": \""""+self.project_key+"""\"
                },
                "summary": \""""+issue_summary+"""\",
                "description": \""""+issue_description+"""\",
                "issuetype": {
                    "name": \""""+issue_type+"""\"
                }
            }
        }
        """

        existed = self.check_jira_issue(issue_summary)
        if not existed:
            # POST request to create new Jira issue
            response = requests.post(postdata_url, auth=self.auth,
                                     headers=headers, data=postdata)
            if response:
                resp_dict = response.json()
                issue_id = str(resp_dict['key'])
                print_info("JIRA Issue Created. Issue-Id: {0}".format(issue_id))
            else:
                print_error("Problem creating JIRA issue")
                print_error("JIRA Error code: ({0}), Error message: ({1})".
                            format(response.status_code, response.reason))
        else:
            if self.append:
                print_info("Issue '{0}' already exists and the execution logs "
                           "will be uploaded since the 'append_log' option is "
                           "set to True in jira config file".format(str(existed)))
                issue_id = existed
            else:
                print_info("Issue '{0}' already exists and the execution logs "
                           "will not be uploaded since the 'append_log' option is "
                           "not set to True in jira config file".format(str(existed)))

        return issue_id
예제 #21
0
 def go_to(self, url, browser_instance=None):
     """Navigates the active browser instance to the provided URL."""
     status = True
     try:
         print_info("Opening url '%s'" % url)
         if browser_instance is not None:
             browser_instance.get(url)
         else:
             self.current_browser.get(url)
     except WebDriverException as err:
         print_error(err)
         if "Reached error page" in str(err):
             print_error("Unable to Navigate to URL:{}"\
                         "possibly because of the url is not valid".format(url))
         else:
             status = False
     except Exception as err:
         print_error(err)
         status = False
         print_error("Unable to Navigate to URL:'%s'" % url)
         traceback.print_exc()
     return status
예제 #22
0
    def copy_file(self, remotepath, localpath, filename):
        """Get the file from remotepath

        :Argument:
             1. remotepath - File path in the remote server
             2. localpath - Local path to save the file
             3. filename - Filename of the file to be tranferred

        :Returns:
             1. status(bool)= True / False
        """
        sftpobj = self.sshobj.open_sftp()
        print_info("Copying {} from {} to {}".format(filename, remotepath,
                                                     localpath))
        if filename:
            remotepath = os.path.join(remotepath, filename)
            localpath = os.path.join(localpath, filename)
        sftpobj.get(remotepath, localpath)
        if os.path.isfile(localpath):
            return True
        else:
            return False
예제 #23
0
    def upload_logfile_to_jira_issue(self,
                                     issue_id,
                                     logfile,
                                     attachment_name=None):
        """Function to attach logs to Jira Ticket using JIRA rest API"""

        fetchuri = self.server
        postdata_url = fetchuri + '/rest/api/2/issue/' + issue_id + '/attachments'
        credential_handler = self.username + ":" + self.password
        password = base64.b64encode(credential_handler)
        boundary = '----------%s' % ''.join(
            random.sample('0123456789abcdef', 15))
        post_data = []
        post_data.append('--%s' % boundary)
        post_data.append(
            'Content-Disposition: form-data; name="file"; filename="%s"' %
            str(logfile.split("/")[-1]))
        post_data.append('Content-Type: %s' % 'text/plain')
        post_data.append('')
        post_data.append(open(logfile, 'r').read())
        post_data.append('--%s--' % boundary)
        post_data.append('')
        body = '\r\n'.join(post_data)
        req = urllib2.Request(str(postdata_url), body)
        req.add_header("X-Atlassian-Token", "nocheck")
        req.add_header("Authorization", "Basic " + password)
        req.add_header("Content-Type",
                       "multipart/form-data; boundary=%s" % boundary)
        try:
            handler = urllib2.urlopen(req)
            extension = json.loads(handler.read())
            print_info("Log File {0} uploaded to Issue-Id: {1}".format(
                logfile.split("/")[-1], issue_id))
        except urllib2.HTTPError, e:
            pNote("Problem attaching logs to JIRA issue {0}".format(issue_id),
                  "error")
            pNote("JIRA Error code: ({0})".format(e.code), "error")
            exit(1)
예제 #24
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
예제 #25
0
    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
예제 #26
0
    def get_element(self, browser, locator, **kwargs):
        """Get an element based on the locator and value
        - By defaults gets a single element,
        - To get the list of all elements matching the value
        use findall='y' as argument.

        :Arguments:
            - browser = instance of selenium webdriver browser.
            - locator = how to locate the element in the webpage.
                        supported format: "supported locator value = value for the locator"
                        1. to locate element by its id:
                            format = "id=id of the element"
                            eg: "id=j_username" will find the element whose\
                            id is j_username
                        2. "name=name of the element"
                        3. "xpath=xpath of the element"
                        4. "link=link to the element"
                        5. "partial_link=partial link to the element"
                        6. "tag=tag of the element"
                        7. "class=class of the element"
                        8. "css=css of the element"
            - **kwargs:
                1. findall = 'y' - finds all the elements with matching value
                           = None - finds the first elemtn with matching value.

        :Returns:
            - the selenium webdriver element if found.
            - None if element was not found
            (prints a NoSuchElementException message to the user)
        """
        assert browser is not None
        print_info("Finding element by {0}"\
                    .format(locator))
        element = self._get_element(browser, locator, **kwargs)
        if element is None:
            print_error("Could not find element(s) with {0}"\
                        .format(locator))
        return element
예제 #27
0
    def testsuite_prerun(self, testsuite_filepath, root, check_files_dict=None):
        """Executes prerun of a testsuite file """
        print('\n')
        print_info('*'*40)
        print_debug("Validating Test suite xml")
        print_info('*'*40)

        testsuite_xsd_fullpath = self.xsd_dir + os.sep + 'warrior_suite.xsd'
        testsuite_status = self.xml_to_xsd_validation(testsuite_filepath, testsuite_xsd_fullpath)
        if testsuite_status:
            data_file_valid, check_files_dict = self.check_testsuite_input_datafile(\
                testsuite_filepath, check_files_dict)
            testsuite_status &= data_file_valid
            for testcase in root.iter('Testcase'):
                tc_path_rel = testsuite_utils.get_path_from_xmlfile(testcase)
                tc_path = file_Utils.getAbsPath(tc_path_rel,
                                                os.path.dirname(testsuite_filepath))
                time.sleep(5)
                if os.path.isfile(tc_path):
                    print('\n')
                    print_info('tc_path: {0}, Testcase file exists...'.format(tc_path))
                    tc_status = self.testcase_prerun(tc_path, check_files_dict)
                else:
                    print('\n')
                    tc_status = False
                    print_error('tc_path: {0}, Testcase file does not exist'.format(tc_path))
                    print_info('TC STATUS: {0}'.format('FAILED'))
                testsuite_status &= tc_status

        else:
            print_error("Incorrect xml format")

        time.sleep(5)
        print('\n')
        status = testcase_Utils.convertLogic(testsuite_status)
        print_info('SUITE STATUS: {0}ED'.format(status))

        return testsuite_status
예제 #28
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
    def convert_string_to_datatype(self):
        """Converts an input string to a python datatype """

        err_msg = ("\nUser input argument value {0} does not match python "
                   "syntax for '{1}'").format(self.arg_value, self.datatype)
        info_msg = ("Warrior FW will handle user input argument value as "
                    "string (default)\n")
        result = self.arg_value
        try:
            if self.datatype is not IOBase:
                result = ast.literal_eval(self.arg_value)
        except Exception:
            print_error(err_msg)
            print_info(info_msg)
            print_error('unexpected error: {0}'.format(traceback.format_exc()))
            result = self.arg_value
        else:
            if self.datatype is not IOBase and not isinstance(
                    result, self.datatype):
                print_error(err_msg)
                print_info(info_msg)
                result = self.arg_value
        return result
 def create_partitions_in_topic(self, partitions, **kwargs):
     """
     create partitions in topic
     Arguments:
       partitions(list) : list of ['topic_name','num_partitions'] lists
       example : [['topic1',4], ['topic2',5]]
       timeout(int): timeout in milliseconds
     Returns:
       result(bool) : False if exception occures, True otherwise
     """
     timeout = kwargs.get("timeout", None)
     validate = kwargs.get("validate", False)
     topic_partitions = {tup[0]:NewPartitions(total_count=tup[1]) for tup in partitions}
     print_info("creating partitions in topic")
     try:
         self.kafka_client.create_partitions(topic_partitions=topic_partitions,
                                             timeout_ms=timeout,
                                             validate_only=validate)
         result = True
     except KafkaError as exc:
         print_error("Exception during creating partitions - {}".format(exc))
         result = False
     return result