Detecting Order Dependence in Flaky Tests

A flaky test can depend on prior state, timing, environment differences, or nondeterministic execution. Narrow the cause with deliberate changes.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Test sequence dependence first
  2. Preserve the evidence
  3. Reproduce the suspected pair under controlled order
  4. Look for implicit shared state and asynchronous work

Test sequence dependence first

When one test fails after a specific earlier test, run it alone and then after that earlier case. If the result changes, inspect shared configuration, files, and mutable objects. Independent fixtures create a clear starting state.

Preserve the evidence

Repeating only the whole suite may hide the particular order. Save the two-test sequence and verify a fix under both orders. A minimal failing input applies to test sequences as well as program data.[1]

Reproduce the suspected pair under controlled order

Suppose an expiry test passes alone and fails when a previous test leaves a fake clock active. Run each separately, then together in both orders without parallel scheduling. Comparing results isolates a state dependency. See fresh fixtures.

Test B alone: pass
A then B: B fails
B then A: both pass
Restoring the clock after A removes the difference

Look for implicit shared state and asynchronous work

Cache entries, locale, environment variables and background tasks can all persist. Fix the fixture lifecycle or the application resource ownership so every test order works. Check the outcome again under ordinary test execution.

References

  1. Python Software Foundation, unittest: Unit Testing Framework ↩