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.