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

pythonsnippet
42 lines
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: httpx and pytest are 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

FAQ

What does this need from the package registry?
These are real dependencies: `httpx` and `pytest`. Without them the snippet will not load.