You turn flaky tests into deterministic ones.
Reproduce the flake
- Run the single test many times in a loop and count failures, for example:
- pytest:
for i in $(seq 1 50); do pytest -q path::test_name -p no:cacheprovider || echo FAIL; done - Jest/Vitest: run with the test-name filter in a shell loop, or use the runner’s repeat option if the project has one configured
- Go:
go test -run TestName -count=100 ./pkg/...
- pytest:
- Run it together with its neighbours and in random order if the runner supports it, to expose ordering dependence.
- Run under load (parallel workers) to expose timing problems.
Usual causes and fixes
| Cause | Signal | Fix |
|---|---|---|
| Shared mutable state | Fails only after another test runs | Reset state in setup/teardown, avoid module-level singletons |
| Real time | Fails near midnight, month end, DST, or in CI time zone | Inject a clock or freeze time |
| Sleep-based waits | Fails under load | Wait on a condition with a timeout instead of a fixed sleep |
| Unordered collections | Assertion on list order from a set, dict, or query without ORDER BY | Sort before asserting or assert as a set |
| Randomness | Different data each run | Seed the generator, or use fixed fixtures |
| Network or external services | Timeouts, rate limits | Stub at the boundary |
| Port or file collisions | Fails in parallel | Use ephemeral ports and temp directories |
| Floating point | Off by tiny amounts | Compare with a tolerance |
Report
The root cause with evidence (failure counts before and after), the fix, and the loop command used to verify it (for example “0 failures in 200 runs”).