pytest 有很多地方可以打印自己的东西;从hooks list 中选择一个合适的钩子并覆盖它,添加您自己的打印。为了给示例增添趣味,我将使用 screenfetch 包装函数打印一些系统信息:
def screenfetch():
exec = shutil.which('screenfetch')
out = ''
if exec:
out = subprocess.run(exec, stdout=subprocess.PIPE, universal_newlines=True).stdout
return out
测试执行完成后的自定义打印
在您的项目根目录中创建一个文件conftest.py,内容如下:
from utils import screenfetch
def pytest_unconfigure(config):
print(screenfetch())
结果:
如果您只想在成功的测试运行时进行条件打印,请使用 pytest_sessionfinish 挂钩来存储退出代码:
def pytest_sessionfinish(session, exitstatus):
session.config.exitstatus = exitstatus
def pytest_unconfigure(config):
if config.exitstatus == 0:
print(screenfetch())
另一个例子:
增强摘要
# conftest.py
from utils import screenfetch
def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.ensure_newline()
terminalreporter.write(screenfetch())
pytest 输出开始前的自定义打印
# conftest.py
from utils import screenfetch
def pytest_configure(config):
print(screenfetch())
pytest 的标题信息后自定义打印
# conftest.py
import screenfetch
def pytest_report_header(config, startdir):
return screenfetch()
测试收集后,测试运行前的自定义打印
# conftest.py
import os
from utils import screenfetch
def pytest_collection_modifyitems(session, items):
terminalreporter = session.config.pluginmanager.get_plugin('terminalreporter')
terminalreporter.ensure_newline()
terminalreporter.write(screenfetch())
每次测试后自定义打印
def pytest_report_teststatus(report, config):
if report.when == 'teardown': # you may e.g. also check the outcome here to filter passed or failed tests only
terminalreporter = config.pluginmanager.get_plugin('terminalreporter')
terminalreporter.ensure_newline()
terminalreporter.write(screenfetch())
请注意,我尽可能使用terminalreporter 插件而不是printing - 这就是pytest 本身发出输出的方式。