Inspect a client request with MockTransport
A client can be tested without contacting the service it normally uses. MockTransport passes each HTTPX request to a handler that returns an HTTPX response. The handler can inspect the URL, query parameters, headers and body.
Inject the transport at the client's boundary rather than patching a low-level socket. This preserves HTTPX's request construction and response decoding while replacing only delivery. Close the client with a context manager. The example uses a reserved demonstration hostname and never attempts a network connection, so it runs offline in the app and browser.
import httpx
def handler(request):
return httpx.Response(200, json={
"q": request.url.params["q"]})
with httpx.Client(transport=
httpx.MockTransport(handler)) as client:
print(client.get("https://demo.test/",
params={"q": "green tea"}).json())Your task
Implement fetch_name(user_id,transport). Create a client with base_url https://demo.test, GET /users/{user_id}, raise for a bad status, and return the JSON name. Use the supplied transport and close the client.
The explanation opens here once every check passes.