當前位置: 首頁>>代碼示例>>Python>>正文


Python junit_xml.TestCase方法代碼示例

本文整理匯總了Python中junit_xml.TestCase方法的典型用法代碼示例。如果您正苦於以下問題:Python junit_xml.TestCase方法的具體用法?Python junit_xml.TestCase怎麽用?Python junit_xml.TestCase使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在junit_xml的用法示例。


在下文中一共展示了junit_xml.TestCase方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: handle_event

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def handle_event(self, context: ExecutionContext, event: events.ExecutionEvent) -> None:
        if isinstance(event, events.Initialized):
            self.start_time = event.start_time
        if isinstance(event, events.AfterExecution):
            test_case = TestCase(
                f"{event.result.method} {event.result.path}",
                elapsed_sec=event.elapsed_time,
                allow_multiple_subelements=True,
            )
            if event.status == Status.failure:
                checks = get_unique_failures(event.result.checks)
                for idx, check in enumerate(checks, 1):
                    # `check.message` is always not empty for events with `failure` status
                    test_case.add_failure_info(message=f"{idx}. {check.message}")
            if event.status == Status.error:
                test_case.add_error_info(
                    message=event.result.errors[-1].exception, output=event.result.errors[-1].exception_with_traceback
                )
            self.test_cases.append(test_case)
        if isinstance(event, events.Finished):
            test_suites = [TestSuite("schemathesis", test_cases=self.test_cases, hostname=platform.node())]
            to_xml_report_file(file_descriptor=self.file_handle, test_suites=test_suites, prettyprint=True) 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:24,代碼來源:junitxml.py

示例2: write_xml_file

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def write_xml_file(self):
    test_cases = []
    if os.path.isfile(self.output):
      logging.warn("File exists,deleting...")
      os.remove(self.output)
    with open(self.output,'a') as f:
      for _, elements in self.log.items():
        for j in elements.viewitems():
          if j[0] == 'date' or j[0] == 'profile' or j[0] == 'score':
            # we really don't care
            pass
          else:
            try:
              test_case = TestCase(j[0], j[1]['descr'], '', '', '')
              if j[1]['status'] == 'Fail':
                test_case.add_failure_info(j[1]['output'])
              else:
                test_case = TestCase(j[0], '', '', '', '')
              test_cases.append(test_case)
            except KeyError:
              # the world's smallest violin playin' for KeyError
              pass
      ts = [TestSuite("Docker Security Benchmarks", test_cases)]
      TestSuite.to_file(f, ts) 
開發者ID:zuBux,項目名稱:drydock,代碼行數:26,代碼來源:output.py

示例3: print_result_cache_junitxml

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def print_result_cache_junitxml(dict_synonyms, suspicious_policy, untested_policy):
    test_cases = []
    mutant_list = list(select(x for x in Mutant))
    for filename, mutants in groupby(mutant_list, key=lambda x: x.line.sourcefile.filename):
        for mutant in mutants:
            tc = TestCase("Mutant #{}".format(mutant.id), file=filename, line=mutant.line.line_number, stdout=mutant.line.line)
            if mutant.status == BAD_SURVIVED:
                tc.add_failure_info(message=mutant.status, output=get_unified_diff(mutant.id, dict_synonyms))
            if mutant.status == BAD_TIMEOUT:
                tc.add_error_info(message=mutant.status, error_type="timeout", output=get_unified_diff(mutant.id, dict_synonyms))
            if mutant.status == OK_SUSPICIOUS:
                if suspicious_policy != 'ignore':
                    func = getattr(tc, 'add_{}_info'.format(suspicious_policy))
                    func(message=mutant.status, output=get_unified_diff(mutant.id, dict_synonyms))
            if mutant.status == UNTESTED:
                if untested_policy != 'ignore':
                    func = getattr(tc, 'add_{}_info'.format(untested_policy))
                    func(message=mutant.status, output=get_unified_diff(mutant.id, dict_synonyms))

            test_cases.append(tc)

    ts = TestSuite("mutmut", test_cases)
    print(TestSuite.to_xml_string([ts])) 
