Sub topic 16
Testing failure paths with simulated errors
Retry code runs only when something goes wrong, so it often ships untested. This chapter shows how to test it without a real provider. It assumes you can write pytest tests and that you have the post_with_retries function from the earlier chapters saved as retry_client.py.
Why not test against the real API?
You can't make a real provider return a 503 on demand. Real calls are also slow, cost money, and give different results each run. A simulated transport returns exactly the failure you choose, instantly and for free.
What to simulate
Each row is one failure path. The last column is what the test should check.
| Failure | Simulate with | Assert |
|---|---|---|
| Temporary server error | 503, then 200 | The call succeeds after retries |
| Permanent client error | 400 | One attempt, error raised |
| Rate limit with header | 429 and `retry-after: 4` | Wait is at least 4 seconds |
| Network failure | `httpx.ConnectError` | The call is retried |
| Sustained outage | 503 on every attempt | Stops at `max_attempts` |
A fake transport
httpx.MockTransport lets you replace the network with a function. The helper below feeds a scripted list of responses or exceptions to the client, one per request, and records each request.
Two details matter:
- Patch
time.sleepso tests don't wait. The patched function records each delay, so you can also check what the code would have waited. - Never let a test sleep for real. A suite that waits through backoff delays quickly becomes too slow to run.
import httpx
import pytest
import retry_client
from retry_client import post_with_retries
@pytest.fixture
def delays(monkeypatch):
recorded = []
monkeypatch.setattr(retry_client.time, "sleep", recorded.append)
return recorded
def make_client(script):
"""Return a client that replays `script` and a list of the requests it saw."""
items = iter(script)
calls = []
def handler(request):
calls.append(request)
item = next(items)
if isinstance(item, Exception):
raise item
return item
return httpx.Client(transport=httpx.MockTransport(handler)), calls
URL = "https://api.example.com/v1/chat"
def test_retries_server_errors_then_succeeds(delays):
client, calls = make_client(
[httpx.Response(503), httpx.Response(503), httpx.Response(200, json={"ok": True})]
)
resp = post_with_retries(client, URL, {"q": "hi"})
assert resp.status_code == 200
assert len(calls) == 3
assert len(delays) == 2
def test_client_error_is_not_retried(delays):
client, calls = make_client([httpx.Response(400)])
with pytest.raises(httpx.HTTPStatusError):
post_with_retries(client, URL, {"q": "hi"})
assert len(calls) == 1
assert delays == []
def test_retry_after_lengthens_the_wait(delays):
client, _ = make_client(
[httpx.Response(429, headers={"retry-after": "4"}), httpx.Response(200)]
)
post_with_retries(client, URL, {"q": "hi"})
assert delays[0] >= 4
def test_network_error_is_retried(delays):
client, calls = make_client([httpx.ConnectError("connection refused"), httpx.Response(200)])
assert post_with_retries(client, URL, {"q": "hi"}).status_code == 200
assert len(calls) == 2
def test_gives_up_after_max_attempts(delays):
client, calls = make_client([httpx.Response(503)] * 3)
with pytest.raises(httpx.HTTPStatusError):
post_with_retries(client, URL, {"q": "hi"}, max_attempts=3)
assert len(calls) == 3
assert len(delays) == 2Making the tests stable
Jitter makes delays random, so assert on bounds rather than exact values. For example, check that a delay is at most min(cap, base * 2 ** (attempt - 1)). You can also seed random with random.seed(0) or patch random.uniform when you need exact numbers.
Test the circuit breaker the same way. Call record_failure() five times and assert that allow() returns False. Then patch time.monotonic to jump past reset_after and assert that allow() returns True again.
Beyond unit tests
Unit tests with fakes check your logic. They don't check that your assumptions about the provider are right. Occasionally compare your fakes against real error responses captured from logs. Check the status codes, the header names, and the shape of the error body.
Exercise
Your test for a 429 response with retry-after: 4 passes, but the test suite now takes 4 seconds longer. What did you forget, and how do you check the wait without sleeping?
Show answer
You forgot to patch time.sleep, so the code really waited. Replace it with a function that records its argument, such as recorded.append, then assert on the recorded value (for example delays[0] >= 4).