如何以动态方式自定义已通过的测试消息

2024-05-29 07:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: report插件消息pytestcustom方式静态压缩算法
1条回答
网友
1楼 · 发布于 2024-05-29 07:48:47

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

一点也不-这正是^{} plugin system应该解决的用例类型

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

from mylib import squeeze

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

要显示存储的百分比值,请在项目或测试根目录的conftest.py中添加一个自定义的^{}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%]

相关问题 更多 >

    热门问题