Coverage for docs_src / app_testing / tutorial004_py310.py: 100%

23 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from contextlib import asynccontextmanager 1hijk

2 

3from fastapi import FastAPI 1hijk

4from fastapi.testclient import TestClient 1hijk

5 

6items = {} 1hijk

7 

8 

9@asynccontextmanager 1hijk

10async def lifespan(app: FastAPI): 1hijk

11 items["foo"] = {"name": "Fighters"} 1abcdefg

12 items["bar"] = {"name": "Tenders"} 1abcdefg

13 yield 1abcdefg

14 # clean up items 

15 items.clear() 1abcdefg

16 

17 

18app = FastAPI(lifespan=lifespan) 1hijk

19 

20 

21@app.get("/items/{item_id}") 1hijk

22async def read_items(item_id: str): 1hijk

23 return items[item_id] 1abcdefg

24 

25 

26def test_read_items(): 1hijk

27 # Before the lifespan starts, "items" is still empty 

28 assert items == {} 1abcdefg

29 

30 with TestClient(app) as client: 1abcdefg

31 # Inside the "with TestClient" block, the lifespan starts and items added 

32 assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} 1abcdefg

33 

34 response = client.get("/items/foo") 1abcdefg

35 assert response.status_code == 200 1abcdefg

36 assert response.json() == {"name": "Fighters"} 1abcdefg

37 

38 # After the requests is done, the items are still there 

39 assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}} 1abcdefg

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