首先,回答您的确切问题:
有没有办法只为特定测试获取Captured stdout call 而不会导致测试失败?
您可以添加一个模仿Captured stdout call 并在测试成功时打印的自定义部分。每个测试中捕获的输出存储在相关的TestReport 对象中,并通过report.capstdout 访问。示例 impl:将以下代码添加到项目或测试根目录中的 conftest.py 中:
import os
def pytest_terminal_summary(terminalreporter, exitstatus, config):
# on failures, don't add "Captured stdout call" as pytest does that already
# otherwise, the section "Captured stdout call" will be added twice
if exitstatus > 0:
return
# get all reports
reports = terminalreporter.getreports('')
# combine captured stdout of reports for tests named `<smth>::test_summary`
content = os.linesep.join(
report.capstdout for report in reports
if report.capstdout and report.nodeid.endswith("test_summary")
)
# add custom section that mimics pytest's one
if content:
terminalreporter.ensure_newline()
terminalreporter.section(
'Captured stdout call',
sep='-',
blue=True,
bold=True,
)
terminalreporter.line(content)
这将添加一个自定义部分 Captured stdout call,它将仅打印为 ID 以 test_summary 结尾的测试捕获的输出(如果您有多个名为 test_summary 的测试函数,请扩展检查)。为了区分这两个部分,自定义部分有一个蓝色标题;如果您希望它与原始颜色匹配,请通过blue=True arg 删除颜色设置。
现在,解决您的实际问题:
test_summary 实际上只是打印某种测试的摘要/统计数据
对我来说,使用自定义报告测试听起来很像一种解决方法;为什么不在测试中收集数据,然后添加一个自定义部分来打印该数据?要收集数据,您可以例如使用record_property 夹具:
def test_foo(record_property):
# records a key-value pair
record_property("hello", "world")
def test_bar(record_property):
record_property("spam", "eggs")
要收集和输出记录的自定义属性,稍微改变上面的 hookimpl。通过record_property 存储的数据可通过report.user_properties 访问:
import os
def pytest_terminal_summary(terminalreporter, exitstatus, config):
reports = terminalreporter.getreports('')
content = os.linesep.join(
f'{key}: {value}' for report in reports
for key, value in report.user_properties
)
if content:
terminalreporter.ensure_newline()
terminalreporter.section(
'My custom summary',
sep='-',
blue=True,
bold=True
)
terminalreporter.line(content)
现在运行上述测试会产生:
$ pytest test_spam.py
=============================== test session starts ================================
platform linux -- Python 3.9.0, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/oleg.hoefling/projects/private/stackoverflow/so-64812992
plugins: metadata-1.10.0, json-report-1.2.4, cov-2.10.1, forked-1.3.0, xdist-2.1.0
collected 2 items
test_spam.py .. [100%]
-------------------------------- My custom summary ---------------------------------
hello: world
spam: eggs
================================ 2 passed in 0.01s =================================