Movatterモバイル変換


[0]ホーム

URL:


Saltar a contenido
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Eventos de testing: lifespan y startup - shutdown

🌐 Traducción por IA y humanos

Esta traducción fue hecha por IA guiada por humanos. 🤝

Podría tener errores al interpretar el significado original, o sonar poco natural, etc. 🤖

Puedes mejorar esta traducciónayudándonos a guiar mejor al LLM de IA.

Versión en inglés

Cuando necesitas quelifespan se ejecute en tus tests, puedes usar elTestClient con un statementwith:

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=={}

Puedes leer más detalles sobre"Ejecutar lifespan en tests en el sitio oficial de documentación de Starlette."

Para los eventos obsoletosstartup yshutdown, puedes usar elTestClient así:

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"}

[8]ページ先頭

©2009-2026 Movatter.jp