HTTPX Mock Transport Unit Test
Test HTTP clients without a network by swapping in httpx MockTransport, scripting responses per URL and asserting request payloads.
Code
import httpx
import pytest
def fetch_invoice(base_url: str, invoice_id: str) -> dict:
with httpx.Client(base_url=base_url) as client:
resp = client.get(f'/invoices/{invoice_id}')
resp.raise_for_status()
return resp.json()
def test_fetch_invoice_parses_payload():
captured: dict = {}
def handler(request: httpx.Request) -> httpx.Response:
captured['url'] = str(request.url)
captured['auth'] = request.headers.get('Authorization')
return httpx.Response(200, json={'id': 'inv-1', 'total': 4200})
client = httpx.Client(
transport=httpx.MockTransport(handler),
base_url='https://api.example.test',
headers={'Authorization': 'Bearer test-token'},
)
with client:
resp = client.get('/invoices/inv-1')
data = resp.json()
assert data['total'] == 4200
assert captured['url'].endswith('/invoices/inv-1')
assert captured['auth'] == 'Bearer test-token'
@pytest.mark.parametrize('status', [500, 502, 503])
def test_fetch_invoice_raises_on_server_error(status):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(status)
client = httpx.Client(transport=httpx.MockTransport(handler))
with pytest.raises(httpx.HTTPStatusError):
client.get('https://api.example.test/invoices/inv-2')What the code does
The working surface is the functions fetch_invoice, test_fetch_invoice_parses_payload, handler and test_fetch_invoice_raises_on_server_error — everything else is wiring.
What to watch for
- Plan for an install step:
httpxandpytestare a real dependency, resolved by the package manager.
Applying it
The main signature reads def fetch_invoice(base_url: str, invoice_id: str) -> dict
fetch_invoice is the public entry point; everything else in the file exists to support it.
Statements that matter
def fetch_invoice(base_url: str, invoice_id: str) -> dict:
with httpx.Client(base_url=base_url) as client:
resp = client.get(f'/invoices/{invoice_id}')
resp.raise_for_status()
return resp.json()
def handler(request: httpx.Request) -> httpx.Response:
captured['url'] = str(request.url)
captured['auth'] = request.headers.get('Authorization')
return httpx.Response(200, json={'id': 'inv-1', 'total': 4200})
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(status)
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- What does this need from the package registry?
- These are real dependencies: `httpx` and `pytest`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.