Test that startup/shutdown handlers passed as parameters to FastAPI are called correctly.
(state: State)
| 319 | |
| 320 | |
| 321 | def test_startup_shutdown_handlers_as_parameters(state: State) -> None: |
| 322 | """Test that startup/shutdown handlers passed as parameters to FastAPI are called correctly.""" |
| 323 | |
| 324 | def app_startup() -> None: |
| 325 | state.app_startup = True |
| 326 | |
| 327 | def app_shutdown() -> None: |
| 328 | state.app_shutdown = True |
| 329 | |
| 330 | app = FastAPI(on_startup=[app_startup], on_shutdown=[app_shutdown]) |
| 331 | |
| 332 | @app.get("/") |
| 333 | def main() -> dict[str, str]: |
| 334 | return {"message": "Hello World"} |
| 335 | |
| 336 | def router_startup() -> None: |
| 337 | state.router_startup = True |
| 338 | |
| 339 | def router_shutdown() -> None: |
| 340 | state.router_shutdown = True |
| 341 | |
| 342 | router = APIRouter(on_startup=[router_startup], on_shutdown=[router_shutdown]) |
| 343 | |
| 344 | def sub_router_startup() -> None: |
| 345 | state.sub_router_startup = True |
| 346 | |
| 347 | def sub_router_shutdown() -> None: |
| 348 | state.sub_router_shutdown = True |
| 349 | |
| 350 | sub_router = APIRouter( |
| 351 | on_startup=[sub_router_startup], on_shutdown=[sub_router_shutdown] |
| 352 | ) |
| 353 | |
| 354 | router.include_router(sub_router) |
| 355 | app.include_router(router) |
| 356 | |
| 357 | assert state.app_startup is False |
| 358 | assert state.router_startup is False |
| 359 | assert state.sub_router_startup is False |
| 360 | assert state.app_shutdown is False |
| 361 | assert state.router_shutdown is False |
| 362 | assert state.sub_router_shutdown is False |
| 363 | with TestClient(app) as client: |
| 364 | assert state.app_startup is True |
| 365 | assert state.router_startup is True |
| 366 | assert state.sub_router_startup is True |
| 367 | assert state.app_shutdown is False |
| 368 | assert state.router_shutdown is False |
| 369 | assert state.sub_router_shutdown is False |
| 370 | response = client.get("/") |
| 371 | assert response.status_code == 200, response.text |
| 372 | assert response.json() == {"message": "Hello World"} |
| 373 | assert state.app_startup is True |
| 374 | assert state.router_startup is True |
| 375 | assert state.sub_router_startup is True |
| 376 | assert state.app_shutdown is True |
| 377 | assert state.router_shutdown is True |
| 378 | assert state.sub_router_shutdown is True |
nothing calls this directly
no test coverage detected
searching dependent graphs…