開發者ID:boxed,項目名稱:mutmut,代碼行數:25,代碼來源:cache.py

示例4: get_test_suites

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def get_test_suites(self):
        test_cases = {}
        test_suites = []
        records = self.passed_checks + self.failed_checks + self.skipped_checks
        for record in records:
            check_name = record.check_name
            if check_name not in test_cases:
                test_cases[check_name] = []

            test_name = "{} {} {}".format(self.check_type, check_name, record.resource)
            test_case = TestCase(name=test_name, file=record.file_path, classname=record.check_class)
            if record.check_result['result'] == CheckResult.FAILED:
                test_case.add_failure_info(
                    "Resource \"{}\" failed in check \"{}\"".format(record.resource, check_name))
            if record.check_result['result'] == CheckResult.SKIPPED:
                test_case.add_skipped_info(
                    "Resource \"{}\" skipped in check \"{}\"\n Suppress comment: {}".format(record.resource, check_name,
                                                                                            record.check_result[
                                                                                                'suppress_comment']))
            test_cases[check_name].append(test_case)
        for key in test_cases.keys():
            test_suites.append(
                TestSuite(name=key, test_cases=test_cases[key], package=test_cases[key][0].classname))
        return test_suites 
開發者ID:bridgecrewio,項目名稱:checkov,代碼行數:26,代碼來源:report.py

示例5: get_junit_items

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def get_junit_items(self, new_items=''):
        """
        Convert from canonical data model to junit test suit
        :param new_items:
        :return:
        """
        test_cases = []
        if not self.test_items and not new_items:
            raise ValueError('There it no test items')
        data = self.test_items if not new_items else new_items

        for item in data:
            tc = TestCase(item.issue, classname=item.confidence)
            message = ''
            for msg in item.msgs:
                message = message + msg.message + "\n\n"
            tc.add_error_info(message=message, error_type=item.severity)
            test_cases.append(tc)
        ts = TestSuite(self.report_name, test_cases)
        return ts 
開發者ID:dowjones,項目名稱:reapsaw,代碼行數:22,代碼來源:Converter.py

示例6: _generate_junit_xml

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def _generate_junit_xml(self, config_name):
      testcases = []
      tests=self.data_source.get_test_results(config_name)
      for test in tests:
          test_time = 0
          if test.func_end_time != None and test.func_start_time != None:
              test_time = test.func_end_time - test.func_start_time
          tc = TestCase(test.name,config_name,test_time, test.description, test.message)
          if 'failed' in test.result:
              tc.add_failure_info(test.result)
          elif 'skipped' in test.result:
              tc.add_skipped_info(test.result)
          testcases.append(tc)
      testsuite = TestSuite(config_name+'_'+self.name, testcases)
      return testsuite 
開發者ID:linkedin,項目名稱:Zopkio,代碼行數:17,代碼來源:junit_reporter.py

示例7: post_test

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def post_test(self, test_num):
        """Called after a test is completed, perform cleanup etc."""
        if self.report.get('report') is None:
            self.report.add('reason', self.report.get_status())
        super(ServerTarget, self).post_test(test_num)
        if self.report.get_status() != Report.PASSED:
            if self.junit_report_path:
                test_case = TestCase(name=self.test_number, status=self.report.get_status())
                test_case.add_failure_info(message=json.dumps(self.report.to_dict()))
                self.failed_test.append(test_case)
            self.save_report_to_disc() 
開發者ID:KissPeter,項目名稱:APIFuzzer,代碼行數:13,代碼來源:fuzz_request_sender.py

示例8: teardown

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def teardown(self):
        if len(self.failed_test):
            test_cases = self.failed_test
        else:
            test_cases = list()
            test_cases.append(TestCase(name='Fuzz test succeed', status='Pass'))
        if self.junit_report_path:
            with open(self.junit_report_path, 'w') as report_file:
                TestSuite.to_file(report_file, [TestSuite("API Fuzzer", test_cases)], prettyprint=True)
        super(ServerTarget, self).teardown() 
