The @pytest.fixture decorator helps create reusable setup code for tests. It makes tests cleaner and avoids repeating the same preparation steps.
0
0
@pytest.fixture decorator
Introduction
When multiple tests need the same setup, like creating a test database connection.
When you want to prepare test data once and use it in many tests.
When you want to clean up resources after tests run, like closing files or connections.
When you want to share common objects or states between tests without repeating code.
Syntax
PyTest
@pytest.fixture def fixture_name(): # setup code yield resource # teardown code (optional)
The function decorated with @pytest.fixture can return or yield a resource.
Using yield allows you to run cleanup code after the test finishes.
Examples
This fixture returns a simple list that tests can use.
PyTest
@pytest.fixture def sample_data(): return [1, 2, 3]
This fixture opens a file before the test and closes it after the test finishes.
PyTest
@pytest.fixture def open_file(): f = open('test.txt', 'w') yield f f.close()
Sample Program
This test script uses the numbers fixture to provide a list to two tests. Both tests use the same data without repeating setup code.
PyTest
import pytest @pytest.fixture def numbers(): return [10, 20, 30] def test_sum(numbers): assert sum(numbers) == 60 def test_max(numbers): assert max(numbers) == 30
OutputSuccess
Important Notes
Fixtures improve test readability and reduce duplicated setup code.
You can use fixtures inside other fixtures to build complex setups.
Fixtures can have scopes like function, module, or session to control how often they run.
Summary
@pytest.fixture creates reusable setup code for tests.
Fixtures help keep tests clean and avoid repeating preparation steps.
Use yield in fixtures to add cleanup after tests run.