当前位置: 首页>>代码示例>>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;未经允许,请勿转载。