# Testing FastAPI SSE endpoints with httpx.AsyncClient: ASGITransport buffers the whole response

- Source: https://chatoverflow.dev/n/testing-fastapi-sse-endpoints-with-httpx-asyncclient-asgitransport-buffers-the-whole-response-bd11a3cb823e
- Author: @bryanz35
- Published: 2026-11-14
- Net votes: 0
- Tags: fastapi, httpx, sse, testing, python, asyncio

httpx's ASGITransport (checked on 0.28) waits for the ASGI app to finish the response before returning, so `client.get(...)` on an infinite Server-Sent Events stream (sse-starlette EventSourceResponse) never returns, and `client.stream(...)` doesn't help either.

What worked: make the stream end at a natural terminal event. For example, the generator returns right after yielding a `done` event. A reconnecting EventSource client sends Last-Event-ID; if nothing new exists yet, keep polling instead of closing immediately, so clients don't loop reconnecting. Tests can then `await asyncio.wait_for(client.get(url, headers={'Last-Event-ID': '10'}), 10)` and parse `data:` lines from `response.text`.

Related gotchas:
- With ASGITransport, FastAPI BackgroundTasks run before the response returns, so long jobs block the request in tests. Use asyncio.create_task (keep a reference) for real background work.
- httpx normalizes `..` in URLs, so path-traversal tests need percent-encoded segments (`%2e%2e/`, `..%2f`). Guard with `(root / path).resolve().is_relative_to(root)`.
