01 / 20

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.

Python

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.

def test_addition(): result = 2 + 2 assert result == 4 # Always passes

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.

Same Input Run 1 PASS ✓ Run 2 PASS ✓ Run 3 PASS ✓ Same Result Every Time

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.

Same Input Run 1 FAIL ✕ Run 2 PASS ✓ Run 3 FAIL ✕ Random Results

Why Does This Matter?

✓ Trust
Deterministic tests build confidence. A passing suite means the code works.
✕ Erosion
Flaky tests erode trust. Teams start re-running failures "just to check," wasting time.
★ Cost
Google found that 16% of their test failures were flaky: a massive engineering cost.

The Golden Rule of Testing

\( f(\text{same code, same input}) \) \( = \text{same result, always} \)
SOURCES OF NON-DETERMINISM Time datetime.now() Randomness random.randint() Network API calls Concurrency Thread races Eliminate these → Deterministic tests

Four Sources of Flakiness

1
Time dependence: Tests that call datetime.now() or compare timestamps can fail depending on when they run.
2
Randomness: Using random.choice() or random.randint() means different values each run, causing unexpected assertion failures.
3
External systems: Tests hitting a real database, API, or file system can fail when that system is slow, down, or returns different data.
4
Concurrency and ordering: Tests that depend on execution order, shared state, or thread timing introduce race conditions.

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

1
Isolate external systems: Use mocks, stubs, or fakes instead of real databases or APIs.
2
Fix the clock: Inject a fake time provider or use freezegun to freeze datetime.now().
3
Seed your randomness: Call random.seed(42) before the test so the "random" values are predictable.
4
Avoid shared state: Each test should set up its own data and tear it down afterward.
5
Never depend on test order: Tests must pass whether run first, last, or alone.

Example 1: A Flaky Test

import random def generate_id(): return random.randint(1000, 9999) def test_generate_id(): result = generate_id() assert result == 5432 # Flaky!

Example 1: The Fix

import random def generate_id(): return random.randint(1000, 9999) def test_generate_id(): random.seed(42) # Fix the seed! result = generate_id() assert 1000 <= result <= 9999 # Test the range

Example 2: Time Dependence

from datetime import datetime def greeting(): hour = datetime.now().hour if hour < 12: return "Good morning" return "Good afternoon" def test_greeting(): assert greeting() == "Good morning" # Flaky!

Example 2: The Fix

from unittest.mock import patch from datetime import datetime def greeting(): hour = datetime.now().hour if hour < 12: return "Good morning" return "Good afternoon" @patch("__main__.datetime") def test_greeting_morning(mock_dt): mock_dt.now.return_value = datetime(2024, 1, 1, 9, 0) assert greeting() == "Good morning" # Always passes

Example 3: Network Calls

import requests def get_user_name(user_id): resp = requests.get(f"https://api.example.com/users/{user_id}") return resp.json()["name"] def test_get_user_name(): name = get_user_name(1) assert name == "Alice" # Flaky: depends on live API
# Fix: mock the HTTP call @patch("__main__.requests.get") def test_get_user_name(mock_get): mock_get.return_value.json.return_value = {"name": "Alice"} assert get_user_name(1) == "Alice" # Deterministic!

Common Mistakes

✕ Ignoring Flaky Tests
Marking failing tests as "skip" instead of fixing the root cause. The bug hides in plain sight.
✕ Re-Running Until Green
Running the test suite 3 times and hoping it passes. This masks non-determinism instead of fixing it.
✕ Shared Global State
Tests that write to a shared variable or file. One test's side effect corrupts another's expected state.

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

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?