Understanding Fixture Scopes
Fixture scopes control how often a fixture is executed. pytest supports four scopes: function, class, module, and session.
Function Scope (Default)
The fixture runs once per test function. This is the default behavior:
@pytest.fixture(scope="function")
def temp_dir():
d = create_temp_directory()
yield d
cleanup_directory(d)
def test_one(temp_dir):
# Gets a fresh temp_dir
assert os.path.exists(temp_dir)
def test_two(temp_dir):
# Gets a NEW temp_dir (different from test_one)
assert os.path.exists(temp_dir)
Class Scope
The fixture runs once per test class, shared across all methods in that class:
@pytest.fixture(scope="class")
def database():
conn = create_connection()
yield conn
conn.close()
class TestUserQueries:
def test_insert(self, database):
database.execute("INSERT INTO users ...")
def test_select(self, database):
# Uses the SAME connection as test_insert
database.execute("SELECT * FROM users")
Module Scope
The fixture runs once per test file, shared across all tests in that module:
@pytest.fixture(scope="module")
def expensive_computation():
# This runs only once for the entire file
return compute_heavy_data()
def test_first(expensive_computation):
assert expensive_computation is not None
def test_second(expensive_computation):
# Uses the SAME result (not recomputed)
assert len(expensive_computation) > 0
Session Scope
The fixture runs once for the entire test session, shared across all files:
@pytest.fixture(scope="session")
def database_connection():
conn = create_connection()
yield conn
conn.close()
# All test files share this single connection