Code Reference

Fixtures

Pytest · Reference cheat sheet

Fixtures

Pytest · Reference cheat sheet


📋 Overview

Fixtures provide setup/teardown via dependency injection. Tests request fixtures by parameter name; scopes control lifetime (function, class, module, package, session).

🔧 Core concepts

ConceptMeaning
@pytest.fixtureDefine reusable resource
yieldSetup before, teardown after
scopeHow often to recreate
autouseApply without requesting
paramsParametrized fixture
Fixture factoryReturn a creator callable

Prefer fixtures over setup/teardown methods for composability.

💡 Examples

Basic yield fixture:

import pytest

@pytest.fixture
def db():
    conn = connect()
    yield conn
    conn.close()

def test_query(db):
    assert db.execute("SELECT 1").fetchone()[0] == 1

Scopes:

@pytest.fixture(scope="session")
def app():
    return create_app()

@pytest.fixture(scope="module")
def client(app):
    return app.test_client()

Factory:

@pytest.fixture
def make_user(db):
    created = []
    def _make(**kwargs):
        u = User(**kwargs)
        db.add(u)
        created.append(u)
        return u
    yield _make
    for u in created:
        db.delete(u)

Autouse:

@pytest.fixture(autouse=True)
def _fast_cache(monkeypatch):
    monkeypatch.setenv("CACHE_URL", "memory://")

⚠️ Pitfalls

  • Session-scoped mutable state leaking between tests.
  • Requesting heavy fixtures unnecessarily — keep scopes tight.
  • Using return when teardown is needed — use yield.
  • Circular fixture dependencies.
  • Overusing autouse — hard to see what a test depends on.

On this page