Introduction

Session-scoped fixtures in pytest are created once per test session and shared across all tests. When a session fixture contains mutable state -- such as a database connection, a shared dictionary, or a singleton object -- tests that modify this state can cause seemingly random failures in unrelated tests. The order-dependent nature of these failures makes them notoriously difficult to reproduce, as the test suite passes when run in isolation but fails when run as part of the full suite. This violates test isolation, a core principle of reliable test suites.

Symptoms

Tests pass individually but fail in the full suite:

```bash # Running individually - all pass $ pytest tests/test_users.py::test_create_user -v $ pytest tests/test_orders.py::test_place_order -v

# Running together - second test fails $ pytest tests/ -v tests/test_users.py::test_create_user PASSED tests/test_orders.py::test_place_order FAILED

E AssertionError: Expected 1 order, got 3 ```

Or with random ordering:

```bash # Different order, different failure $ pytest --random-order tests/ -v tests/test_orders.py::test_place_order PASSED tests/test_users.py::test_create_user FAILED

E KeyError: 'unexpected_key_in_shared_state' ```

Common Causes

  • Mutable default in session fixture: Returning a list, dict, or object that gets mutated by tests
  • Database not cleaned between tests: Session-scoped database fixture with incomplete transaction rollback
  • Singleton or module-level state: Session fixture caches a singleton that maintains internal state
  • Missing teardown in session fixture: yield without cleanup leaves shared resources in a dirty state
  • Test order dependency: Tests accidentally depend on side effects from other tests via shared fixtures
  • Global variable modified by fixture: Session fixture modifies a module-level variable that other tests read

Step-by-Step Fix

Step 1: Identify the leaking fixture

Use pytest-randomly to surface the dependency:

bash
pip install pytest-randomly
pytest --randomly-seed=1234 tests/ -v

Run with different seeds to find the consistent failure pattern. Then isolate with:

bash
pytest tests/test_a.py tests/test_b.py -v  # passes
pytest tests/test_b.py tests/test_a.py -v  # fails - test_b depends on test_a's side effect

Step 2: Fix mutable state in session fixtures

```python # WRONG - shared mutable dict @pytest.fixture(scope="session") def shared_config(): return {"database_url": "sqlite:///test.db", "users": []}

def test_add_user(shared_config): shared_config["users"].append("alice") # Modifies session fixture!

# CORRECT - return immutable data or deep copy @pytest.fixture(scope="session") def shared_config(): return {"database_url": "sqlite:///test.db"}

@pytest.fixture def test_config(shared_config): """Each test gets its own copy.""" return {**shared_config, "users": []} # Fresh dict per test

def test_add_user(test_config): test_config["users"].append("alice") # Safe - isolated to this test ```

Step 3: Add proper teardown to database fixtures

```python @pytest.fixture(scope="session") def db_engine(): """Session-scoped engine - created once.""" engine = create_engine("sqlite:///test.db") Base.metadata.create_all(engine) yield engine Base.metadata.drop_all(engine)

@pytest.fixture def db_session(db_engine): """Function-scoped session - clean for every test.""" connection = db_engine.connect() transaction = connection.begin() session = Session(bind=connection)

yield session

session.close() transaction.rollback() # Rolls back all changes from this test connection.close() ```

Each test gets a fresh transaction that is rolled back after the test, ensuring no state leaks between tests while the expensive engine creation happens only once.

Step 4: Use class-level fixtures for grouped isolation

```python class TestUserCreation: @pytest.fixture(autouse=True) def setup(self, db_session): self.session = db_session

def test_create_admin(self): admin = User(role="admin") self.session.add(admin) self.session.commit() assert self.session.query(User).filter_by(role="admin").count() == 1

def test_create_regular_user(self): user = User(role="user") self.session.add(user) self.session.commit() assert self.session.query(User).filter_by(role="user").count() == 1 ```

Prevention

  • Never return mutable objects from session-scoped fixtures without wrapping them in a factory
  • Use --random-order in CI to detect test order dependencies
  • Keep session fixtures limited to truly immutable or thread-safe resources (compiled regex, constants)
  • Use function-scoped fixtures for anything that tests modify
  • Add pytest-leaks to detect resource leaks from fixtures
  • Document which fixtures are safe to mutate and which are not in a conftest.py docstring