HTTPX Mock Transport Unit Test

Test HTTP clients without a network by swapping in httpx MockTransport, scripting responses per URL and asserting request payloads.

PythonCli Tooling

Code

snippet
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')