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

29 statements  

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

1from typing import Union 1abcde

2 

3from fastapi import Depends, FastAPI 1abcde

4from fastapi.testclient import TestClient 1abcde

5from typing_extensions import Annotated 1abcde

6 

7app = FastAPI() 1abcde

8 

9 

10async def common_parameters( 1abcde

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

12): 

13 return {"q": q, "skip": skip, "limit": limit} 1abcde

14 

15 

16@app.get("/items/") 1abcde

17async def read_items(commons: Annotated[dict, Depends(common_parameters)]): 1abcde

18 return {"message": "Hello Items!", "params": commons} 1abcde

19 

20 

21@app.get("/users/") 1abcde

22async def read_users(commons: Annotated[dict, Depends(common_parameters)]): 1abcde

23 return {"message": "Hello Users!", "params": commons} 1abcde

24 

25 

26client = TestClient(app) 1abcde

27 

28 

29async def override_dependency(q: Union[str, None] = None): 1abcde

30 return {"q": q, "skip": 5, "limit": 10} 1abcde

31 

32 

33app.dependency_overrides[common_parameters] = override_dependency 1abcde

34 

35 

36def test_override_in_items(): 1abcde

37 response = client.get("/items/") 1abcde

38 assert response.status_code == 200 1abcde

39 assert response.json() == { 1abcde

40 "message": "Hello Items!", 

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

42 } 

43 

44 

45def test_override_in_items_with_q(): 1abcde

46 response = client.get("/items/?q=foo") 1abcde

47 assert response.status_code == 200 1abcde

48 assert response.json() == { 1abcde

49 "message": "Hello Items!", 

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

51 } 

52 

53 

54def test_override_in_items_with_params(): 1abcde

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

56 assert response.status_code == 200 1abcde

57 assert response.json() == { 1abcde

58 "message": "Hello Items!", 

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

60 }