Sub topic 11
Testing Fallbacks with Fault Injection
This chapter assumes you have read the earlier chapters on timeouts, retries, circuit breakers, and fallback strategies. You should be comfortable writing Python tests with plain assert statements.
A fallback that has never run is a guess. Fallback code is only exercised when something breaks, so bugs in it stay hidden until the worst moment. Fault injection fixes this by causing the failure on purpose, in a controlled setting, and checking what the service does.
What to Inject
Each failure mode from the start of this tutorial maps to a fault you can inject.
| Failure mode | Fault to inject | What the test should confirm |
|---|---|---|
| Error | Raise `ConnectionError` | The fallback runs and the response is flagged as degraded |
| Slowness | Delay longer than the timeout | The call ends at the timeout, not after the full delay |
| Partial outage | Fail some calls and succeed on others | Successful calls are not marked degraded |
| Prolonged outage | Fail every call | The circuit breaker opens and stops calling the dependency |
| Recovery | Fail, then succeed | The service returns to normal behavior |
A Fake Dependency You Can Control
The simplest injection point is the dependency itself. Pass a fake in place of the real client, and make the fake fail on command. The get_recommendations function from the fallback chapter already takes fetch as an argument, so this works without changing it.
class FaultyDependency:
"""A stand-in for a real client that fails in scripted ways."""
def __init__(self, outcomes):
# outcomes is a list: each item is a result or an exception to raise.
self.outcomes = list(outcomes)
self.calls = 0
def __call__(self, user_id, timeout=None):
self.calls += 1
outcome = self.outcomes.pop(0)
if isinstance(outcome, Exception):
raise outcome
return outcomeThe calls counter matters. It lets a test prove that the breaker stopped calling the dependency, which you cannot see from the response alone.
Testing the Fallback Paths
The tests below cover the three paths of get_recommendations: healthy, cached fallback, and default fallback. Each test checks the degraded flag as well as the data, because a fallback that hides itself is a bug.
import time
_cache = {}
def get_recommendations(user_id, fetch, timeout=0.5):
try:
items = fetch(user_id, timeout=timeout)
_cache[user_id] = (items, time.monotonic())
return {"items": items, "degraded": False}
except (TimeoutError, ConnectionError):
if user_id in _cache:
items, _ = _cache[user_id]
return {"items": items, "degraded": True, "source": "cache"}
return {"items": [], "degraded": True, "source": "default"}
class FaultyDependency:
def __init__(self, outcomes):
self.outcomes = list(outcomes)
self.calls = 0
def __call__(self, user_id, timeout=None):
self.calls += 1
outcome = self.outcomes.pop(0)
if isinstance(outcome, Exception):
raise outcome
return outcome
def test_healthy_call_is_not_degraded():
_cache.clear()
dep = FaultyDependency([["a", "b"]])
result = get_recommendations("u1", dep)
assert result == {"items": ["a", "b"], "degraded": False}
def test_failure_serves_cache_and_flags_it():
_cache.clear()
dep = FaultyDependency([["a", "b"], ConnectionError()])
get_recommendations("u1", dep)
result = get_recommendations("u1", dep)
assert result["items"] == ["a", "b"]
assert result["degraded"] is True
assert result["source"] == "cache"
def test_failure_with_cold_cache_returns_default():
_cache.clear()
dep = FaultyDependency([TimeoutError()])
result = get_recommendations("u2", dep)
assert result == {"items": [], "degraded": True, "source": "default"}
if __name__ == "__main__":
test_healthy_call_is_not_degraded()
test_failure_serves_cache_and_flags_it()
test_failure_with_cold_cache_returns_default()
print("all fallback tests passed")Note the _cache.clear() at the start of each test. Module-level state leaks between tests, and a leaked cache entry would make the cold-cache test pass or fail for the wrong reason.
Testing the Circuit Breaker
For the breaker, assert on the number of calls that reach the dependency. After max_failures failures, further calls must not reach it.
import time
class CircuitBreaker:
def __init__(self, max_failures=3, reset_after=30.0):
self.max_failures = max_failures
self.reset_after = reset_after
self.failures = 0
self.opened_at = None
def call(self, fn, fallback):
if self.opened_at is not None:
if time.monotonic() - self.opened_at < self.reset_after:
return fallback()
try:
result = fn()
except Exception:
self.failures += 1
if self.failures >= self.max_failures:
self.opened_at = time.monotonic()
return fallback()
self.failures = 0
self.opened_at = None
return result
def test_breaker_opens_and_stops_calling():
calls = {"n": 0}
def broken():
calls["n"] += 1
raise ConnectionError()
breaker = CircuitBreaker(max_failures=3, reset_after=30.0)
for _ in range(10):
assert breaker.call(broken, lambda: "fallback") == "fallback"
assert calls["n"] == 3
def test_breaker_recovers_after_cool_down():
state = {"healthy": False}
def dependency():
if not state["healthy"]:
raise ConnectionError()
return "ok"
breaker = CircuitBreaker(max_failures=1, reset_after=0.05)
assert breaker.call(dependency, lambda: "fallback") == "fallback"
state["healthy"] = True
assert breaker.call(dependency, lambda: "fallback") == "fallback"
time.sleep(0.06)
assert breaker.call(dependency, lambda: "fallback") == "ok"
if __name__ == "__main__":
test_breaker_opens_and_stops_calling()
test_breaker_recovers_after_cool_down()
print("breaker tests passed")The recovery test uses a short reset_after so it runs quickly. It checks that the breaker stays open during the cool-down even though the dependency is healthy again, and that it closes after the trial call succeeds.
Beyond Unit Tests
Unit tests with fakes prove the logic. They do not prove the wiring. Two further levels are worth adding.
- Integration tests with a fault proxy. Run the real client against a proxy that can add latency or drop connections. This catches a timeout that was configured on the wrong layer.
- Game days in a staging environment. Turn off a real dependency and watch dashboards. This checks that the degraded-state metrics and alerts from the previous chapter fire, not only that the code returns the right value.
Inject faults in production only after the same experiments pass in staging, and keep the blast radius small, for example a single instance or a small share of traffic.
Common Mistakes
- Mocking the function that contains the fallback instead of the dependency beneath it. The fallback code never runs.
- Testing only the first failure. Many bugs appear on the third call, when the breaker opens, or after recovery.
- Using real sleeps of several seconds. Shorten timeouts and cool-downs through parameters so the suite stays fast.
- Forgetting to reset shared state such as caches and breaker counters between tests.
Exercise
A test injects a ConnectionError into a dependency wrapped by a circuit breaker with max_failures=3, then makes five calls. The test asserts that every response equals the fallback value, and it passes. Which additional assertion would show that the breaker is working, and why is the first assertion not enough?
Show answer
Assert that the dependency was called exactly three times, using a call counter on the fake. Every response equals the fallback value even if there is no breaker at all, because each failed call returns the fallback on its own. Only the call count shows that the last two calls were stopped before reaching the dependency.
Exercise
Write the outcomes list you would pass to FaultyDependency to test recovery of get_recommendations after an outage. Assume the cache is empty at the start, and state what each of the four calls should return.
Show answer
Use [["a"], ConnectionError(), TimeoutError(), ["b"]]. Call 1 returns {"items": ["a"], "degraded": False}. Call 2 returns the cached ["a"] with degraded True and source "cache". Call 3 does the same. Call 4 returns {"items": ["b"], "degraded": False}, which confirms the service left the degraded state once the dependency recovered.