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

Python 成功运行pytest时将ASCII艺术输出到控制台,python,django,pytest,ascii-art,Python,Django,Pytest,Ascii Art,我正在使用pytest在Django项目中运行测试。我使用的是定义了DJANGO_SETTINGS_模块的pytest.ini,因此我只使用以下工具运行测试: pytest 现在,如果测试运行成功,我想向控制台输出添加一些艺术。我知道我能做到: pytest && cat ascii_art.txt 但我想将ASCII艺术隐藏到配置或其他地方,以便只使用pytest运行测试。我看不到任何可以使用的pytest配置选项。还有其他方法吗?有很多地方可以在pytest中打印自己的东

我正在使用pytest在Django项目中运行测试。我使用的是定义了DJANGO_SETTINGS_模块的pytest.ini,因此我只使用以下工具运行测试:

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

pytest && cat ascii_art.txt

但我想将ASCII艺术隐藏到配置或其他地方,以便只使用
pytest
运行测试。我看不到任何可以使用的pytest配置选项。还有其他方法吗?

有很多地方可以在
pytest
中打印自己的东西;从中选择适当的挂钩并覆盖它,添加您自己的打印。为了增加示例的趣味性,我将使用包装器函数打印一些系统信息:

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())
结果:

如果只希望在成功的测试运行时进行有条件打印,请使用钩子存储退出代码:

def pytest_sessionfinish(session, exitstatus):
    session.config.exitstatus = exitstatus

def pytest_unconfigure(config):
    if config.exitstatus == 0:
        print(screenfetch())
另一个例子:

增强摘要 在
pytest
输出开始之前自定义打印
pytest
标题信息后的自定义打印 收集测试后、测试运行前的自定义打印 每次测试后定制打印 请注意,我使用
terminalreporter
插件,而不是在可能的情况下仅使用
print
ing-这就是
pytest
本身发出输出的方式

# conftest.py
from utils import screenfetch

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    terminalreporter.ensure_newline()
    terminalreporter.write(screenfetch())
# conftest.py

from utils import screenfetch

def pytest_configure(config):
    print(screenfetch())
# 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())