How to get pytest to register_assert_rewrites for all modules under tests/ directory?

Question:

I have a project like:

/app
    /app
        foo.py
        bar.py
    /tests
        __init__.py
        core.py
        test_foo.py
        test_bar.py

In core.py, I have some functions that call assert. These functions are imported into test_foo.py and test_bar.py.

Calling pytest test_foo.py by default will not pretty print any of the values used in the assert, if the assert was called from a function imported from core.py.

One way around this is to add the following to tests/__init__.py:

import pytest
pytest.register_assert_rewrite('tests.core')

However, this is inconvenient as you would need to add every module from your tests directory into this call.

Is there a way to get pytest to do this automatically, without me having to specify each module I want pytest to rewrite?

Asked By: Matthew Moisen

||

Answers:

The pretty asserts are thanks to Pytest’s Assertion Rewriting mechanism. Its documentation states:

… this hook only rewrites test modules themselves (as defined by the
python_files configuration option)

So one thing you could do is to change your core.py file into test_*.py (like test_core.py or test_core_utils.py), which is the standard pattern of files that pytest is translating.

Another option would be to change the python_files configuration in pytest.ini like so:

[pytest]
python_files = test_*.py core.py

See more about it here.

Answered By: Peter K
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.