Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 15 min · revision 3

Fast, Deterministic, Not Flaky

Keep your test suite fast and reliable by controlling time, faking outbound HTTP calls, managing randomness, and quarantining the flaky tests that remain.

Contentsand lesson path

What you will learn

  • Keep the suite fast and deterministic by controlling time and randomness, faking external HTTP services and isolating flaky tests.

Prerequisites: Software Testing Fundamentals, Data Access with SQLAlchemy

01. Why it matters

A test suite that developers and CI pipelines trust is fast and deterministic: the same code gives the same result on every run. When a pull request build fails, engineers should be able to assume that the change under review caused it. But as test suites grow, three kinds of trouble appear: tests that sleep for seconds waiting for background tokens to expire, tests that fail whenever an external payment gateway experiences a momentary network timeout, and tests that fail intermittently once every thirty runs with no code changes.

Slow and flaky tests slow the whole team down. Developers stop running tests locally because the suite takes too long. Worse, when tests fail intermittently in CI, teams fall into the habit of clicking "Re-run failed jobs" until the build turns green. Once a team accepts intermittent test failures, the test suite ceases to be a trustworthy quality gate. In this lesson, you will learn how to remove the four most common causes of slow and flaky backend integration tests (real time, real network calls, unseeded randomness and state shared between tests), plus a quarantine policy for the flakes that remain, because concurrency, test ordering, resource leaks and infrastructure can still cause them.

A suite without false alarms or fixed sleeps is what makes refactoring and library upgrades affordable: when it fails, people investigate instead of pressing re-run.

02. Controlling time without sleeping

Testing time-dependent features—such as token expiration, rate limiting windows, scheduled job intervals, or session timeouts—is a frequent source of test bloat and flakiness. A naive solution is invoking time.sleep(2) or asyncio.sleep(15) inside the test to let real clock time elapse.

Calling sleep() in tests is an anti-pattern. If fifty tests each sleep for just one second, your test suite adds nearly a minute of dead idle time. Worse, if CI runners experience high CPU load, a fixed sleep duration may elapse before a background task finishes, causing intermittent race conditions.

The proper technique is controlling the clock. In Python, libraries like freezegun or time-machine let tests freeze the clock at an exact timestamp and move it forward by minutes or hours instantly. The example needs something with an expiry, so here is a small token store for the reading-list project; it reads the clock with datetime.now(timezone.utc), which freezegun replaces (install it with uv pip install freezegun):

Python · app/expiry.py
import secrets
from datetime import datetime, timedelta, timezone

_tokens: dict[str, tuple[int, datetime]] = {}  # token -> (user id, expiry)


def create_expiring_token(user_id: int, valid_minutes: int) -> str:
    token = secrets.token_urlsafe(16)
    expires = datetime.now(timezone.utc) + timedelta(minutes=valid_minutes)
    _tokens[token] = (user_id, expires)
    return token


def verify_token(token: str) -> int | None:
    """Return the user id, or None if the token is unknown or expired."""
    if token not in _tokens:
        return None
    user_id, expires = _tokens[token]
    if datetime.now(timezone.utc) > expires:
        return None
    return user_id
Python · tests/test_expiry.py
from datetime import datetime, timedelta, timezone

from freezegun import freeze_time

from app.expiry import create_expiring_token, verify_token


def test_token_expires_after_fifteen_minutes() -> None:
    start_time = datetime(2026, 10, 26, 12, 0, 0, tzinfo=timezone.utc)
    with freeze_time(start_time) as frozen_clock:
        # Issue a token valid for 15 minutes
        token = create_expiring_token(user_id=42, valid_minutes=15)
        assert verify_token(token) == 42

        # Move the frozen clock forward 16 minutes, without sleeping
        frozen_clock.tick(timedelta(minutes=16))

        # The token has now expired
        assert verify_token(token) is None

The test checks a 15-minute expiry without waiting. No wall-clock time passes, and the result does not depend on how busy the machine is. Note the boundary: verify_token uses >, so a token is still valid at the exact second it expires. With a frozen clock you can test both sides of that limit.

03. Faking external HTTP boundaries

Modern backend services rarely operate in isolation. They communicate with third-party payment processors (Stripe), email providers (SendGrid), identity providers (OAuth2 / Dex), and internal downstream microservices. Calling live third-party APIs from automated tests causes three problems:

  • Latency and rate limits. Every call to an external API adds a network round trip to the test, and a busy CI pipeline can hit the vendor's rate limits.
  • Vendor outages. An outage at an external vendor halts your engineering deployments even though your own application code is completely healthy.
  • Untestable failures. You cannot make a real vendor return a 502 Bad Gateway or time out on command, so the code that handles those cases goes untested.

Instead of hitting live endpoints, mock at the HTTP transport boundary using tools like respx or httpx.MockTransport. Here is a small billing client to test (install the libraries with uv pip install httpx respx); note the timeout, without which a hung gateway would hang the request too:

Python · app/billing.py
from dataclasses import dataclass

import httpx

