Stream response bodies in `ASGITransport`
ASGITransport now streams response bodies. Inside async with, the app runs in a task group owned by the transport, and the response is returned as soon as the app sends http.response.start. This makes it possible to test SSE and other endpoints that never finish.
transport = httpx2.ASGITransport(app=app)
async with httpx2.AsyncClient(transport=transport, base_url="http://testserver") as client:
async with client.stream("GET", "/events") as response:
async for line in response.aiter_lines():
...
The task group lives for the lifetime of the transport rather than inside an async generator per request. A task group held across yield breaks when a response isn't closed in the same task. On main, TestASGIWebSocketTransport::test_http fails that way on asyncio and on trio.
- Closing the response sends
http.disconnectto the app. Apps still running when the transport exits are cancelled. - Without
async with, the app runs to completion before the response is returned, as before. - An exception raised before
http.response.startis raised from the request. One raised after it is raised while reading the body, soclient.get()still raises it. ASGIWebSocketTransportreuses the base task group instead of managing its own.- An app that returns without completing its response raises
RuntimeErrorinstead of producing a truncated or synthetic500response.
Behaviour changes:
- Inside
async with, context variables set by the app are no longer visible to the caller. - A streaming response from
handle_async_requestthat is never closed is reported byanyiowith aResourceWarningonce it is garbage collected.
Depends on #1270, which makes AsyncClient unwind transports in reverse order, so several transports with task groups can be mounted together. This PR targets that branch until it merges.
Supersedes #1032 and #1171. Addresses the long-standing upstream request encode/httpx#2186.
AI Disclaimer
This PR was developed with the assistance of either Claude or Codex. I've reviewed and verified the changes.