開發者ID:KissPeter,項目名稱:APIFuzzer,代碼行數:12,代碼來源:fuzz_request_sender.py

示例9: file_junit_report

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def file_junit_report(rules, report):
    """
    Output file Junit xml report

    :param rules: set of rules to verify
    :param report: report generated by drheader
    :return: None
    """

    test_cases = []

    for header in rules:
        tc = []
        for item in report:
            if item.get('rule') == header:
                violation = item.copy()
                violation.pop('rule')
                message = violation.pop('message')
                tc = TestCase(name=header + ' :: ' + message)
                tc.add_failure_info(message, violation)
                test_cases.append(tc)
        if not tc:
            tc = TestCase(name=header)
            test_cases.append(tc)

    os.makedirs('reports', exist_ok=True)
    with open('reports/junit.xml', 'w') as f:
        TestSuite.to_file(f, [TestSuite(name='DrHeader', test_cases=test_cases)], prettyprint=False)
        f.close() 
開發者ID:Santandersecurityresearch,項目名稱:DrHeader,代碼行數:31,代碼來源:cli_utils.py

示例10: add_junit_test

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def add_junit_test(test_cases, testname, succ, message='default message', elapsed_sec=0):
  test_case = TestCase(testname, elapsed_sec = elapsed_sec)
  if not succ:
    test_case.add_failure_info(message)
  test_cases.append(test_case) 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:7,代碼來源:utils.py

示例11: toplevel_to_junit

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def toplevel_to_junit(
    num: int, toplevel: TestcaseExecution
) -> typing.List[junit_xml.TestCase]:
    """Convert a toplevel testcase to junit testcases."""
    testcases: typing.List[junit_xml.TestCase] = []
    _, testcases = testcase_to_junit(
        f"{num:02} - {toplevel.name}", 0, toplevel.name, toplevel, True
    )
    return testcases 
開發者ID:Rahix,項目名稱:tbot,代碼行數:11,代碼來源:junit.py

示例12: testcase_to_junit

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def testcase_to_junit(
    toplevel: str,
    i: int,
    cls_path: str,
    testcase: TestcaseExecution,
    is_toplevel: bool = False,
) -> typing.Tuple[int, typing.List[junit_xml.TestCase]]:
    """Convert a testcase to junit testcases."""
    testcases = []
    my_cls_path = cls_path if is_toplevel else f"{cls_path} -> {testcase.name}"
    tc = junit_xml.TestCase(
        f"99999 - Summary {testcase.name}",
        classname=f"{toplevel}.{i:05} - {my_cls_path}",
    )
    if not testcase.success:
        if testcase.exc is not None:
            tc.add_error_info(f'Testcase failed with "{testcase.exc}"', testcase.trace)
        else:
            tc.add_error_info(f"Testcase failed because of sub testcase failure")
    testcases.append(tc)
    old_i = i
    i += 1
    for step_id, step in enumerate(testcase.sub_steps):
        if isinstance(step, TestcaseExecution):
            tc = junit_xml.TestCase(
                f"{step_id:05} - Testcase: {step.name}",
                classname=f"{toplevel}.{old_i:05} - {my_cls_path}",
            )
            testcases.append(tc)
            i_new, testcases_new = testcase_to_junit(toplevel, i, my_cls_path, step)
            i = i_new
            testcases += testcases_new
        elif isinstance(step, ShellStep):
            tc = junit_xml.TestCase(
                f"{step_id:05} - Shell: {step.command}",
                classname=f"{toplevel}.{old_i:05} - {my_cls_path}",
                stdout=step.output,
            )
            testcases.append(tc)
    return i, testcases 
開發者ID:Rahix,項目名稱:tbot,代碼行數:42,代碼來源:junit.py

示例13: main

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def main() -> None:
    """Generate a JUnit XML file."""

    log = logparser.from_argv()

    toplevels = parse_log(log)
    testcases: typing.List[junit_xml.TestCase] = []
    for i, toplevel in enumerate(toplevels):
        testcases += toplevel_to_junit(i, toplevel)
    print(
        json.dumps(list(map(lambda x: f"{x.classname}", testcases)), indent=4),
        file=sys.stderr,
    )

    print(junit_xml.TestSuite.to_xml_string([junit_xml.TestSuite("tbot", testcases)])) 
