In this lesson, you will learn how to use pytest fixtures to automate setup and teardown tasks, ensuring each test runs in a clean, predictable environment.
The Problem with Shared State
When writing tests that interact with external systems—like writing to a temporary file, connecting to a mock database, or modifying a shared configuration object—you often run into "state leakage." If Test A modifies an object and doesn't clean up, Test B might fail not because the code is broken, but because it inherited a "dirty" environment. Manually resetting this state in every test leads to repetitive, error-prone boilerplate code.
Using Fixtures for Lifecycle Management
pytest fixtures allow you to define a setup (creating the environment) and a teardown (cleaning up) in one place. By decorating a function with @pytest.fixture, you signal to pytest that this function provides a resource.
Consider a test that requires a temporary configuration file:
import pytest
import os
@pytest.fixture
def temp_config():
# Setup: Create a resource
config_path = "test_config.json"
with open(config_path, "w") as f:
f.write('{"status": "ready"}')
yield config_path # Provide the resource to the test
# Teardown: Clean up the resource
if os.path.exists(config_path):
os.remove(config_path)
def test_config_loading(temp_config):
# The test runs, and temp_config is guaranteed to exist
with open(temp_config, "r") as f:
assert "ready" in f.read()
How it Works
- Dependency Injection: By adding
temp_configas an argument totest_config_loading,pytestautomatically executes the fixture before the test starts. - The
yieldKeyword: The code beforeyieldacts as the setup phase. When the test finishes,pytestresumes the function at the line afteryieldto perform the teardown. - Isolation: Because
pytestre-runs the fixture for every test that requests it, you are guaranteed a fresh, independent environment every time, regardless of what happened in previous tests.
Key Takeaway: Use fixtures to encapsulate setup and teardown logic, ensuring test isolation by resetting shared state automatically before and after every individual test case.