CHARGES_URL = "https://api.payments.example.com/v1/charges"


@dataclass
class ChargeResult:
    status: str
    reason: str | None = None


def charge_card(user_id: int, amount_cents: int) -> ChargeResult:
    body = {"user_id": user_id, "amount_cents": amount_cents}
    try:
        response = httpx.post(CHARGES_URL, json=body, timeout=5.0)
    except httpx.TransportError:  # timeouts, refused connections, DNS errors
        return ChargeResult("failed", "payment_gateway_unavailable")
    if response.status_code >= 500:
        return ChargeResult("failed", "payment_gateway_unavailable")
    # Any other non-2xx answer (a 4xx, or even a 3xx) raises HTTPStatusError:
    # only a 5xx or a transport error is the gateway's fault.
    response.raise_for_status()
    return ChargeResult("succeeded")
Python · tests/test_payments.py
import respx
from httpx import Response

from app.billing import charge_card


@respx.mock
def test_payment_handles_gateway_outage_gracefully() -> None:
    # Intercept the outbound HTTP call to the payment vendor's API
    route = respx.post("https://api.payments.example.com/v1/charges").mock(
        return_value=Response(502, json={"error": "gateway_timeout"})
    )

    result = charge_card(user_id=10, amount_cents=4900)
    assert result.status == "failed"
    assert result.reason == "payment_gateway_unavailable"
    assert route.called

Intercepting at the HTTP transport layer exercises your real HTTP client code: serialisation, headers, status code parsing and exception handling, without a request leaving the machine. respx raises an error for any request that no route matches, so a forgotten call cannot slip out to the real API. To simulate a timeout, give the route side_effect=httpx.ConnectTimeout instead of a response.

With third-party services behind HTTP stubs, these tests no longer wait on the network, and an outage at the vendor no longer fails your build.

04. Quarantine policy over blanket retries

When faced with a test that fails intermittently, teams often reach for a quick fix: enabling automatic test retries in CI (such as pytest --reruns 3 from the pytest-rerunfailures plugin). Blanket test retries are risky: they can mask genuine race conditions, memory leaks, and connection pool exhaustion, sweeping real production bugs under the rug.

A quarantine policy works better:

  1. Quarantine at once. When a test exhibits intermittent failure, immediately move it to a quarantined test group or mark it with @pytest.mark.quarantine, a custom marker you register in your pytest configuration. CI runs pytest -m "not quarantine" as the gate and pytest -m quarantine separately. The quarantined group runs in CI to gather diagnostics, but its failure does not block the primary deployment gate.
  2. Give it an owner. Every quarantined test is assigned an owner and an issue ticket with a strict resolution deadline (e.g. within 48 hours).
  3. Fix the root cause. The owner diagnoses the flakiness (often shared database state, unseeded randomness, or unpinned time) and fixes the underlying defect before restoring the test to the core merge gate.

In addition to time and external networks, uncontrolled randomness is a common source of flakiness. When tests use pseudo-random data generators (such as Faker or random integers) without a fixed seed, one specific random value out of thousands may trigger an unexpected boundary condition. To make such tests deterministic, pass the code a generator with a fixed seed, such as random.Random(1337), call Faker.seed(1337) before generating data, or use sequential counters (such as itertools.count()) in your data factories. When every run uses the same inputs, rerunning the failing test reproduces the failure.

The fourth cause is shared state: a test that depends on rows, files or module variables left behind by an earlier test passes or fails depending on test order. For the database, the per-test rollback fixture from the lab already removes it: every test starts from the same empty tables. In-process state needs the same care. _tokens in app/expiry.py above is a module-level dictionary that lives for the whole pytest run, so reset it in an autouse fixture (_tokens.clear() before each test) instead of letting one test see another test's tokens. Running the suite in random order (for example with the pytest-randomly plugin) shows order dependence early.

A suite that fails only when something is wrong keeps its value as a merge gate: developers run it before they push, and a red build gets investigated instead of re-run.

05. Check your understanding

Practice check · 3 questions

Determinism and flakiness prevention

Three questions on controlling clocks, external HTTP faking, and quarantine policies.

Q1. A test like the lesson's advances the frozen clock by exactly 15 minutes instead of 16, and the 15-minute token still validates. What is the likely cause?
Q2. A respx route makes the payment API return 502 to charge_card from this lesson. What should the test assert?
Q3. A test of a feature that shuffles quiz questions fails about once in 50 runs. What makes it deterministic?
Practice only: not graded, not saved, not evidence.

06. Apply it

Review your current integration suite: replace any occurrences of time.sleep with freezegun or time-machine. Identify external third-party HTTP endpoints and wrap them with respx to test failure paths such as 502 Bad Gateway and connection timeouts. Finally, check your test suite history for intermittent failures and quarantine any flaky tests with clear remediation tickets.

07. Review prompt

Explain why blanket CI retries (--reruns) are considered an anti-pattern in production engineering teams. Describe how freezing time differs from patching time.sleep, and list three specific failure scenarios that can only be tested reliably when faking HTTP at the transport layer.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check