Global safety nets (no network, frozen settings) and predictable setup order depend on how pytest resolves fixtures.
`autouse=True` makes a fixture apply to every test in its scope without being requested: in a conftest it covers that directory tree, in a module that module, in a class that class. Typical uses are guards and resets: blocking network access, resetting a global cache, setting a test settings object. Use them sparingly, since hidden setup makes tests harder to understand.
How pytest orders fixtures for a test:
- Higher scopes first: session fixtures are set up before module ones, before function ones.
- Autouse fixtures before explicitly requested ones within the same scope.
- Dependencies before dependents; otherwise, the order in the test's signature.
Don't rely on signature order for correctness; express real dependencies by having one fixture request the other.
Overriding fixtures happens at several levels: a conftest closer to the test, a fixture of the same name in the test module, or a class. And @pytest.mark.parametrize("name", [...]) with the name of a fixture overrides the fixture's value directly for that test.
pytest --setup-show prints each fixture's SETUP and TEARDOWN with its scope as tests run, the fastest way to debug ordering and scoping surprises.
Example
# test_autouse.py
import pytest
CACHE = {}
@pytest.fixture(autouse=True)
def clear_cache(): # runs for every test in this module
CACHE.clear()
yield
CACHE.clear()
@pytest.fixture(scope="module")
def config():
return {"debug": False}
@pytest.fixture
def user():
return "ada"
def test_cache_starts_empty(config):
CACHE["x"] = 1
assert config["debug"] is False
@pytest.mark.parametrize("user", ["override"]) # replaces the fixture's value
def test_override(user):
assert user == "override" and CACHE == {}
# $ pytest --setup-show -q -> shows SETUP/TEARDOWN order per fixtureRemember
- autouse fixtures apply to every test in their scope
- Order: higher scope first, autouse first, then dependencies
- Express ordering through fixture dependencies, not signature order
- --setup-show reveals fixture setup and teardown
Watch out for
- Putting heavy autouse fixtures in the root conftest so every unit test pays for them.