编辑:由于我需要访问测试项目的 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
布鲁诺的回答给了我更彻底地分析这个功能所需的动力:)
那么它的工作原理如下:
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."))
The longrepr
属性仅在失败时可用。它采用一个三元组,最后一个值是用于装饰标题的装饰/包围的字符。它将出现在报告的“失败”部分:
----------------------------------- Header ------------------------------------
Message
自定义部分将创建额外的结果部分以打印到console。但他们不会进入 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>