MockTransport: a server you write as a function
A client sends requests and hands you the responses. Before calling a real server, give the client a function to call instead, so you can see exactly what it sends.
import httpx2
def fake_server(request):
print("server got:", request.method, request.url.path)
return httpx2.Response(200, json={"id": 2, "customer": "Ben"})
client = httpx2.Client(transport=httpx2.MockTransport(fake_server), base_url="https://api.example.com")
response = client.get("/tickets/2")
print(response.status_code, response.json())httpx2.Client is the object that sends requests. A transport is the part that actually delivers them; normally that is the network. MockTransport delivers each request to your function and returns whatever response the function makes.
base_url is put in front of every path, so client.get("/tickets/2") asks for https://api.example.com/tickets/2. Nothing left your computer.
A fake server that decides
TICKETS = {1: "I was charged twice for one order", 2: "My parcel has not arrived"}
def fake_server(request):
ticket_id = int(request.url.path.split("/")[-1])
if ticket_id not in TICKETS:
return httpx2.Response(404, json={"detail": "ticket not found"})
return httpx2.Response(200, json={"id": ticket_id, "text": TICKETS[ticket_id]})
client = httpx2.Client(transport=httpx2.MockTransport(fake_server), base_url="https://api.example.com")
for ticket_id in (1, 9):
response = client.get(f"/tickets/{ticket_id}")
print(response.status_code, response.json())request.url.path.split("/") cuts /tickets/9 at each slash, and [-1] takes the last piece, the id. The same client code gets a 200 for one ticket and a 404 for the other.
Why this matters: code that calls a paid model API is code you want to test without paying. A mock transport lets a test decide exactly what the API answers, including the errors that are hard to cause on purpose. Lesson 12 uses it for exactly that.
- Make
fake_serverreturn 500 for ticket 1 and run the loop. - Print
request.headersinsidefake_server, then passheaders={"X-Team": "support"}toclient.get. - Call
client.post("/tickets", json={"text": "hi"})and printrequest.contentin the server.
Slow is fine. Stopping is the only problem.