Course contentsShow
← Python
Lesson 751 of 1,06012. Testing and DebuggingFree lesson

Managing Shared State with Pytest Fixtures

Implement reusable setup and teardown logic using pytest fixtures to ensure a clean and consistent environment for every individual test case.

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

  1. Dependency Injection: By adding temp_config as an argument to test_config_loading, pytest automatically executes the fixture before the test starts.
  2. The yield Keyword: The code before yield acts as the setup phase. When the test finishes, pytest resumes the function at the line after yield to perform the teardown.
  3. Isolation: Because pytest re-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.