[pytest-dev] Fixture ordering and scopes

Bruno Oliveira nicoddemus at gmail.com
Thu Mar 15 17:42:23 EDT 2018

Hi everyone and Holger,

Looking at the code below:

data = {}
@pytest.fixture(scope='session')def clean_data():
@pytest.fixture(autouse=True)def add_data():
    data['value'] = 1
@pytest.mark.usefixtures('clean_data')def test_foo():
    assert data.get('value')

Should test_foo fail or pass? Keep your answer in mind before proceeding. :)

I ask this because *unrelated* fixtures, i.e. which don’t depend on each
other, are executed in the order they are declared in the test function
signature, regardless of scope.

The example above *fails*, because the fixtures are executed in (add_data,
clean_data) order: add_data, being *autouse*, is added to the beginning of
the argument list, and afterwards clean_data is inserted because of the
usefixtures mark.

This came up in #2405 <https://github.com/pytest-dev/pytest/issues/2405>,
where Jason Coombs assumed that clean_data, being session-scoped, would
always be executed first.

I wonder if the current state of things is by design, or just an accident
of how things work?

I opened up a PR <https://github.com/pytest-dev/pytest/pull/3306> which
does sort parameters by scope while keeping the relative order of fixtures
of same scope intact, and the test suite passes without failures so if the
current behavior is by design there are not tests enforcing it. Using code
in the PR, then things might also be surprising:

@pytest.fixture(scope='session')def s(): pass
@pytest.fixture(scope='function')def f(): pass
def test_foo(f, s):

s and f are unrelated and execute in (f, s) order in master, but in (s, f)
order in my branch.

Would like to hear what people think about this matter, as I think it is an
important one, specially *Holger* if this is a design decision or just an
accident of implementation, and if we should change it.

Also, please feel free to just reply with what you thought what should be
the behavior of the first sample.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pytest-dev/attachments/20180315/166720fb/attachment-0001.html>

More information about the pytest-dev mailing list