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)classclassmodulemodulesessionsession
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_pathfixture_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_pathVisualize 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.
flowchart LR A["Fixture setup code runs"] --> B["Yields value to test"] B --> C["Test runs using the value"] C --> D["Teardown code (after yield) runs"]
🧪 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 coffeeWas this page helpful?
Let us know how we did
