Coverage for docs_src/dependency_testing/tutorial001_an_py39.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from typing import Annotated, Union 1abcd

2 

3from fastapi import Depends, FastAPI 1abcd

4from fastapi.testclient import TestClient 1abcd

5 

6app = FastAPI() 1abcd

7 

8 

9async def common_parameters( 1abcd

10 q: Union[str, None] = None, skip: int = 0, limit: int = 100 

11): 

12 return {"q": q, "skip": skip, "limit": limit} 1abcd

13 

14 

15@app.get("/items/") 1abcd

16async def read_items(commons: Annotated[dict, Depends(common_parameters)]): 1abcd

17 return {"message": "Hello Items!", "params": commons} 1abcd

18 

19 

20@app.get("/users/") 1abcd

21async def read_users(commons: Annotated[dict, Depends(common_parameters)]): 1abcd

22 return {"message": "Hello Users!", "params": commons} 1abcd

23 

24 

25client = TestClient(app) 1abcd

26 

27 

28async def override_dependency(q: Union[str, None] = None): 1abcd

29 return {"q": q, "skip": 5, "limit": 10} 1abcd

30 

31 

32app.dependency_overrides[common_parameters] = override_dependency 1abcd

33 

34 

35def test_override_in_items(): 1abcd

36 response = client.get("/items/") 1abcd

37 assert response.status_code == 200 1abcd

38 assert response.json() == { 1abcd

39 "message": "Hello Items!", 

40 "params": {"q": None, "skip": 5, "limit": 10}, 

41 } 

42 

43 

44def test_override_in_items_with_q(): 1abcd

45 response = client.get("/items/?q=foo") 1abcd

46 assert response.status_code == 200 1abcd

47 assert response.json() == { 1abcd

48 "message": "Hello Items!", 

49 "params": {"q": "foo", "skip": 5, "limit": 10}, 

50 } 

51 

52 

53def test_override_in_items_with_params(): 1abcd

54 response = client.get("/items/?q=foo&skip=100&limit=200") 1abcd

55 assert response.status_code == 200 1abcd

56 assert response.json() == { 1abcd

57 "message": "Hello Items!", 

58 "params": {"q": "foo", "skip": 5, "limit": 10}, 

59 }