Skip to content

Fixture execution order: higher-scoped fixtures are not necessarily run before lower-scoped fixtures #2405

Closed
@jaraco

Description

@jaraco

I've encountered what appears to be a violation of the expectation that higher-scoped fixtures are run before lower scoped fixtures.

In conftest.py, I have a module-scoped fixture.

@pytest.fixture(scope='module')
def clean_data():
    ...

In the test suite, I wish to reference that fixture:

pytestmark = pytest.mark.usefixtures('clean_data')

And an autouse test at the class scope:

class TestStuff:
    @pytest.fixture(scope='class', autouse=True)
    def add_data(cls):
        ...

But when the tests run, it appears that add_data runs before clean_data. Perhaps that's because of the autouse feature. Is that expected for all autouse fixtures to be run before marked fixtures even when the autouse is at a finer scope?

I was able to work around the issue by removing the pytestmark and instead specifying clean_data as a parameter to each add_data across several classes in the module. I don't like this workaround because it violates the goal of signaling the cleanup exactly once at the beginning of the module (akin to a setup_module method).

If this fixture execution order is by design, is there a better way to achieve what I'm after (essentially the setup_module and setup_class behavior from unittest)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: fixturesanything involving fixtures directly or indirectlytopic: marksrelated to marks, either the general marks or builtintype: bugproblem that needs to be addressed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions