How to Use Fixture in pytest: Simple Guide with Examples
In
pytest, a fixture is a function decorated with @pytest.fixture that prepares test data or resources. You use it by adding the fixture name as a parameter to your test function, and pytest will run the fixture first and pass its result to the test.Syntax
A fixture is defined by creating a function and decorating it with @pytest.fixture. The fixture function can return data or set up resources. To use the fixture, include its name as a parameter in your test function. Pytest will automatically call the fixture before the test runs and provide its return value.
- @pytest.fixture: marks the function as a fixture.
- fixture function: prepares data or resources.
- test function parameter: names the fixture to use.
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 provides a list of numbers. The test function uses this fixture to check if the sum of the list is correct. The fixture runs before the test and passes the list to it.
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.
- Using fixtures without the
@pytest.fixturedecorator. - Trying to use fixtures inside test classes without proper setup.
- Modifying fixture data inside tests, which can cause unexpected results if the fixture is reused.
python
import pytest # Wrong: missing decorator def data(): return 5 def test_wrong(data): # This will fail because 'data' is not a fixture assert data == 5 # Right way @pytest.fixture def data(): return 5 def test_right(data): assert data == 5
Quick Reference
Remember these tips when using fixtures in pytest:
- Use
@pytest.fixtureto define a fixture. - Pass the fixture name as a parameter to your test function.
- Fixtures can return data or set up/tear down resources.
- Fixtures run before each test that uses them by default.
- Use
scopeparameter in@pytest.fixtureto control fixture lifetime (e.g., function, module, session).
Key Takeaways
Define fixtures with @pytest.fixture to prepare test data or resources.
Use fixture names as parameters in test functions to access fixture data.
Fixtures run automatically before tests that request them.
Always decorate fixture functions properly to avoid silent failures.
Use fixture scope to control how often fixtures are set up.