Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write to the console from a pytest plugin during the collection phase?

Tags:

python

pytest

I'm writing a pytest plugin that needs to warn the user about anomalies encountered during the collection phase, but I don't find any way to consistently send output to the console from inside my pytest_generate_tests function.

Output from print and from the logging module only appears in the console when adding the -s option. All logging-related documentation I found refers to logging inside tests, not from within a plugin.

like image 534
alexamici Avatar asked Sep 01 '25 01:09

alexamici


1 Answers

In the end I used the pytest-warning infrastructure by using the undocumented _warn() method of the pytest config object passed to or anyway accessible from various hooks. For example:

def pytest_generate_tests(metafunc):
    [...]
    if warning_condition:
        metafunc.config._warn("Warning condition encountered.")
    [...]

This way you get additional pytest-warnings in the one-line summary if any was reported and you can see the warnings details by adding the '-r w' option to the pytest command line.

like image 161
alexamici Avatar answered Sep 02 '25 14:09

alexamici