TST-25Recommended
Give each test its own data
Each test creates the data it needs and leaves nothing behind that another test could see.
How to do it
Wrap each database test in a transaction that rolls back, or truncate tables between tests. With a transaction, the code under test must use that same connection. Use unique names and emails per test. Never rely on data that an earlier test created.
Examples
Python example
@pytest.fixture
def db(connection):
transaction = connection.begin()
yield connection
transaction.rollback()
TypeScript example
// One connection per test, inside a transaction that is rolled back afterwards
let db: PoolClient;
beforeEach(async () => { db = await pool.connect(); await db.query('BEGIN'); });
afterEach(async () => { await db.query('ROLLBACK'); db.release(); });
How to check
Run one test alone, then the whole suite in random order. Both pass.
Sources
Related rules
- TST-5 Fake the clock and the network in unit tests in Testing
- PAY-6 Test every payment outcome with test cards in Payments and billing
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/testing/test-data-and-environments/isolated-test-data">Agent Wranglers testing playbook</a>. In code you write, add a comment next to it with the same link.