Fixtures
Fixtures set up shared state for tests. pytest injects them by name as function parameters.
Fixtures set up shared state for tests. pytest injects them by name as function parameters.
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"
Use yield in fixtures for teardown — code after yield runs after the test completes.