Deterministic vs.
Non-Deterministic Tests
Learn why some tests always produce the same result and others behave like a coin flip: sometimes passing, sometimes failing, with no code changes at all.
What Is a Software Test?
A test is a small program that runs your code automatically and checks whether the output matches what you expect. If the output matches: the test passes. If not: it fails.
What Does Deterministic Mean?
A deterministic test produces the exact same outcome every time it runs, given the same code and the same inputs. There is no randomness, no dependency on timing, and no reliance on external systems.
What Is a Non-Deterministic Test?
A non-deterministic test (often called a "flaky" test) can produce different results on different runs, even though nothing in the code changed. It might pass 9 out of 10 times, then suddenly fail.
Why Does This Matter?
The Golden Rule of Testing
Four Sources of Flakiness
Deterministic vs. Flaky: Side by Side
| Deterministic | Non-Deterministic (Flaky) | |
|---|---|---|
| Same code, repeated runs | Always same result | Result may vary |
| External dependencies | None or mocked | Real services, network |
| Time / randomness | Fixed or seeded | Uses live clock / RNG |
| Team trust | High: failures = real bugs | Low: "just re-run it" |
| Debugging difficulty | Easy: reproducible | Hard: intermittent |
How to Make Tests Deterministic
Example 1: A Flaky Test
Example 1: The Fix
Example 2: Time Dependence
Example 2: The Fix
Example 3: Network Calls
Common Mistakes
Question 1 of 5
A test calls datetime.now() and asserts the result is a specific date. This test passes at midnight but fails at noon. This is an example of:
Question 2 of 5
Which of the following is the best way to make a test that uses random.randint() deterministic?
Question 3 of 5
A test sends a real HTTP request to an external API. The API goes offline for maintenance, and the test fails. What is the root cause of this non-determinism?
Question 4 of 5
Test A writes a record to a shared database.
Test B reads from that database and asserts the record count is 1.
When run individually, both pass. When run together, Test B sometimes sees 2 records (if Test A ran first and didn't clean up).
What principle is being violated here?
Question 5 of 5
A developer's test suite has 200 tests. 15 of them fail intermittently. The developer's solution is to re-run the suite until all tests pass, then merge the code. What is the biggest problem with this approach?