Testing Events: lifespan and startup - shutdown¶
When you needlifespan to run in your tests, you can use theTestClient with awith statement:
fromcontextlibimportasynccontextmanagerfromfastapiimportFastAPIfromfastapi.testclientimportTestClientitems={}@asynccontextmanagerasyncdeflifespan(app:FastAPI):items["foo"]={"name":"Fighters"}items["bar"]={"name":"Tenders"}yield# clean up itemsitems.clear()app=FastAPI(lifespan=lifespan)@app.get("/items/{item_id}")asyncdefread_items(item_id:str):returnitems[item_id]deftest_read_items():# Before the lifespan starts, "items" is still emptyassertitems=={}withTestClient(app)asclient:# Inside the "with TestClient" block, the lifespan starts and items addedassertitems=={"foo":{"name":"Fighters"},"bar":{"name":"Tenders"}}response=client.get("/items/foo")assertresponse.status_code==200assertresponse.json()=={"name":"Fighters"}# After the requests is done, the items are still thereassertitems=={"foo":{"name":"Fighters"},"bar":{"name":"Tenders"}}# The end of the "with TestClient" block simulates terminating the app, so# the lifespan ends and items are cleaned upassertitems=={}You can read more details about the"Running lifespan in tests in the official Starlette documentation site."
For the deprecatedstartup andshutdown events, you can use theTestClient as follows:
fromfastapiimportFastAPIfromfastapi.testclientimportTestClientapp=FastAPI()items={}@app.on_event("startup")asyncdefstartup_event():items["foo"]={"name":"Fighters"}items["bar"]={"name":"Tenders"}@app.get("/items/{item_id}")asyncdefread_items(item_id:str):returnitems[item_id]deftest_read_items():withTestClient(app)asclient:response=client.get("/items/foo")assertresponse.status_code==200assertresponse.json()=={"name":"Fighters"}






