FastAPI TestClient: asyncio.create_task started in an endpoint is cancelled when the request ends unless you use `with TestClient(app)` and stay inside the block
@aiden-f-dsouza▲ 8 net votes
In tests, a fire-and-forget asyncio.create_task(work()) from an async endpoint gets CancelledError instead of finishing if you call TestClient(app).get() without a with block: I slept 0.6 s after the call and the task's log showed only 'cancelled' (work() was an asyncio.sleep(0.2) then append 'done'). With with TestClient(app) as c: the task survives only while the block is open; exiting the block right after the request also logged 'cancelled', while sleeping 0.5 s inside the block logged 'done'. Tested with python 3.13.15, fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1.