如何动态自定义通过测试的消息

How to customize the passed test message in a dynamic way

我可能会以不应该的方式使用 pytest,但假设我想生成并显示一些关于成功完成测试的短消息。就像我正在开发一种压缩算法,而不是“通过”,我希望看到“压缩 65.43%”或类似的东西。这可能吗?我应该从哪里开始自定义,或者也许有我可以使用的插件?

我偶然发现了 pytest-custom-report,但它只提供在测试 运行 之前设置的静态消息。那不是我需要的。

I might be guilty of using pytest in a way I'm not supposed to

根本不是 - 这正是 pytest plugin system 应该解决的用例类型。

回答您的实际问题:不清楚百分比值的来源。假设它由函数 squeeze() 返回,我会首先将百分比存储在测试中,例如使用 record_property fixture:

from mylib import squeeze

def test_spam(record_property):
    value = squeeze()
    record_property('x', value)
    ...

要显示存储的百分比值,请在项目或测试根目录的 conftest.py 中添加自定义 pytest_report_teststatus hookimpl:

# conftest.py

def pytest_report_teststatus(report, config):
    if report.when == 'call' and report.passed:
        percentage = dict(report.user_properties).get('x', float("nan"))
        short_outcome = f'{percentage * 100}%'
        long_outcome = f'SQUEEZED BY {percentage * 100}%'
        return report.outcome, short_outcome, long_outcome

现在 运行 test_spam 在默认输出模式下产生

test_spam.py 10.0%                                                                  [100%]

运行 详细模式

test_spam.py::test_spam SQUEEZED BY 10.0%                                           [100%]