Skip to content
Latchkey

pytest "ScopeMismatch" fixture error in CI

pytest fixtures can only depend on fixtures of an equal or broader scope. A session- or module-scoped fixture that requests a function-scoped one would outlive it, so pytest refuses with ScopeMismatch.

What this error means

Collection or setup errors with "ScopeMismatch: You tried to access the function scoped fixture X with a module scoped request object."

pytest
ScopeMismatch: You tried to access the function scoped fixture 'tmp_path' with a
session scoped request object, involved factories:
tests/conftest.py:10:  def db(tmp_path)

Common causes

A broad fixture depends on a narrow one

A session-scoped fixture requests a function-scoped fixture, which would be recreated more often than its dependent lives.

A built-in narrow fixture used in a broad fixture

Built-ins like tmp_path are function-scoped; using them inside a module/session fixture triggers the mismatch.

How to fix it

Align the scopes

  1. Decide the intended lifetime of the broader fixture.
  2. Either narrow it to match its dependency, or replace the narrow dependency with a broader equivalent.
  3. Re-run so scopes are compatible.
tests/conftest.py
@pytest.fixture(scope="session")
def db(tmp_path_factory):  # session-scoped factory, not tmp_path
    path = tmp_path_factory.mktemp("db")
    ...

Use the *_factory variants for broad scopes

Session/module fixtures should use tmp_path_factory/tmp_path_factory.mktemp rather than function-scoped built-ins.

How to prevent it

  • Make a fixture's dependencies equal or broader in scope.
  • Use factory fixtures inside session/module-scoped fixtures.
  • Keep fixture scopes intentional and documented.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →