SyntaxStudy
Sign Up
Python Intermediate 4 min read

pytest Fixtures

Fixtures

Fixtures set up shared state for tests. pytest injects them by name as function parameters.

Example
import pytest

@pytest.fixture
def sample_user():
    return {"id": 1, "name": "Alice", "email": "alice@example.com"}

@pytest.fixture
def db_connection():
    conn = create_test_db()
    yield conn          # setup done
    conn.close()        # teardown

def test_user_name(sample_user):
    assert sample_user["name"] == "Alice"

def test_save_user(db_connection, sample_user):
    save(db_connection, sample_user)
    assert find(db_connection, 1)["name"] == "Alice"
Pro Tip

Use yield in fixtures for teardown — code after yield runs after the test completes.