Debian Codegraph @

docs_src/app_testing/tutorial004_py310.py

raw
1 from contextlib import asynccontextmanager
2
3 from fastapi import FastAPI
4 from fastapi.testclient import TestClient
5
6 items = {}
7
8
9 @asynccontextmanager
10 async def lifespan(app: FastAPI):
11 items["foo"] = {"name": "Fighters"}
12 items["bar"] = {"name": "Tenders"}
13 yield
14 # clean up items
15 items.clear()
16
17
18 app = FastAPI(lifespan=lifespan)
19
20
21 @app.get("/items/{item_id}")
22 async def read_items(item_id: str):
23 return items[item_id]
24
25
26 def test_read_items():
27 # Before the lifespan starts, "items" is still empty
28 assert items == {}
29
30 with TestClient(app) as client:
31 # Inside the "with TestClient" block, the lifespan starts and items added
32 assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
33
34 response = client.get("/items/foo")
35 assert response.status_code == 200
36 assert response.json() == {"name": "Fighters"}
37
38 # After the requests is done, the items are still there
39 assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
40
41 # The end of the "with TestClient" block simulates terminating the app, so
42 # the lifespan ends and items are cleaned up
43 assert items == {}