Automate test using @pytest.fixture for setup
Preconditions (2)
✅ Expected Result: The test passes confirming the fixture provides correct data
import pytest @pytest.fixture def sample_data(): return {"name": "Alice", "age": 30} def test_sample_data(sample_data): assert sample_data["name"] == "Alice" assert sample_data["age"] == 30
The @pytest.fixture decorator marks the sample_data function as a fixture. This means pytest will run it before the test that uses it and provide its return value as an argument.
The test function test_sample_data accepts sample_data as a parameter. Pytest automatically calls the fixture and passes its return value.
Assertions check that the fixture data matches expected values. This confirms the fixture setup works correctly.
This approach avoids repeating setup code in multiple tests and keeps tests clean and focused.
Modify the fixture to accept a parameter for 'name' and 'age' and run the test with three different sets of data
@pytest.fixture decorator in pytest?@pytest.fixture does@pytest.fixture decorator is used to create setup code that can be reused in many tests to avoid repetition.db_connection in pytest?@pytest.fixture, fully qualified with the pytest module.@pytest.fixture correctly. def db_connection(): pass misses the decorator. @fixture
def db_connection(): pass uses @fixture without importing. @pytest.test
def db_connection(): pass uses @pytest.test which is invalid.@pytest.fixture before function [OK]import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_sum(sample_data):
assert sum(sample_data) == 6
print('Test passed')sample_data returns a list [1, 2, 3]. The test receives this list as argument.import pytest
@pytest.fixture
def resource():
setup = open('file.txt')
yield setup
setup.close()import pytest
@pytest.fixture
def temp_file():
f = open('temp.txt', 'w')
yield f
f.close()Pass the test and this pattern moves unknown