Skip to content

Pytest Fixtures - Managing Test Dependencies

A fixture is a reusable function that provides a value to tests.

Use fixtures for:

  • test data factories
  • temporary resources
  • dependency setup (clients, config)
test_fixture_basic.py
import pytest
 
 
@pytest.fixture
def user():
    return {"name": "Alice", "role": "admin"}
 
 
def test_user_role(user):
    assert user["role"] == "admin"

You can control how often fixtures run:

  • function (default)
  • class
  • module
  • session
fixture_scope.py
import pytest
 
 
@pytest.fixture(scope="module")
def expensive_resource():
    return [1, 2, 3]
fixture_yield.py
import pytest
 
 
@pytest.fixture
def temp_config_file(tmp_path):
    p = tmp_path / "config.json"
    p.write_text('{"mode": "test"}')
    yield p
    # cleanup happens automatically for tmp_path

A yield fixture runs its setup code, hands the value to the test, and then resumes after the test to run its teardown code.

diagram Pytest Fixture Flow mermaid
A fixture runs setup, yields a value to the test, then resumes for teardown after the test finishes.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading