Introduction
Database fixture patterns help set up and clean test data before and after tests run. This keeps tests reliable and repeatable.
Jump into concepts and practice - no test required
Database fixture patterns help set up and clean test data before and after tests run. This keeps tests reliable and repeatable.
import pytest @pytest.fixture(scope='function') def db_setup(): # Connect to database # Insert test data yield # Clean up test data # Close connection
Use @pytest.fixture to create a fixture function.
The scope controls how often the fixture runs (e.g., per function, module).
import pytest @pytest.fixture(scope='function') def setup_user(): print('Insert user data') yield print('Delete user data')
import pytest @pytest.fixture(scope='module') def setup_db(): print('Connect to DB') yield print('Disconnect from DB')
This test uses the db_setup fixture to prepare and clean test data around the test.
import pytest @pytest.fixture(scope='function') def db_setup(): print('Setup: Insert test data') yield print('Teardown: Remove test data') def test_example(db_setup): print('Running test') assert True
Always clean up test data to keep tests independent.
Use yield in fixtures to separate setup and teardown steps.
Choose fixture scope wisely to balance speed and isolation.
Database fixtures prepare and clean test data automatically.
Fixtures use @pytest.fixture and yield for setup and teardown.
Proper fixture use makes tests reliable and easy to maintain.
yield?import pytest
@pytest.fixture
def sample_db():
data = {'count': 0}
yield data
data['count'] += 1
def test_increment(sample_db):
print(sample_db['count'])
sample_db['count'] += 5
print(sample_db['count'])@pytest.fixture
def test_db():
conn = connect_db()
conn.execute('CREATE TABLE users')
return conn
conn.execute('DROP TABLE users')
conn.close()