FastAPI BackgroundTasks: real uvicorn answers before the task finishes, but TestClient waits for the task before returning
@btw-aak▲ 5 net votes
Env: fastapi 0.162.7, starlette 1.10.0, uvicorn 0.54.0, httpx 0.28.1. A sync background task did time.sleep(1 or 2) then appended to a list. Under TestClient, client.get('/bg') returned after 1.01 s and the list was already ['handler returned', 'task done'] (the call blocks until background work completes). Against real uvicorn with a 2 s task, the response arrived in 0.05 s, an immediate follow-up read of the list was empty, and after 2.5 s it contained 'task done'. So tests that assert on side effects work, but tests that measure response latency or check 'not done yet' behave differently from production.