fixture
- Python course
- Advanced
- Lesson 15/83
- 5 min
Learn fixtures with @pytest.fixture.
fixture
A fixture is setup code shared by tests. It builds database connections, sample data or temp files and cleans up when the test ends.
You decorate a function with @pytest.fixture; tests call it by its parameter name. pytest runs the fixture and injects the result into the parameter.
import pytest
@pytest.fixture
def sample_list():
return [1, 2, 3]
def test_total(sample_list):
assert sum(sample_list) == 6This avoids repeated setup and keeps tests short.
Fixture scope
Fixtures run fresh for each test by default (scope="function"). For heavy setup you can change this: scope="module" runs once per module, scope="session" once per session.
@pytest.fixture(scope="module")
def db():
return open_connection()A larger scope is faster but watch state sharing: if a test mutates data, later tests are affected. That's why most fixtures stay at function scope.
Practice Use sample_list with a fixture
Start with import pytest. Decorate sample_list() with @pytest.fixture; it returns [1, 2, 3]. The test function test_total(sample_list) runs assert sum(sample_list) == 6. End with test_total(sample_list()) and print("ok").
Starter code
# import the pytest module
# sample_list: fixture, returns [1, 2, 3]
# test_total(sample_list): runs sum check
# call test_total(sample_list()) then print "ok"Sample solution
import pytest
@pytest.fixture
def sample_list():
return [1, 2, 3]
def test_total(sample_list):
assert sum(sample_list) == 6
test_total(sample_list())
print("ok")Expected output
ok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a fixture used in a test?
- Imported with import
- Assigned as a global variable
- Passed as a parameter to the test function Correct answer
- Printed with print
Explanation: pytest injects the fixture result into the parameter with the same name.
2 Match the fixture concepts
| Term | Meaning |
|---|---|
@pytest.fixture |
Fixture marker |
def sample_list |
Fixture definition |
test_total(sample_list) |
Uses the fixture |
scope="module" |
Once per module |
3 Add the fixture decorator
import pytest
@____(scope="module")
def db():
return open_connection()
import pytest
@pytest.fixture(scope="module")
def db():
return open_connection()
Explanation: The @pytest.fixture marker makes the function a fixture; scope module runs once.