Inject an HTTP Transport for Testable Clients
Core idea
Separate application logic from transport, the component that sends a request and receives a response. Define a narrow callable contract and inject a fake in tests. Here transport(path) returns a status and bounded body bytes; the client decides whether to parse the response. A real adapter would also manage timeouts, TLS, redirects and closing.
import jsondef quantity(transport, path): status, body = transport(path) if status != 200: raise ValueError('unexpected status') return json.loads(body)['qty']def fake(path): print(path) return 200, b'{"qty":7}'print(quantity(fake, '/items/A'))The client parses a successful response without knowing how bytes were obtained.
Check failure handling
def fetch_label(transport): status, body = transport('/label') if status == 404: return None if status != 200: raise ValueError('unexpected status') return body.decode('utf-8')print(fetch_label(lambda path:(404, b'not found')))print(fetch_label(lambda path:(200, b'blue')))A missing label and a valid label have distinct outcomes.
Common mistake
A fake only checks the contract you model; it does not verify wire protocol or TLS. Add integration tests for the real adapter and validate parsed field types and shapes.
Practice
Add a fake returning malformed JSON and another returning status 503; verify distinct failure behavior without contacting a server.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP client abstraction
Check your understanding of http client abstraction.
What is printed?
def use(send): return send('/x')[0]print(use(lambda p:(201,b'')))What is printed?
calls=[]def fake(path): calls.append(path) return 200,b''fake('/stock')print(calls)Why inject a transport?
What remains to test with a real adapter?