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

๐Ÿงช 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