首页 > 解决方案 > 如何以动态方式自定义通过的测试消息

问题描述

我可能会对以我不应该的方式使用 pytest 感到内疚,但假设我想在成功完成测试时生成并显示一些短消息。就像我正在开发一种压缩算法,而不是“PASSED”,我希望看到“SQUEEZED BY 65.43%”或类似的东西。这甚至可能吗?我应该从哪里开始定制,或者我可能会使用一个插件?

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

标签: pythontestingpytest

解决方案


我可能会因为我不应该使用 pytest 的方式而感到内疚

一点也不——这正是pytest插件系统应该解决的用例。

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

from mylib import squeeze

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

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

# 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%]

推荐阅读