ozr*_*983 4 python django ascii-art pytest
我正在使用 pytest 在 Django 项目中运行测试。我正在使用 pytest.ini 定义了 DJANGO_SETTINGS_MODULE,所以我只运行测试:
pytest
Run Code Online (Sandbox Code Playgroud)
现在,如果测试运行成功,我想在控制台输出中添加一些ASCII艺术。我知道我可以做到:
pytest && cat ascii_art.txt
Run Code Online (Sandbox Code Playgroud)
但是我想将 ASCII 艺术隐藏到配置或其他地方,以便我继续仅使用pytest. 我没有看到任何可以使用的 pytest 配置选项。任何其他想法如何做到这一点?
有很多地方可以打印自己的东西pytest;从钩子列表中选择一个合适的钩子并覆盖它,添加你自己的打印。为了让示例更有趣,我将使用screenfetch包装函数打印一些系统信息:
def screenfetch():
exec = shutil.which('screenfetch')
out = ''
if exec:
out = subprocess.run(exec, stdout=subprocess.PIPE, universal_newlines=True).stdout
return out
Run Code Online (Sandbox Code Playgroud)
conftest.py在项目根目录中创建一个文件,内容如下:
from utils import screenfetch
def pytest_unconfigure(config):
print(screenfetch())
Run Code Online (Sandbox Code Playgroud)
结果:
如果您只想在成功的测试运行时进行条件打印,请使用pytest_sessionfinish钩子存储退出代码:
def pytest_sessionfinish(session, exitstatus):
session.config.exitstatus = exitstatus
def pytest_unconfigure(config):
if config.exitstatus == 0:
print(screenfetch())
Run Code Online (Sandbox Code Playgroud)
另一个例子:
# conftest.py
from utils import screenfetch
def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.ensure_newline()
terminalreporter.write(screenfetch())
Run Code Online (Sandbox Code Playgroud)
pytest输出开始前的自定义打印# conftest.py
from utils import screenfetch
def pytest_configure(config):
print(screenfetch())
Run Code Online (Sandbox Code Playgroud)
pytest的标题信息# conftest.py
import screenfetch
def pytest_report_header(config, startdir):
return screenfetch()
Run Code Online (Sandbox Code Playgroud)
# 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())
Run Code Online (Sandbox Code Playgroud)
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())
Run Code Online (Sandbox Code Playgroud)
请注意,我在可能的情况下使用terminalreporter插件而不是printing - 这就是它pytest本身发出输出的方式。
| 归档时间: |
|
| 查看次数: |
580 次 |
| 最近记录: |