Test data, cleanup and risk-based priorities
A test owns its data: it creates it through the API, uses it and cleans up, so the result does not depend on run order or neighbouring workers. Fields with a uniqueness constraint get unique values, access is checked with separate accounts, and cleanup runs in a finalizer so it happens even after a failure. What to test first is set by risk: the probability of a defect times its impact.
API · Test design
A suite is green in the morning and red in the evening: a test fails on the second run. Where do data come from and what comes first?
A test creates a user with the email qa@test.example. The first run is green, the second fails with 409: a user with that email already exists. A colleague runs the suite in parallel and the tests fight over the same entity. That is not an API defect, it is a test design defect: data and the order of work need design just like the cases themselves. The second question that comes with it: you cannot check everything, so where do you start.
How it works and why
There is one principle: a test owns its data. It creates what it needs through the API (or a setup step), uses it and cleans up after itself. Then the result depends only on the test code and the system, not on what is left from yesterday's run or what a neighbouring worker is doing right now.
Shared data versus own data
Shared data and order
Test B waits for the result of test A and for a permanent user from a previous run. Alone, in parallel or for the second time it fails.
Data per test
Each test creates unique data, checks and cleans up. Running in any order and in parallel gives the same result.
A set of rules for data follows from this:
- Unique values for fields with a uniqueness constraint (a suffix from a random string), otherwise the second run fails with
409. - Separate accounts for roles (user, admin, another user): access tests need a "foreign" owner of a resource.
- Permanent read-only data (reference lists, tariffs) that nobody changes.
- Minimal data: only what the case needs. A production dump is not suitable, because it contains personal data.
- Time and randomness are tested through fixed values or a range, not by expecting an exact "now".
Example: from a shared scenario to a fixture with cleanup
Before: two tests where the second uses the result of the first.
// two tests that depend on each other and on the previous run
let orderId: string;
test('create order', async ({ request }) => { orderId = (await create(request)).id; });
test('pay order', async ({ request }) => { await pay(request, orderId); });
// run "pay order" alone, or in another worker: orderId is undefined
The test "pay order" cannot be run alone, and after a change of order or on another worker orderId is empty. After: a Playwright fixture creates an order for each test and deletes it in the teardown.
import { test as base, expect } from '@playwright/test';
export const test = base.extend<{ order: { id: string } }>({
order: async ({ request }, use) => {
const res = await request.post('/v1/orders', { data: { sku: 'A1', quantity: 1 } });
expect(res.status()).toBe(201);
const order = await res.json();
await use(order); // the test runs here
const del = await request.delete('/v1/orders/' + order.id); // runs even if the test failed
expect(del.ok(), 'cleanup must not fail silently').toBeTruthy();
},
});
test('pay own order', async ({ request, order }) => {
const res = await request.post('/v1/orders/' + order.id + '/pay');
expect(res.status()).toBe(200);
});
The code after use runs even when the test failed, so cleanup does not depend on success. A unique value for a field with a uniqueness constraint:
const email = 'qa+' + crypto.randomUUID().slice(0, 8) + '@test.example';
const res = await request.post('/v1/users', { data: { name: 'Olena', email } });
Cleanup can also be environmental: resetting the database before a run or a separate tenant per run. The main point is that it must not mask a defect: if DELETE does not work, a separate test should show it, not a silently swallowed error in the teardown. Leftover data from past runs is a typical cause of flaky tests, and tests that run in parallel must not share one entity.
Priorities by risk. You cannot fully check everything, so the order is set by risk: probability of a failure × consequences. The estimate is made with the team on a simple scale from 1 to 3.
| Endpoint | Probability | Impact | Risk | Depth of tests |
|---|---|---|---|---|
POST /transfers (new logic, money) | 3 | 3 | 9 | Full: classes, boundaries, negatives, states, permissions, repeat |
GET /orders/{id} (other people's data) | 2 | 3 | 6 | Permissions, 404 versus 403, response fields |
GET /products (filters) | 2 | 2 | 4 | Positives, pairwise of parameters |
GET /config/colors (stable for ages) | 1 | 1 | 1 | One positive scenario |
Limits and alternatives
- Data from the API or from the database. Creating through the API also checks that very operation, but it is slower and depends on it working. Filling the database directly is faster but bypasses business logic. Often both are combined: the API for entities, the database for rare states.
- Resetting the environment per run is simple when it is isolated (a container, a separate schema). In a shared environment per-test cleanup is better.
- The risk scale is subjective. It is agreed with the team and reviewed after incidents: a failure that has already happened raises the probability.
- High risk: money, authorization and access to other people's data, irreversible changes, new or frequently changed logic, integrations with third-party systems. Medium: the main business scenarios, search, filters, pagination. Low: rare configurations, cosmetic fields, long-stable code.
Common mistakes
- One permanent user for all tests. One test changes the password, another fails, and the cause is hunted for hours.
- Deleting data only at the end of a successful suite. After a failure it stays and breaks the next run.
- Testing everything evenly. An hour on reference-list colours and five minutes on transfers is an inverted priority.
- Catching a cleanup error with an empty
catch. A delete defect disappears without a trace while garbage accumulates.
Check yourself
The test "pay an order" fails when run alone but passes as part of the whole suite. What does that mean and what should change?
Answer
The test depends on data created by another test. Make it self-sufficient: a fixture or a setup step of the same test creates the order and cleans up after it.
There are two endpoints: POST /payments (new logic) and GET /countries (stable for ages). Time is short. Which one gets deeper coverage, and why?
Answer
POST /payments. It handles money (high impact), and new logic raises the probability of a failure. The reference list /countries is stable and low risk, a positive scenario is enough.