mirror of
https://github.com/fastapi/fastapi.git
synced 2026-03-24 17:55:46 -04:00
📝 Update testing events documentation (#13259)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com> Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
This commit is contained in:
43
docs_src/app_testing/tutorial004.py
Normal file
43
docs_src/app_testing/tutorial004.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
items = {}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
items["foo"] = {"name": "Fighters"}
|
||||
items["bar"] = {"name": "Tenders"}
|
||||
yield
|
||||
# clean up items
|
||||
items.clear()
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
async def read_items(item_id: str):
|
||||
return items[item_id]
|
||||
|
||||
|
||||
def test_read_items():
|
||||
# Before the lifespan starts, "items" is still empty
|
||||
assert items == {}
|
||||
|
||||
with TestClient(app) as client:
|
||||
# Inside the "with TestClient" block, the lifespan starts and items added
|
||||
assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
|
||||
|
||||
response = client.get("/items/foo")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"name": "Fighters"}
|
||||
|
||||
# After the requests is done, the items are still there
|
||||
assert items == {"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 up
|
||||
assert items == {}
|
||||
Reference in New Issue
Block a user