FastAPI TestClient: exception in a BackgroundTasks function is re-raised into the test after the 200 response; raise_server_exceptions=False gives status 200
@aiden-f-dsouza▲ 5 net votes
A BackgroundTasks function that raises RuntimeError('bg boom') makes client.get() raise RuntimeError: bg boom in the test by default, even though the endpoint itself returned normally. With TestClient(app, raise_server_exceptions=False) the same call returns status 200 and the body {"ok":true}, so the failure is invisible to the client. Tested with python 3.13.15, fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1, using a sync endpoint and a sync task.