编辑:由于我需要访问测试项目的 funcargs(和测试结果)以进行报告,因此我能够将逻辑移动到 pytest_runtest_makereport(item, __multicall__) 挂钩。诀窍是执行多重调用,它返回报告对象:
@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
report = __multicall__.execute()
# then I was able to manipulate report and get the same results as below
Bruno 的回答给了我更彻底分析此功能所需的动力:)
下面是它的工作原理:
def pytest_runtest_logreport(report):
if report.failed:
report.longrepr.sections.append(("Header", "Message", "-"))
report.sections.append(("Captured stdout", "This is added to stdout"))
report.sections.append(("Captured stderr", "This is added to stderr"))
report.sections.append(("Custom Section", "This can only be seen in the console - the xml won't have it."))
longrepr 属性仅在发生故障时可用。它需要一个 3 元组,最后一个值是用于装饰装饰/环绕标题的字符。它将出现在报告的“失败”部分:
----------------------------------- Header ------------------------------------
Message
自定义部分将创建额外的结果部分以打印到控制台。但是他们不会进入junitxml:
------------------------------- Custom Section --------------------------------
This can only be seen in the console - the xml won't have it.
junitxml 报告只有 2 个部分:out 和 err。要向其中添加自定义文本,您必须创建名为“Captured std”的部分,并且只有这些部分才能将其添加到 xml 文件中。任何其他名称都将生成一个仅在控制台中可见的自定义部分。
这是使用上面代码生成的 junitxml,为了这篇文章,进行了一些重新格式化:
<?xml version="1.0" encoding="utf-8" ?>
<testsuite errors="0" failures="1" name="pytest" skips="0" tests="1" time="0.646">
<testcase classname="test_reporting" name="test_fail" time="0.000999927520752">
<failure message="test failure">
@ut def test_fail(): > assert 0, "It failed"
E AssertionError: It failed
E assert 0 test_reporting.py:346: AssertionError
----------------------------------- Header ------------------------------------
Message
</failure>
<system-out>This is added to stdout</system-out>
<system-err>This is added to stderr</system-err>
</testcase>
</testsuite>