Test Overview
This test demonstrates how pytest fixtures help create reusable test setups. It verifies that the fixture provides the same setup data to multiple tests.
This test demonstrates how pytest fixtures help create reusable test setups. It verifies that the fixture provides the same setup data to multiple tests.
import pytest @pytest.fixture def sample_data(): print("Setting up data") return {"name": "Alice", "age": 30} def test_name(sample_data): assert sample_data["name"] == "Alice" def test_age(sample_data): assert sample_data["age"] == 30
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and discovers tests | pytest is ready to run test_name and test_age | — | PASS |
| 2 | pytest calls fixture sample_data before test_name | Prints 'Setting up data', returns {'name': 'Alice', 'age': 30} | — | PASS |
| 3 | test_name runs using sample_data fixture | sample_data contains {'name': 'Alice', 'age': 30} | Assert sample_data['name'] == 'Alice' | PASS |
| 4 | pytest calls fixture sample_data before test_age | Prints 'Setting up data', returns {'name': 'Alice', 'age': 30} | — | PASS |
| 5 | test_age runs using sample_data fixture | sample_data contains {'name': 'Alice', 'age': 30} | Assert sample_data['age'] == 30 | PASS |
test_example?
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_example(sample_data):
assert sum(sample_data) == 6
print('Test passed')import pytest
@pytest.fixture
def resource():
return open('file.txt', 'r')
def test_read(resource):
data = resource.read()
assert data != ''
resource.close()@pytest.fixture
def db_connection():
conn = connect_to_db()
return conn@pytest.fixture
def db_connection():
conn = connect_to_db()
yield conn
conn.close() correctly uses yield and closes connection after test. Add a try-except block inside the fixture to catch errors does not guarantee cleanup. Call conn.close() before returning conn closes before returning, breaking connection. Remove the fixture and open connection inside each test removes fixture benefits.Pass the test and this pattern moves unknown