Skip to content

Pytest Fixtures - Managing Test Dependencies

What is a fixture?

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

Use fixtures for:

  • test data factories
  • temporary resources
  • dependency setup (clients, config)

Basic fixture

test_fixture_basic.py
import pytest
 
 
@pytest.fixture
def user():
    return {"name": "Alice", "role": "admin"}
 
 
def test_user_role(user):
    assert user["role"] == "admin"
test_fixture_basic.py
import pytest
 
 
@pytest.fixture
def user():
    return {"name": "Alice", "role": "admin"}
 
 
def test_user_role(user):
    assert user["role"] == "admin"

Fixture scope

You can control how often fixtures run:

  • functionfunction (default)
  • classclass
  • modulemodule
  • sessionsession
fixture_scope.py
import pytest
 
 
@pytest.fixture(scope="module")
def expensive_resource():
    return [1, 2, 3]
fixture_scope.py
import pytest
 
 
@pytest.fixture(scope="module")
def expensive_resource():
    return [1, 2, 3]

Yield fixtures (cleanup)

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
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

Visualize it

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.

🧪 Try It Yourself

Exercise 1 – Write a unittest TestCase

Exercise 2 – assertRaises

Exercise 3 – setUp and tearDown

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did