gpt4 book ai didi

python - 在成功运行 pytest 时将 ASCII 艺术输出到控制台

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:24 30 4
gpt4 key购买 nike

我正在使用 pytest 在 Django 项目中运行测试。我正在使用定义了 DJANGO_SETTINGS_MODULE 的 pytest.ini,所以我只运行测试:

pytest

现在,我想添加一些 ASCII如果测试运行成功,艺术到控制台输出。我知道我能做到:

pytest && cat ascii_art.txt

但我想将 ASCII 艺术隐藏到配置或其他地方,以便我继续使用 pytest 运行测试。我没有看到任何可以使用的 pytest 配置选项。还有其他关于如何做到这一点的想法吗?

最佳答案

pytest 中有很多地方可以打印你自己的东西;从 hooks list 中选择合适的 Hook 并覆盖它,添加您自己的打印。为了给示例增添趣味,我将使用 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())

结果:

enter image description here

如果您只想在成功的测试运行时有条件地打印,请使用 pytest_sessionfinish钩子(Hook)存储退出代码:

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 本身发出输出的方式。

关于python - 在成功运行 pytest 时将 ASCII 艺术输出到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53637733/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com