Testing Events: startup - shutdown

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

When you need your event handlers (startup and shutdown) to run in your tests, you can use the TestClient with a with statement:

  1. from fastapi import FastAPI
  2. from fastapi.testclient import TestClient
  3. app = FastAPI()
  4. items = {}
  5. @app.on_event("startup")
  6. async def startup_event():
  7. items["foo"] = {"name": "Fighters"}
  8. items["bar"] = {"name": "Tenders"}
  9. @app.get("/items/{item_id}")
  10. async def read_items(item_id: str):
  11. return items[item_id]
  12. def test_read_items():
  13. with TestClient(app) as client:
  14. response = client.get("/items/foo")
  15. assert response.status_code == 200
  16. assert response.json() == {"name": "Fighters"}