Sub topic 16
Testing Failure Paths with Simulated Errors
Retry code is hard to trust because it only runs when something goes wrong. If you test it only against the real API, the failure branches may not run until an outage. This chapter shows how to trigger those branches on demand, without network access and without waiting for real delays.
This chapter assumes you can read the retry loop from the earlier chapters and have used pytest. It also assumes you know what httpx is and what the CircuitBreaker class does. Save the retry function as llm_retry.py and the circuit breaker as breaker.py. The tests below import from those two modules.
What to test and what to fake
A failure-handling test has three parts: a script of failures, a way to skip real waiting, and assertions about behavior. The behaviors worth asserting are these:
- How many requests were sent.
- Which delays were requested.
- Which exception reached the caller.
You fake three things:
- The server. It returns a scripted sequence of responses or exceptions.
- The clock.
time.sleepandtime.monotonicare replaced so tests run in milliseconds. - The randomness. Jitter is pinned to a known value, or you assert on bounds instead of exact values.
Faking the server with a mock transport
httpx.MockTransport takes a function that receives each request and returns an httpx.Response. It can also raise an exception, which is how you simulate a dropped connection. A client built on this transport behaves like a real one, including raise_for_status(), but never touches the network.
The helper below takes a script and returns a client plus a list that records every request. Each script item is either an exception to raise or a (status, headers) tuple.
import httpx
import pytest
import llm_retry
from llm_retry import post_with_retries
def make_client(script):
"""Return a client that follows `script`, one item per request, and a call log."""
calls = []
items = iter(script)
def handler(request):
calls.append(request)
item = next(items) # StopIteration here means the code made an unexpected extra call
if isinstance(item, Exception):
raise item
status, headers = item
return httpx.Response(status, headers=headers, json={"ok": status < 400})
return httpx.Client(transport=httpx.MockTransport(handler)), callsThe next(items) call does a useful job. If your code sends more requests than the script allows, the test fails instead of looping.
Faking the clock and the jitter
Two fixtures replace time.sleep with a function that records its argument and random.uniform with a function that returns the upper bound. Delays then equal the exponential ceiling, so you can compare them exactly.
@pytest.fixture
def sleeps(monkeypatch):
recorded = []
monkeypatch.setattr(llm_retry.time, "sleep", recorded.append)
return recorded
@pytest.fixture
def no_jitter(monkeypatch):
monkeypatch.setattr(llm_retry.random, "uniform", lambda low, high: high)monkeypatch undoes each change when the test ends. Because llm_retry.time is the shared time module, the patch is process-wide while the test runs. That is fine for these tests, but keep the patched region small.
Testing the retry loop
Each test below scripts one situation. The expected delays come from the loop's settings: base=0.5, so the ceilings are 0.5, 1.0, 2.0, and so on, with cap=30.0.
URL = "https://api.example.test/v1/chat"
def test_retries_server_errors_then_succeeds(sleeps, no_jitter):
client, calls = make_client([(503, {}), (503, {}), (200, {})])
resp = post_with_retries(client, URL, {"q": "hi"})
assert resp.status_code == 200
assert len(calls) == 3
assert sleeps == [0.5, 1.0]
@pytest.mark.parametrize("status", [400, 401, 404])
def test_permanent_errors_are_not_retried(status, sleeps):
client, calls = make_client([(status, {})])
with pytest.raises(httpx.HTTPStatusError):
post_with_retries(client, URL, {"q": "hi"})
assert len(calls) == 1
assert sleeps == []
def test_retry_after_lengthens_the_wait(sleeps, no_jitter):
client, calls = make_client([(429, {"retry-after": "7"}), (200, {})])
post_with_retries(client, URL, {"q": "hi"})
assert sleeps == [7.0]
def test_gives_up_after_max_attempts(sleeps, no_jitter):
client, calls = make_client([(503, {})] * 5)
with pytest.raises(httpx.HTTPStatusError):
post_with_retries(client, URL, {"q": "hi"}, max_attempts=5)
assert len(calls) == 5
assert len(sleeps) == 4 # no sleep after the final failed attempt
def test_network_error_is_retried(sleeps):
client, calls = make_client([httpx.ConnectError("refused"), (200, {})])
resp = post_with_retries(client, URL, {"q": "hi"})
assert resp.status_code == 200
assert len(calls) == 2
assert len(sleeps) == 1
def test_jitter_stays_within_the_ceiling(sleeps):
client, _ = make_client([(503, {})] * 4 + [(200, {})])
post_with_retries(client, URL, {"q": "hi"})
for i, delay in enumerate(sleeps):
assert 0 <= delay <= min(30.0, 0.5 * 2 ** i)The last test uses real randomness and checks bounds. Use this approach when a value is random by design. An exact-value test on random output is either flaky or tests nothing.
Testing the circuit breaker with a fake clock
The breaker depends on time.monotonic. Replace it with a function that reads a variable you control, and you can move time forward in a single line.
import breaker
from breaker import CircuitBreaker
def test_breaker_opens_then_probes_after_cooldown(monkeypatch):
now = [1000.0]
monkeypatch.setattr(breaker.time, "monotonic", lambda: now[0])
cb = CircuitBreaker(failure_threshold=3, reset_after=30.0)
for _ in range(3):
cb.record_failure()
assert not cb.allow() # open: calls are blocked
now[0] += 29
assert not cb.allow() # still cooling down
now[0] += 1
assert cb.allow() # cool-down over: one probe is allowed
cb.record_success()
assert cb.failures == 0 and cb.allow()The test checks the boundary on both sides: one second too early and exactly on time. Off-by-one mistakes in timing code usually sit at that boundary.
Testing streaming failures
A stream can fail after some chunks were already delivered. A generator that yields a few chunks and then raises reproduces this without any server.
def flaky_stream():
yield "Hello"
yield ", wor"
raise httpx.ReadError("connection reset")
def collect(stream):
"""Return (text received so far, error or None)."""
parts = []
try:
for chunk in stream:
parts.append(chunk)
except httpx.TransportError as exc:
return "".join(parts), exc
return "".join(parts), None
def test_partial_text_is_kept_when_the_stream_breaks():
text, error = collect(flaky_stream())
assert text == "Hello, wor"
assert isinstance(error, httpx.ReadError)This test pins down a design decision: the caller receives the partial text and the error together. What your application does next, whether it resumes, restarts, or shows the partial text, is a separate decision, and this test only proves the information is available to make it.
Choosing the right simulation
| Failure to simulate | How | What to assert |
|---|---|---|
| Temporary server error | Script `(503, {})` entries | Call count, recorded delays |
| Permanent client error | Script `(400, {})` | One call, no sleep, exception raised |
| Rate limit with a wait hint | `(429, {"retry-after": "7"})` | Delay is at least 7 seconds |
| Dropped connection | Raise `httpx.ConnectError` in the handler | Retried, then success or re-raise |
| Timeout | Raise `httpx.ReadTimeout` in the handler | Same as other transport errors |
| Sustained outage | Many consecutive failures | Breaker opens, fallback is used |
| Broken stream | Generator that raises mid-way | Partial text preserved |
If you use a provider SDK instead of your own loop, most SDKs accept a custom httpx client, so you can pass in a mock transport and test your configured max_retries. SDK retries sleep for real by default, so keep max_retries small in those tests or they will be slow.
Common mistakes in failure tests
- Asserting on the final result only. A loop that retries ten times and one that retries twice both end in success. Assert on call count and delays too.
- Forgetting to test the give-up path. The case where every attempt fails is the one that decides whether your app hangs or reports an error.
- Real sleeps in tests. A suite that waits through backoff delays gets slow, and people stop running it.
- Mocking so deeply that nothing is tested. If you replace the retry function itself, you test your mock. Fake the transport and the clock, and leave the retry logic real.
Exercise
Write a test for the retry loop where the server returns 500 on the first attempt and 429 with retry-after: 3 on the second, then 200. With jitter disabled and base=0.5, what list of sleeps should the test assert, and why?
Show answer
The test should assert sleeps == [0.5, 3.0]. After attempt 1 the ceiling is 0.5 and there is no Retry-After header, so the delay is 0.5. After attempt 2 the exponential ceiling is 1.0, but the header asks for 3 seconds, and the loop takes max(1.0, min(3.0, 30.0)), which is 3.0. The test should also assert that three requests were made.
Exercise
A teammate's test for the give-up path scripts five 503 responses and passes max_attempts=5, but asserts len(sleeps) == 5. The test fails. Is the test or the code wrong?
Show answer
The test is wrong. The loop sleeps only between attempts. After the fifth failed attempt it raises instead of sleeping, so there are four sleeps. The correct assertion is len(sleeps) == 4.