官方文档:API Reference — pytest documentation
BaseReport 定义Case结果输出
>>> from _pytest.reports import TestReport
>>> test = TestReport(1,1,1,'pass','','running')
>>> print(dir(test))
['__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__test__', '__weakref__', '_from_json', '_get_verbose_word', '_to_json', 'caplog', 'capstderr', 'capstdout', 'count_towards_summary', 'duration', 'failed', 'from_item_and_call', 'fspath', 'get_sections', 'head_line', 'keywords', 'location', 'longrepr', 'longreprtext', 'nodeid', 'outcome', 'passed', 'sections', 'skipped', 'toterminal', 'user_properties', 'when']
pluggy — pluggy 1.3.1.dev11+g46fec3f documentationhttps://pluggy.readthedocs.io/en/latest/index.html#hookwrappers
# pytest插件 https://www.osgeo.cn/pytest/writing_plugins.html
import pytest@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):print('-------------------------------')# 获取常规的钩子方法的调用结果,返回一个result对象out = yieldprint('用例的执行结果', out)# 获取调用结果的测试报告,返回一个report对象,report对象的属性# 包括when(setup, call, teardown三个值)、nodeid(测试用例的名字)、# outcome(用例执行的结果 passed, failed)report = out.get_result()print('测试报告: %s' % report)print('步骤:%s' % report.when)print('nodeid: %s' % report.nodeid)# 打印函数注释信息print('description: %s' % str(item.function.__doc__))print('运行结果: %s' % report.outcome)
case运行不同步骤,重写pytest处理结果
print('步骤:%s' % report.when)if when == "call":custom.running_test(item, call, report)if when == 'setup':custom.before_test(item, call, report)if when == 'teardown':custom.after_test(item, call, report)
获取case运行时失败信息
excinfo = call.excinfotrace_info = traceback.format_exception(excinfo.type, excinfo.value, excinfo.tb )
获取case运行时失败信息
report = out.get_result()print('测试报告Case日志: %s' % report.caplog())print('测试报告Case stderr: %s' % report.capstderr())print('测试报告Case stdout: %s' % report.capstdout())