Testing Integrations: Fake Servers, Fault Injection and Contract Checks
Test code that calls an API without the real API: run a fake server that you control, inject timeouts, malformed JSON, truncated bodies and error pages, check that failures become typed errors, and verify the suite with an independent run.
In this lesson you will
- Test against a fake server you control
- Inject faults on purpose
- Map failures to typed errors
- Check responses against a contract
About 28 minutes
How do you test a payment API on Friday night?
Noor cannot test her integration against the real courier every time she changes a line: it is slow, it costs money, the provider might block her, and it never fails when you want it to. Tests of integration code use a fake: a small server that you run, which answers the way the real one is documented to, and which can be told to misbehave. With it, tests run in milliseconds, work offline, and can reproduce the bad days: the timeout, the 500 error with an HTML page instead of JSON, the body cut off in the middle, the field that is suddenly missing. Those are exactly the cases that real providers produce and that a happy-path test never covers.
Fault injection means deliberately making the fake fail in a chosen way for one test. A client should turn every failure into a small set of typed errors that the rest of the program can handle: a timeout error, a server error, a bad-response error. Without this layer, a ValueError from deep inside the JSON parser reaches the user as a crash. A contract check complements the fake: it compares a response, recorded once from the real service, against a description of the fields and types that your code relies on, and fails when the provider changes something. Run it regularly against the real service, in a separate job, and run the fast fake-based tests on every change.
| Fault | What the fake does | What the client must do |
|---|---|---|
| Timeout | Waits longer than the client’s limit | Raise TimeoutFailure |
| Server error | 500 with an HTML page | Raise ServerFailure, do not parse HTML |
| Malformed JSON | 200 with “{” only | Raise BadResponse |
| Truncated body | Cuts the reply short | Raise BadResponse |
| Missing field | 200 without “rates” | Raise BadResponse |
import json, threading, time, unittest, urllib.request, urllib.error, http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class ApiError(Exception): pass
class TimeoutFailure(ApiError): pass
class ServerFailure(ApiError): pass
class BadResponse(ApiError): pass
class RatesClient:
def __init__(self, base, timeout=0.3): self.base, self.timeout = base, timeout
def cheapest(self, grams):
try:
with urllib.request.urlopen(self.base + "/rates?weight=%d" % grams, timeout=self.timeout) as r:
raw = r.read()
except urllib.error.HTTPError as e:
raise ServerFailure("status %d" % e.code)
except (TimeoutError, urllib.error.URLError) as e:
raise TimeoutFailure(str(e))
except http.client.IncompleteRead:
raise BadResponse("truncated body")
try:
rates = json.loads(raw)["rates"]
return min(rates, key=lambda r: r["price_cents"])["service"]
except (ValueError, KeyError, TypeError):
raise BadResponse("not the documented JSON")
MODE = {"m": "ok"}
class Fake(BaseHTTPRequestHandler):
def do_GET(self):
m = MODE["m"]
if m == "timeout": time.sleep(1.0)
body = {"ok": b'{"rates": [{"service": "express", "price_cents": 1290}, {"service": "standard", "price_cents": 606}]}',
"html500": b"<html><body>Bad gateway</body></html>", "malformed": b'{"rates": [', "missing": b'{"data": []}', "timeout": b"{}", "truncated": b'{"rates": []}'}[m]
self.send_response(500 if m == "html500" else 200)
self.send_header("Content-Length", str(len(body) + (50 if m == "truncated" else 0))); self.end_headers()
try: self.wfile.write(body)
except OSError: pass
if m == "truncated": self.close_connection = True
def log_message(self, *a): pass
class T(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), Fake); threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
cls.client = RatesClient("http://127.0.0.1:%d" % cls.srv.server_address[1])
@classmethod
def tearDownClass(cls): cls.srv.shutdown()
def run_mode(self, m): MODE["m"] = m; return self.client.cheapest(1250)
def test_happy_path(self): self.assertEqual(self.run_mode("ok"), "standard")
def test_timeout(self):
with self.assertRaises(TimeoutFailure): self.run_mode("timeout")
def test_html_error_page(self):
with self.assertRaises(ServerFailure): self.run_mode("html500")
def test_malformed_json(self):
with self.assertRaises(BadResponse): self.run_mode("malformed")
def test_missing_field(self):
with self.assertRaises(BadResponse): self.run_mode("missing")
def test_truncated_body(self):
with self.assertRaises(BadResponse): self.run_mode("truncated")
def test_contract_of_recorded_response(self):
recorded = json.loads(b'{"rates": [{"service": "express", "price_cents": 1290}, {"service": "standard", "price_cents": 606}]}')
self.assertIsInstance(recorded["rates"], list)
for r in recorded["rates"]:
self.assertEqual(set(r), {"service", "price_cents"}); self.assertIsInstance(r["price_cents"], int)
import sys, unittest, io, json, re
sys.path.insert(0, sys.argv[1])
import test_rates
suite = unittest.defaultTestLoader.loadTestsFromModule(test_rates)
res = unittest.TestResult(); suite.run(res)
names = sorted(t.id().split(".")[-1] for t in suite._tests[0]) if False else None
print("ran", res.testsRun, "tests | failures:", len(res.failures), "| errors:", len(res.errors))
for f in res.failures + res.errors: print("PROBLEM:", f[0].id(), f[1].strip().splitlines()[-1])
print("DATA " + json.dumps({"run": res.testsRun, "fail": len(res.failures) + len(res.errors)}))
ran 7 tests | failures: 0 | errors: 0
The suite ran 7 tests with 0 failures. One is the happy path, which checks that the client picks the cheaper of two rates, “standard” at 606 cents. Five inject faults, and each is turned into the right typed error: when the fake sleeps longer than the client’s 0.3 second limit, the client raises TimeoutFailure and does not hang; an HTML error page with status 500 raises ServerFailure without trying to parse the HTML as JSON; a body cut off in the middle of its JSON and a body that is valid JSON but lacks the “rates” field both raise BadResponse; and a response that promises more bytes than it sends, which the client detects as an incomplete read, also raises BadResponse. The seventh test is a contract check: the recorded response must be a list whose items have exactly the fields service and price_cents, with the price as an integer.
Why is this worth the effort? Each of those five faults is something that real providers have produced, and the usual outcome in code without such tests is a stack trace in the customer’s face or, worse, a silent wrong answer: an empty list of rates read as “no delivery possible”. With typed errors, the caller can decide: retry on a timeout, show “try again later” on a server failure, and alert a developer on a bad response, which means that the provider has changed or is broken. Notice that the fake is not trying to be the real service. It reproduces only the behaviours that the client depends on, which is why it stays small. One detail cost the first draft of this lesson a failing test: the fake that sleeps for a second blocked the single-threaded server, so the next test’s request queued behind it and timed out for the wrong reason. The fix is a threaded server, which handles each request separately, and it shows that fakes need testing too.
Independent check: the same test file was run in a separate process with python -m unittest, as a continuous integration service would do, and it reported “Ran 7 tests” and exit status 0, matching the in-process run. The listing of test names confirmed that all five fault tests are present, and the number of failure types in the table of the lesson, five, equals the number of fault tests. A test suite whose coverage you can count is easier to trust than one you cannot.
Check by hand: the happy-path response has two rates, 1,290 and 606 cents, so the cheapest is the one at 606, “standard”. The fake waits one second and the client waits only 0.3, so the timeout fires first. The truncated reply claims 50 more bytes than it sends, so reading it must fail with an incomplete read.
A fake only knows what you taught it. Run contract checks against the real service regularly, and keep the recorded responses up to date, or your tests will pass while production fails.
Callers should not need to know about urllib or json exceptions. Three or four error types, with clear meanings, make the rest of the program simple and testable.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. Libraries such as responses and vcr in Python, or nock in Node.js, record and replay HTTP traffic. They apply the same ideas, so check their documentation.
Practice
Add a fault for a slow body that arrives in pieces. Add a test that the client sends the right query parameter. Write a contract test that compares a live call to the fixture and run it only when an environment variable is set.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why use a fake server in tests?
- It is the real service
- It needs no code
- It is fast, offline, and can be told to fail
- It replaces all tests
Reproduce bad days on demand.
What is fault injection?
- Fixing bugs
- Making the fake misbehave on purpose
- Adding features
- Encrypting traffic
Timeouts, bad JSON, error pages.
Why map failures to typed errors?
- It is shorter
- Callers can handle each kind sensibly
- Python requires it
- It hides errors
Retry, tell the user, alert a developer.
What does a contract check do?
- Compares a response with the fields and types you rely on
- Signs the response
- Compresses it
- Retries it
It notices provider changes.
Why run the suite in a separate process too?
- It is what CI does and confirms the result
- To slow it
- To translate it
- It is required
An independent run.
Summary
- Test with a fake server you control.
- Inject faults: timeouts, bad JSON, HTML errors, truncation, missing fields.
- Turn failures into typed errors.
- Add contract checks against recorded real responses.
Questions
Should I ever test against the real API?
Yes, in a small separate set of tests or a nightly job, with test credentials, to check that the fake still matches reality. Do not run them on every change.
How many fault tests are enough?
One for each way that the provider can fail in a way that matters to you, and each error path of your own code.
What about time in tests?
Pass the clock and the sleep function in, as lesson 4 and lesson 5 did, so that tests do not wait.
