Home > Net >  How to customize the passed test message in a dynamic way
How to customize the passed test message in a dynamic way

Time:10-11

I might be guilty of using pytest in a way I'm not supposed to, but let's say I want to generate and display some short message on successful test completion. Like I'm developing a compression algorithm, and instead of "PASSED" I'd like to see "SQUEEZED BY 65.43%" or something like that. Is this even possible? Where should I start with the customization, or maybe there's a plugin I might use?

I've stumbled upon pytest-custom-report, but it provides only static messages, that are set up before tests run. That's not what I need.

CodePudding user response:

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

Not at all - this is exactly the kind of use cases the pytest plugin system is supposed to solve.

To answer your actual question: it's not clear where the percentage value comes from. Assuming it is returned by a function squeeze(), I would first store the percentage in the test, for example using the record_property fixture:

from mylib import squeeze

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

To display the stored percentage value, add a custom pytest_report_teststatus hookimpl in a conftest.py in your project or tests root directory:

# 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

Now running test_spam in default output mode yields

test_spam.py 10.0%                                                                  [100%]

Running in the verbose mode

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