Fixtures help you prepare things once and use them many times in your tests. This saves time and keeps tests clean.
0
0
Why fixtures provide reusable test setup in PyTest
Introduction
When you need to create a database connection before running tests.
When you want to set up a web browser for multiple web tests.
When you need to prepare test data that many tests will use.
When you want to clean up resources after tests finish.
When you want to avoid repeating the same setup code in every test.
Syntax
PyTest
import pytest @pytest.fixture def resource(): # setup code resource_object = [] yield resource_object # teardown code
Use @pytest.fixture to mark a function as a fixture.
The yield keyword separates setup and teardown parts.
Examples
This fixture returns a list that tests can use.
PyTest
import pytest @pytest.fixture def sample_data(): data = [1, 2, 3] return data
This fixture opens a file before a test and closes it after.
PyTest
import pytest @pytest.fixture def open_file(): f = open('test.txt', 'w') yield f f.close()
Sample Program
This example shows a fixture number_list that sets up a list for tests. The setup message prints once before tests, and the teardown message prints after tests finish.
PyTest
import pytest @pytest.fixture(scope="module") def number_list(): print('Setup: Creating list') data = [10, 20, 30] yield data print('Teardown: Cleaning up') def test_sum(number_list): assert sum(number_list) == 60 def test_len(number_list): assert len(number_list) == 3
OutputSuccess
Important Notes
Fixtures run before the test that uses them and can clean up after with yield.
Using fixtures avoids repeating setup code in every test function.
Fixtures can be shared across many tests for consistency.
Summary
Fixtures prepare reusable test setup to keep tests simple and clean.
They help avoid repeating the same setup code in multiple tests.
Fixtures can also handle cleanup after tests automatically.