In which order are pytest fixtures executed? In which order are pytest fixtures executed? python python

In which order are pytest fixtures executed?


The easiest way to control the order in which fixtures are executed, is to just request the previous fixture in the later fixture. So to make sure b runs before a:

@pytest.fixture(autouse=True, scope="function")def b():    pass@pytest.fixture(scope="function")def a(b):    pass

For details on the general fixture resolution order, see Maxim's excellent answer below or have a look at the documentation.


I was just having this problem with two function-scoped autouse fixtures. I wanted fixture b to run before fixture a, but every time, a ran first. I figured maybe it was alphabetical order, so I renamed a to c, and now b runs first. Pytest doesn't seem to have this documented. It was just a lucky guess. :-)

That's for autouse fixtures. Considering broader scopes (eg. module, session), a fixture is executed when pytest encounters a test that needs it. So if there are two tests, and the first test uses a session-scoped fixture named sb and not the one named sa, then sb will get executed first. When the next test runs, it will kick off sa, assuming it requires sa.


TL;DR

There are 3 aspects being considered together when building fixture evaluation order, aspects themselves are placed in order of priority:

  • Fixture dependencies - fixtures are evaluated from rootest required back to one required in test function.
  • Fixture scope - fixtures are evaluated from session through module to function scoped. On the same scope autouse fixtures are evaluated before non-autouse ones.
  • Fixture position in test function arguments - fixtures are evaluated in order of presence in test function arguments, from leftest to rightest.

Official explanation with code example by link below

https://docs.pytest.org/en/stable/fixture.html#fixture-instantiation-order