How to Use @pytest.fixture for Setup in Tests
Use
@pytest.fixture to define reusable setup functions that provide test data or state. Mark a function with @pytest.fixture and pass it as an argument to your test functions to use the setup automatically.Syntax
The @pytest.fixture decorator marks a function as a fixture. This function can prepare data or state for tests. Tests receive the fixture by naming it as a parameter.
@pytest.fixture: Decorator to define a fixture.- Fixture function: Returns data or sets up state.
- Test function: Accepts fixture name as argument to use it.
python
import pytest @pytest.fixture def sample_data(): return [1, 2, 3] def test_sum(sample_data): assert sum(sample_data) == 6
Output
============================= test session starts =============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ==============================
Example
This example shows a fixture that provides a list. The test uses this list to check the sum. The fixture runs before the test and passes its return value automatically.
python
import pytest @pytest.fixture def numbers(): print("Setup: Creating numbers list") return [10, 20, 30] def test_total(numbers): assert sum(numbers) == 60 def test_length(numbers): assert len(numbers) == 3
Output
============================= test session starts =============================
collected 2 items
Setup: Creating numbers list
.
Setup: Creating numbers list
.
test_example.py .. [100%]
============================== 2 passed in 0.01s ==============================
Common Pitfalls
Common mistakes include:
- Not using the fixture name as a test argument, so the fixture never runs.
- Modifying fixture data inside tests, which can cause unexpected results if reused.
- Using
printstatements expecting output without running pytest with -s option.
python
import pytest @pytest.fixture def data(): return [1, 2, 3] def test_wrong(): # Fixture 'data' is defined but not used here assert True def test_right(data): # Correct usage: fixture passed as argument assert sum(data) == 6
Output
============================= test session starts =============================
collected 2 items
test_pitfalls.py . [100%]
============================== 2 passed in 0.01s ==============================
Quick Reference
Remember these tips when using @pytest.fixture:
- Define setup code in a function decorated with
@pytest.fixture. - Use the fixture by naming it as a parameter in your test functions.
- Fixtures can return data or perform setup/teardown.
- Use
scopeparameter to control fixture lifetime (function, module, session).
Key Takeaways
Use @pytest.fixture to create reusable setup code for tests.
Pass fixture names as test function arguments to use them.
Fixtures can return data or perform setup tasks before tests run.
Avoid modifying fixture data inside tests to prevent side effects.
Use fixture scope to control how often setup runs.