[TIP] py.test: Best way of having a fixture autoused "almost all of the time"

holger krekel holger at merlinux.eu
Fri Aug 8 05:52:08 PDT 2014

On Fri, Aug 08, 2014 at 13:41 +0100, Paul Moore wrote:
> I've got a situation where I want to use a py.test autouse fixture to
> make sure my tests run in a clean environment. The idea is that I have
> a fixture marked as autouse which uses application features to isolate
> the test environment from the user's config files. But obviously I
> don't want that fixture to activate when actually testing the
> functionality it uses!
> The simple approach would be to have a structure
> tests
>     tests/isolation
>         test_isolation.py
>     tests/the_rest
>         conftest.py
>             @fixture(autouse=True)
>             def isolate_env():
>         ... all the rest of the application tests
> but I'm not a huge fan of the extra directory level, for a single
> file. Is it possible to say that I *don't* want isolate_env activated
> in the test_isolation.py file?

One common approach is to read a marker from the autouse fixture like this:

    def isolate_env(request):
        marker = request.node.get_marker("no_isolate_env")
        if marker is None:
            # do the isolation

and have a test like this:

    import pytest

    def test_isolate_env():

you can also mark a test class this way.  Or even a whole module:

    # all tests in this module inhibit the autouse isolate_env fixture
    pytestmark = pytest.mark.no_isolate_env
This module syntax is the workaround for the fact that you can't decorate
a module in Python.  See also: https://pytest.org/latest/example/markers.html#marking-whole-classes-or-modules


More information about the testing-in-python mailing list