How to Use Fixtures in pytest for Cleaner Tests
In
pytest, fixtures are functions decorated with @pytest.fixture that provide setup code for tests. You use them by adding the fixture name as a parameter to your test functions, and pytest automatically runs the fixture before the test.Syntax
A fixture is defined using the @pytest.fixture decorator above a function. This function prepares some data or state and returns it. To use the fixture, include its name as a parameter in your test function, and pytest will call the fixture first and pass its result to the test.
@pytest.fixture: marks a function as a fixture- Fixture function: sets up and returns data or resources
- Test function parameter: named after the fixture to receive its output
python
import pytest @pytest.fixture def sample_data(): return [1, 2, 3] def test_sum(sample_data): assert sum(sample_data) == 6
Example
This example shows a fixture that creates a list of numbers. The test function uses this fixture to check if the sum is correct. The fixture runs before the test and provides the data automatically.
python
import pytest @pytest.fixture def numbers(): print("Setting up numbers fixture") return [10, 20, 30] def test_total(numbers): assert sum(numbers) == 60 def test_length(numbers): assert len(numbers) == 3
Output
Setting up numbers fixture
.
Setting up numbers fixture
.
Common Pitfalls
Common mistakes when using fixtures include:
- Not adding the fixture name as a parameter in the test function, so the fixture never runs.
- Trying to use fixtures without the
@pytest.fixturedecorator. - Modifying fixture data inside tests without copying it, which can cause unexpected side effects.
Always keep fixtures simple and stateless to avoid test interference.
python
import pytest # Wrong: fixture missing decorator # def data(): # return [1, 2, 3] @pytest.fixture def data(): return [1, 2, 3] def test_wrong(): # Fixture not used because parameter missing assert True def test_right(data): assert sum(data) == 6
Quick Reference
| Fixture Feature | Description |
|---|---|
| @pytest.fixture | Decorator to define a fixture function |
| Fixture function | Sets up and returns test data or resources |
| Test parameter | Use fixture name as test function argument |
| Scope | Control fixture lifetime (function, module, session) |
| Autouse | Run fixture automatically without test parameter |
Key Takeaways
Define fixtures with @pytest.fixture to prepare reusable test data or setup.
Use fixture names as parameters in test functions to access fixture data.
Avoid modifying fixture data inside tests to prevent side effects.
Fixtures help keep tests clean and reduce repeated setup code.
You can control fixture scope and automatic use for flexible testing.