【问题标题】:Output ASCII art to console on succesfull pytest run在成功的 pytest 运行时将 ASCII 艺术输出到控制台
【发布时间】:2018-12-05 17:29:50
【问题描述】:

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

pytest

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

pytest && cat ascii_art.txt

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

【问题讨论】:

    标签: python django pytest ascii-art


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      相关资源
      最近更新 更多