In FastAPI, what does wrapping TestClient(app) in a with block change for an app whose lifespan loads a model, and what breaks without it?
answer
- entering and leaving the client
- lifespan startup and shutdown messages
- yielded dict copied into request.state
- one event loop for the block
basics
~10 sEntering with TestClient(app) runs the lifespan's startup, so the model loads and the yielded dict reaches request.state; leaving runs shutdown. Without the block the lifespan never runs, and reading request.state.model raises AttributeError.
solid answer
~40 sA bare `TestClient(app)` never sends the lifespan events. `__enter__` starts a blocking portal (a thread with its own event loop), runs the app's `lifespan` up to its `yield` and keeps the yielded dict; each request inside the block gets a shallow copy of it as `request.state`. `__exit__` resumes the lifespan after the `yield`, so cleanup runs too. Without the block nothing is loaded: `request.state.model` raises `AttributeError`, which the client re-raises into the test. The block also keeps one event loop for every request in it, whereas a bare client starts a fresh loop per request, so loop-bound resources made at startup stay usable. Deprecated `on_event("startup")` handlers follow the same rule.
code
python · 37 linesfrom contextlib import asynccontextmanager
import pytest
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
def load_model() -> dict:
return {"name": "sentiment", "version": 3}
@asynccontextmanager
async def lifespan(app: FastAPI):
model = load_model()
yield {"model": model}
model.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/predict")
async def predict(request: Request):
return {"model": request.state.model["name"]}
def test_predict_with_lifespan():
with TestClient(app) as client:
response = client.get("/predict")
assert response.status_code == 200
assert response.json() == {"model": "sentiment"}
def test_predict_without_lifespan():
client = TestClient(app)
with pytest.raises(AttributeError):
client.get("/predict")go deeper
Remember that only with TestClient(app) as client runs the lifespan; a bare client skips startup and shutdown entirely.
Walk through enter and exit: the portal, startup up to yield, the yielded dict copied into request.state per request, shutdown on exit, and one loop for the block.
Diagnose the failures it explains: AttributeError on request.state, startup resources missing, and different-loop errors from a bare client that starts a new loop per request.
Decide how a suite pays for startup: one lifespan run per test for isolation or a shared client fixture for speed, and what shared model state costs in test independence.
## The lifespan in one paragraph A FastAPI **lifespan** is an async context manager passed as `FastAPI(lifespan=lifespan)`. The code before its `yield` runs once at startup (load a model, open a pool), the code after it runs once at shutdown, and a dict it yields becomes **lifespan state**: each request sees a shallow copy of that dict as `request.state`, so an endpoint reads `request.state.model`. In production the server drives this through the ASGI `lifespan.startup` and `lifespan.shutdown` messages: Uvicorn's `lifespan` setting defaults to `"auto"`, so `fastapi run` sends startup before it accepts a connection and shutdown when it stops. In a test there is no server, so the client has to play that part, and `TestClient` only does so inside a `with` block. ## What the `with` block does `with TestClient(app) as client:` maps the block's edges onto the lifespan: 1. **`__enter__`** starts a **blocking portal**: a background thread running one event loop for the whole block. 2. It runs the app's lifespan on that loop and sends `lifespan.startup`. Your code runs up to `yield`; the yielded dict is stored as the client's state. 3. **Requests inside the block** run on that same loop and each gets a copy of the stored state as its `request.state`. 4. **`__exit__`** sends `lifespan.shutdown`, so the code after `yield` runs, then the loop and thread are torn down. If the lifespan raises before its `yield` (a missing model file, say), entering the block raises that exception, and the test errors before it sends a request. ## What breaks without it A bare `client = TestClient(app)` is a working client, but it never sends the lifespan messages: - **Nothing is loaded.** Startup code never runs, so the model, pool or cache does not exist. - **`request.state` is empty.** Reading `request.state.model` raises `AttributeError: 'State' object has no attribute 'model'`, and with the default `raise_server_exceptions=True` that error surfaces in the test. - **No cleanup runs**, because shutdown never runs either. - **Each request gets its own event loop.** Without a block, the client opens a fresh portal, and with it a fresh loop, for every request. An object bound to the loop of one request (an `asyncio.Event`, a driver connection) fails in the next with a different-loop `RuntimeError`. - The deprecated `@app.on_event("startup")` and `"shutdown"` handlers follow the same rule: they run only inside the block. New code uses `lifespan`. ## Bare client versus `with` block | Behaviour | `TestClient(app)` | `with TestClient(app) as client:` | |---|---|---| | Lifespan startup | never runs | runs on entry | | Lifespan shutdown | never runs | runs on exit | | `request.state` from the yielded dict | empty | populated per request | | Event loop for requests | a new one per request | one loop for the block | | A startup failure | invisible until a request fails | raised on entry | ## Sharing one lifespan run across tests Loading a large model once per test is slow, so suites usually put the block in a fixture: enter `with TestClient(app) as client:` and `yield client`, and every test that asks for the fixture shares one startup. How long that fixture lives is a choice about the test runner's fixture scopes, covered with pytest. Two FastAPI facts matter here: - The state dict is copied **shallowly** per request: rebinding `request.state.model` in one request does not leak, but mutating the model object itself does. - Because one loop serves the whole block, loop-bound resources created in the lifespan stay usable by every request in it. ## Reading a failure A test that fails with `AttributeError` on `request.state`, or finds a startup resource that is `None`, is nearly always using a bare client. Look for: - `TestClient(app)` built at module level and used outside any `with` block; - a fixture that returns the client instead of yielding it from inside the block, which exits the block, and runs shutdown, before the test starts; - a helper that builds a fresh bare client per call, which also gives every request a different event loop. The fix is the same in each case: make every request in the test happen inside one entered block, and let the lifespan create what the endpoints need.
- What happens if the lifespan raises while loading the model inside with TestClient(app)?Entering the block raises the lifespan's exception, for example the `OSError` from a missing model file, so the test errors before it sends a request. That is the behaviour you want: a startup failure is reported where it happens instead of surfacing later as an `AttributeError` on `request.state` in some endpoint.
- Can a fixture share one lifespan run across many FastAPI tests?Yes: enter `with TestClient(app) as client:` inside the fixture and `yield client`, so startup runs once for every test that uses it and shutdown runs at teardown. Returning the client instead of yielding it from inside the block exits the block first, which runs shutdown before any test sends a request.
A bare TestClient is like phoning a shop before opening time: someone answers, but nothing laid out at opening is on the shelves. The with block opens the shop before your calls and closes it after them.
- Constructing TestClient(app) runs the lifespan straight away
- The lifespan starts lazily on the client's first request
- Without the with block, request.state.model simply returns None
- Shutdown code runs after every request in the block
- on_event startup handlers run even without the with block