Automate test setup using advanced pytest fixtures for complex scenario
Preconditions (2)
✅ Expected Result: Tests run successfully using the advanced fixture, data is inserted correctly, and setup/teardown happens only once
import pytest class FakeDatabase: def __init__(self): self.data = [] self.connected = False def connect(self): self.connected = True def disconnect(self): self.connected = False def insert(self, item): if not self.connected: raise Exception("Not connected") self.data.append(item) def get_all(self): return self.data @pytest.fixture(scope="module") def db(): db_instance = FakeDatabase() db_instance.connect() # Setup yield db_instance db_instance.disconnect() # Teardown def test_insert_data(db): db.insert({'id': 1, 'name': 'Test Item'}) all_data = db.get_all() assert {'id': 1, 'name': 'Test Item'} in all_data def test_insert_another_data(db): db.insert({'id': 2, 'name': 'Another Item'}) all_data = db.get_all() assert {'id': 2, 'name': 'Another Item'} in all_data
This code defines a FakeDatabase class to simulate a database connection and data insertion.
The db fixture uses scope='module' so it sets up once per module, connecting before tests and disconnecting after all tests finish. The yield keyword separates setup and teardown.
Two tests use the db fixture to insert data and verify it was added correctly. Because the fixture is module-scoped, the database connection is reused, demonstrating how advanced fixtures handle complex setup and teardown efficiently.
Now add data-driven testing with 3 different data inputs using the advanced fixture
import pytest
@pytest.fixture
def resource():
print('Setup resource')
yield 'data'
print('Cleanup resource')
def test_example(resource):
print(f'Using {resource}')import pytest
@pytest.fixture
def setup_db():
connection = open_db()
return connection
close_db(connection)
def test_query(setup_db):
assert setup_db.is_connected()Pass the test and this pattern moves unknown