Automate reusable test setup using pytest fixture
Preconditions (2)
✅ Expected Result: Both tests pass using the same reusable 'sample_data' fixture setup
import pytest @pytest.fixture def sample_data(): return {"name": "Alice", "age": 30} def test_name_is_string(sample_data): assert isinstance(sample_data["name"], str), "Name should be a string" def test_age_is_integer(sample_data): assert isinstance(sample_data["age"], int), "Age should be an integer"
The @pytest.fixture decorator defines a reusable setup function sample_data that returns a dictionary. This fixture can be used by any test function by adding it as a parameter. This way, the setup code is written once and reused, making tests cleaner and easier to maintain.
Each test function receives the fixture data automatically. The assertions check the data types as required. This demonstrates how fixtures provide reusable test setup in pytest.
Now add a fixture that provides different user data sets and write tests that run with each data set
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