Pytest Fixtures - Managing Test Dependencies
What is a fixture?
Section titled “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
Section titled “Basic fixture”import pytest
@pytest.fixture
def user():
return {"name": "Alice", "role": "admin"}
def test_user_role(user):
assert user["role"] == "admin"Fixture scope
Section titled “Fixture scope”You can control how often fixtures run:
function(default)classmodulesession
import pytest
@pytest.fixture(scope="module")
def expensive_resource():
return [1, 2, 3]Yield fixtures (cleanup)
Section titled “Yield fixtures (cleanup)”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
Section titled “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.
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
Section titled “🧪 Try It Yourself”Exercise 1 – Write a unittest TestCase
Section titled “Exercise 1 – Write a unittest TestCase”Exercise 2 – assertRaises
Section titled “Exercise 2 – assertRaises”Exercise 3 – setUp and tearDown
Section titled “Exercise 3 – setUp and tearDown”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading