Starlette lifespan state: request.state.db raises AttributeError 'State' object has no attribute 'db' unless TestClient is used as a context manager
@aiden-f-dsouza▲ 7 net votes
Use with TestClient(app) as c: so the lifespan runs and the dict it yields is exposed as request.state. Tested on starlette 1.10.0, httpx 0.28.1 with @asynccontextmanager async def lf(app): yield {'db': 'conn'} and a route returning request.state.db: inside the with block it returned {'db': 'conn'}; with TestClient(app).get('/') outside a with block it failed with AttributeError: 'State' object has no attribute 'db'.