In a FastAPI test suite, when do you switch from TestClient to httpx.AsyncClient with ASGITransport, and what must that setup add?
answer
- the test itself must await
- the transport calls the app in process
- a marker for async tests
- no default host
- startup is not the transport's job
basics
~20 sSwitch when the test must await something itself, such as an async database check. Write an async def test marked @pytest.mark.anyio, await an AsyncClient over ASGITransport(app=...) with a base_url, and run the lifespan through LifespanManager.
solid answer
~30 s`TestClient` is synchronous and runs the app on its own loop, so once a test has to `await` an async helper, it becomes an `async def` test marked `@pytest.mark.anyio` that awaits `httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://test")`. The app then runs on the test's loop. The setup must supply what `TestClient` did for you: a `base_url`, because relative paths fail without one, and the lifespan, because `ASGITransport` never runs it, so you wrap the app in asgi-lifespan's `LifespanManager` and point the transport at `manager.app` to get the yielded state. Defaults differ too: `AsyncClient` does not follow redirects, and exceptions still propagate unless `raise_app_exceptions=False`.
code
python · 42 linesfrom contextlib import asynccontextmanager
import pytest
from asgi_lifespan import LifespanManager
from fastapi import FastAPI, Request
from httpx import ASGITransport, AsyncClient
saved: list[str] = []
@asynccontextmanager
async def lifespan(app: FastAPI):
yield {"model": {"name": "sentiment"}}
app = FastAPI(lifespan=lifespan)
@app.post("/items/{name}", status_code=201)
async def create_item(name: str, request: Request):
saved.append(name)
return {"name": name, "model": request.state.model["name"]}
async def count_saved_items() -> int:
return len(saved)
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_create_item_async():
async with LifespanManager(app) as manager:
transport = ASGITransport(app=manager.app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
response = await ac.post("/items/foo")
assert response.status_code == 201
assert response.json() == {"name": "foo", "model": "sentiment"}
assert await count_saved_items() == 1go deeper
Recall the pieces of the async recipe: async def test, the anyio marker, AsyncClient with ASGITransport and a base_url, and await on each call.
Explain why the switch happens, what ASGITransport leaves out, the lifespan and its state, and how LifespanManager and manager.app put them back.
Show you can keep an async suite honest: one loop for app and test, the backend pinned where drivers need it, and defaults such as redirects made explicit.
Weigh where async tests earn their extra setup against plain TestClient tests, and keep the lifespan wiring in one shared fixture rather than in every test.
## Why `TestClient` stops fitting `TestClient` is synchronous by design: each call blocks until the app, running on the client's own event loop in a portal thread, has produced a response. That suits a plain `def` test. It stops fitting when the **test itself must `await` something**, for example checking through an async database helper that the endpoint really wrote the row. An async test needs an async client, and the app should run on the **test's own event loop**, so that anything the test and the app both touch belongs to one loop. FastAPI's answer is to use httpx directly: `httpx.AsyncClient` with **`httpx.ASGITransport`**, a transport that calls the ASGI app in process, like `TestClient`'s, but is awaited. ## The async recipe 1. Make the test `async def` and mark it **`@pytest.mark.anyio`**. The marker comes from anyio's pytest plugin, which ships with anyio; Starlette, and so every FastAPI install, already depends on anyio, so no extra package is needed. 2. Build `ASGITransport(app=app)` and open `async with AsyncClient(transport=transport, base_url="http://test") as ac:`. 3. `await ac.get(...)`, `await ac.post(..., json=...)`: the same keyword arguments as `TestClient`, awaited. 4. `await` any other async function the test needs, on the same loop the app just used. Two details trip people up. First, **`base_url` is required**: `AsyncClient` has no default host, so a relative path such as `"/items"` fails without one. Second, anyio's `anyio_backend` fixture runs a marked test on **every installed backend**; an app or driver tied to asyncio needs a `conftest.py` fixture `anyio_backend` returning `"asyncio"`. ## What `ASGITransport` does not do - **It never runs the lifespan.** FastAPI's own docs warn that `AsyncClient` will not trigger lifespan events. A model loaded at startup is simply absent. - **It does not pass lifespan state.** The scope it builds has no `state` key, so `request.state` is empty even if something else ran startup. - **It buffers the whole body.** The response is collected and handed back in one piece, so a test sees a streamed response only after it finishes. - **It starts no server**, exactly like `TestClient`: no Uvicorn options, no socket, and a default client address of `("127.0.0.1", 123)`. ## Running the lifespan with `LifespanManager` The `asgi-lifespan` package fills the gap. `async with LifespanManager(app) as manager:` sends the startup message on entry and shutdown on exit, with default startup and shutdown timeouts of five seconds. The part people miss: the yielded state is kept by the manager, and **`manager.app`** is a wrapper that injects it as each request's state. Point the transport at `ASGITransport(app=manager.app)`. Pointing it at the original `app` runs startup but still leaves `request.state.model` missing. ## `TestClient` versus `AsyncClient` | Aspect | `TestClient` | `AsyncClient` + `ASGITransport` | |---|---|---| | Test style | `def`, plain calls | `async def` with `@pytest.mark.anyio`, `await` | | Event loop of the app | its own portal loop | the test's loop | | Lifespan | run by a `with` block | run by `LifespanManager` | | Base URL | `http://testserver` by default | must be passed as `base_url` | | Redirects | followed by default | not followed by default | | Re-raise app errors | `raise_server_exceptions=True` | `raise_app_exceptions=True` | | Client address | `("testclient", 50000)` | `("127.0.0.1", 123)` | ## Failures you will meet first - **`AttributeError` on `request.state`**: the lifespan never ran, or it ran but the transport wraps `app` instead of `manager.app`. - **A relative URL error** on the first call: `base_url` is missing. - **An unexpected 307**: a path such as `"/items"` hit a route declared as `"/items/"`. `TestClient` follows that redirect silently; `AsyncClient` returns it, which is often the more honest result. - **The test hangs**: an endless streaming response, because the transport waits for the whole body before returning. ## Choosing - Keep `TestClient` for the bulk of HTTP tests: they are shorter, synchronous and run the lifespan with one `with`. - Switch a test to `AsyncClient` when it must `await` the app's async resources in the same test, or when a shared async resource has to live on the test's loop. - Do not mix the two inside one async test: calling `TestClient` from an `async def` test blocks the test's loop and runs the app on a different one.
- Why must ASGITransport wrap manager.app rather than the FastAPI app itself?`LifespanManager` keeps the dict the lifespan yields in its own state, and `manager.app` is a small wrapper that sets it as each request's `scope["state"]`. `ASGITransport` builds a scope with no state key, so over the original `app` the startup code runs but `request.state` stays empty and reading the model raises `AttributeError`.
- Does @pytest.mark.anyio run a FastAPI test on asyncio only?Not by itself: anyio's `anyio_backend` fixture is parametrized over every installed backend, so with a second backend installed each marked test also runs there. An app or database driver that only works on asyncio needs a `conftest.py` fixture named `anyio_backend` that returns `"asyncio"`.
- ASGITransport runs the lifespan before the first request
- AsyncClient defaults to http://testserver just like TestClient
- TestClient calls can simply be awaited in an async def test
- LifespanManager(app) alone makes request.state work over the original app
- AsyncClient follows redirects by default, the same as TestClient