When you need lifespan to run in your tests, you can use the TestClient with a with 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=={}