Designing database test fixtures: isolation and cleanup
A database test fixture is the data and resources that put a test in a reproducible starting state. It may create a user or order needed by one test, then roll back or clean up so the next test is unaffected. Unlike seed data deployed as reference data, a fixture's lifetime belongs to the test run.
Designing database test fixtures: isolation and cleanup
A database test fixture is the data and resources that put a test in a reproducible starting state. It may create a user or order needed by one test, then roll back or clean up so the next test is unaffected. Unlike seed data deployed as reference data, a fixture's lifetime belongs to the test run.
Why fixtures matter
Tests that depend on existing rows or execution order may pass locally and fail in CI. Declare the needed state so a failure can be reproduced. For example, a cancellation test can create an owner and a pending order, invoke cancellation, and check the state transition. These records belong to that scenario; they should not be mutable global data shared by every test.
A fixture can also own a database connection, transaction, temporary schema, or test object. Make setup and cleanup ownership explicit. Resources outside the database transaction need their own teardown.
Choose a lifetime
Start with fresh data and cleanup per test function. Reusable factories are fine, but have each test create rows with unique keys. pytest's default fixture scope is function; it also supports class, module, package, and session. A broader scope can save expensive setup, but mutable shared data can couple tests. Share only immutable baseline data or resources whose state is isolated; otherwise use per-test transactions and unique records.
Rollback, deletion, or reset
When a test stays on one connection inside a transaction and the database supports the needed behavior, rollback is often simple and fast. SQLAlchemy 2.0 documents a pattern that binds a session to an external transaction with join_transaction_mode="create_savepoint", then rolls back the outer transaction at teardown. This depends on correct SAVEPOINT support in the database and driver.
A rollback cannot be assumed to undo writes made on another connection or process, committed work, or effects outside the database. DDL transaction behavior also varies by database. For such tests, consider a dedicated test database with table reset, a disposable schema, or deleting only rows created by the test. First verify the target is a dedicated test environment, and constrain reset permissions and scope so cleanup cannot reach production.
Django illustrates the trade-off: TestCase wraps tests in transactions and rolls them back, which is fast but unsuitable for observing some real commit/rollback behavior. TransactionTestCase resets tables after a test and allows transaction effects to be observed. Backend support changes the behavior and cost, so check the framework's behavior with the database engine in use.
Example with pytest and SQLAlchemy
The following illustrates structure; it has not been run. engine, Customer, Order, and cancel_order must come from the application, and the database/driver must support the transaction pattern.
import pytest
from sqlalchemy.orm import Session
@pytest.fixture
def db_session(engine):
connection = engine.connect()
outer = connection.begin()
session = Session(bind=connection, join_transaction_mode="create_savepoint")
try:
yield session
finally:
session.close()
outer.rollback()
connection.close()
def test_order_can_be_cancelled(db_session):
customer = Customer(name="fixture-customer")
order = Order(customer=customer, status="pending")
db_session.add(order)
db_session.flush()
cancel_order(db_session, order.id)
db_session.flush()
assert order.status == "cancelled"Code after yield is pytest teardown and runs after the test, including when the test fails. If setup fails before yield, that fixture's later cleanup does not run. Split resource setup into fixtures that each clean up what they successfully created. Do not assume this pattern undoes another connection's writes, committed work, or effects such as sending a message.
Check isolation and parallel runs
Use unique keys rather than fixed shared IDs, and remove only rows the test created. Respect foreign-key dependencies when deleting. After a failure, inspect whether rows remain; run the test alone and in the full suite and compare outcomes. Parallel workers sharing a database can still collide on unique constraints, resets, or edits to common baseline rows. Prefer a database or schema per worker; if that is not feasible, include a worker identifier in test keys and keep global resets out of the parallel section.
Before adopting a fixture, ask: is its required state visible in code? Is its default lifetime one test? Are resources cleaned up on success and failure? Does rollback cover every connection and side effect? Is the database unmistakably a test target? Are parallel workers isolated?
Good fixtures make dependencies explicit and define who removes their state. Begin with test-scoped data and a dedicated test database; only widen lifetimes or share baseline data when measured setup cost justifies the added coupling.
Sources
[pytest: How to use fixtures](https://docs.pytest.org/en/stable/how-to/fixtures.html)
[SQLAlchemy 2.0: External transactions for test suites](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#joining-a-session-into-an-external-transaction-such-as-for-test-suites)
[Django 5.2: Testing tools](https://docs.djangoproject.com/en/5.2/topics/testing/tools/#testcase)