開發者ID:Rahix,項目名稱:tbot,代碼行數:17,代碼來源:junit.py

示例14: take_action

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def take_action(self, args):
        test_cases = []
        if args.playbook is not None:
            playbooks = args.playbook
            results = (models.TaskResult().query
                       .join(models.Task)
                       .filter(models.TaskResult.task_id == models.Task.id)
                       .filter(models.Task.playbook_id.in_(playbooks)))
        else:
            results = models.TaskResult().query.all()

        for result in results:
            task_name = result.task.name
            if not task_name:
                task_name = result.task.action
            additional_results = {
                'host': result.host.name,
                'playbook_path': result.task.playbook.path
            }
            result_str = jsonutils.dumps(additional_results)
            test_path = \
                u'{playbook_file}.{play_name}'.format(
                    playbook_file=os.path.basename(result.task.playbook.path),
                    play_name=result.task.play.name)
            test_case = TestCase(
                name=task_name,
                classname=test_path,
                elapsed_sec=result.duration.seconds,
                stdout=result_str)
            if result.status == 'skipped':
                test_case.add_skipped_info(message=result.result)
            elif (result.status in ('failed', 'unreachable') and
                    result.ignore_errors is False):
                test_case.add_failure_info(message=result.result)
            test_cases.append(test_case)
        test_suite = TestSuite('Ansible Tasks', test_cases)

        # TODO: junit_xml doesn't order the TestCase parameters.
        # This makes it so the order of the parameters for the same exact
        # TestCase is not guaranteed to be the same and thus results in a
        # different stdout (or file). This is easily reproducible on Py3.
        xml_string = six.text_type(test_suite.to_xml_string([test_suite]))
        if args.output_file == '-':
            if six.PY2:
                sys.stdout.write(encodeutils.safe_encode(xml_string))
            else:
                sys.stdout.buffer.write(encodeutils.safe_encode(xml_string))
        else:
            with open(args.output_file, 'wb') as f:
                f.write(encodeutils.safe_encode(xml_string)) 
開發者ID:dmsimard,項目名稱:ara-archive,代碼行數:52,代碼來源:generate.py

示例15: _build_test_case

# 需要導入模塊: import junit_xml [as 別名]
# 或者: from junit_xml import TestCase [as 別名]
def _build_test_case(self, task_data, host_data):
        """Build a TestCase from the given TaskData and HostData."""

        name = '[%s] %s: %s' % (host_data.name, task_data.play, task_data.name)
        duration = host_data.finish - task_data.start

        if self._task_class == 'true':
            junit_classname = re.sub(r'\.yml:[0-9]+$', '', task_data.path)
        else:
            junit_classname = task_data.path

        if host_data.status == 'included':
            return TestCase(name, junit_classname, duration, host_data.result)

        res = host_data.result._result
        rc = res.get('rc', 0)
        dump = self._dump_results(res, indent=0)
        dump = self._cleanse_string(dump)

        if host_data.status == 'ok':
            return TestCase(name, junit_classname, duration, dump)

        test_case = TestCase(name, junit_classname, duration)

        if host_data.status == 'failed':
            if 'exception' in res:
                message = res['exception'].strip().split('\n')[-1]
                output = res['exception']
                test_case.add_error_info(message, output)
            elif 'msg' in res:
                message = res['msg']
                test_case.add_failure_info(message, dump)
            else:
                test_case.add_failure_info('rc=%s' % rc, dump)
        elif host_data.status == 'skipped':
            if 'skip_reason' in res:
                message = res['skip_reason']
            else:
                message = 'skipped'
            test_case.add_skipped_info(message)

        return test_case 
開發者ID:redhat-openstack,項目名稱:infrared,代碼行數:44,代碼來源:junit_report.py


注:本文中的junit_xml.TestCase方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。