Coverage for docs_src / app_testing / tutorial004_py310.py: 100%
23 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1from contextlib import asynccontextmanager 1ghij
3from fastapi import FastAPI 1ghij
4from fastapi.testclient import TestClient 1ghij
6items = {} 1ghij
9@asynccontextmanager 1ghij
10async def lifespan(app: FastAPI): 1ghij
11 items["foo"] = {"name": "Fighters"} 1abcdef
12 items["bar"] = {"name": "Tenders"} 1abcdef
13 yield 1abcdef
14 # clean up items
15 items.clear() 1abcdef
18app = FastAPI(lifespan=lifespan) 1ghij
21@app.get("/items/{item_id}") 1ghij
22async def read_items(item_id: str): 1ghij
23 return items[item_id] 1abcdef
26def test_read_items(): 1ghij
27 # Before the lifespan starts, "items" is still empty
28 assert items == {} 1abcdef
30 with TestClient(app) as client: 1abcdef
31 # Inside the "with TestClient" block, the lifespan starts and items added
32 assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} 1abcdef
34 response = client.get("/items/foo") 1abcdef
35 assert response.status_code == 200 1abcdef
36 assert response.json() == {"name": "Fighters"} 1abcdef
38 # After the requests is done, the items are still there
39 assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} 1abcdef
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 == {} 1abcdef