---
title: "Give each test its own data · Agent Wranglers"
url: https://agentwranglers.se/playbook/testing/test-data-and-environments/isolated-test-data
updated: 2026-10-20
licence: "All rights reserved"
---

# Give each test its own data

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Test data and environments](https://agentwranglers.se/playbook/testing/test-data-and-environments)
- Rule: Each test creates the data it needs and leaves nothing behind that another test could see.
- How: 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.
- Check: Run one test alone, then the whole suite in random order. Both pass.

Example:

```python
@pytest.fixture
def db(connection):
    transaction = connection.begin()
    yield connection
    transaction.rollback()
```

```ts
// 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(); });
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers testing playbook: https://agentwranglers.se/playbook/testing/test-data-and-environments/isolated-test-data`.

- Previous: [Build test data with factories](https://agentwranglers.se/playbook/testing/test-data-and-environments/data-factories)
- Next: [Keep a staging copy with fake data](https://agentwranglers.se/playbook/testing/test-data-and-environments/production-like-staging)
- [Test data and environments](https://agentwranglers.se/playbook/testing/test-data-and-environments)
