Coverage for tests/test_response_model_data_filter.py: 100%

41 statements  

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

1from typing import List 1abcde

2 

3from fastapi import FastAPI 1abcde

4from fastapi.testclient import TestClient 1abcde

5from pydantic import BaseModel 1abcde

6 

7app = FastAPI() 1abcde

8 

9 

10class UserBase(BaseModel): 1abcde

11 email: str 1abcde

12 

13 

14class UserCreate(UserBase): 1abcde

15 password: str 1abcde

16 

17 

18class UserDB(UserBase): 1abcde

19 hashed_password: str 1abcde

20 

21 

22class PetDB(BaseModel): 1abcde

23 name: str 1abcde

24 owner: UserDB 1abcde

25 

26 

27class PetOut(BaseModel): 1abcde

28 name: str 1abcde

29 owner: UserBase 1abcde

30 

31 

32@app.post("/users/", response_model=UserBase) 1abcde

33async def create_user(user: UserCreate): 1abcde

34 return user 1abcde

35 

36 

37@app.get("/pets/{pet_id}", response_model=PetOut) 1abcde

38async def read_pet(pet_id: int): 1abcde

39 user = UserDB( 1abcde

40 email="johndoe@example.com", 

41 hashed_password="secrethashed", 

42 ) 

43 pet = PetDB(name="Nibbler", owner=user) 1abcde

44 return pet 1abcde

45 

46 

47@app.get("/pets/", response_model=List[PetOut]) 1abcde

48async def read_pets(): 1abcde

49 user = UserDB( 1abcde

50 email="johndoe@example.com", 

51 hashed_password="secrethashed", 

52 ) 

53 pet1 = PetDB(name="Nibbler", owner=user) 1abcde

54 pet2 = PetDB(name="Zoidberg", owner=user) 1abcde

55 return [pet1, pet2] 1abcde

56 

57 

58client = TestClient(app) 1abcde

59 

60 

61def test_filter_top_level_model(): 1abcde

62 response = client.post( 1abcde

63 "/users", json={"email": "johndoe@example.com", "password": "secret"} 

64 ) 

65 assert response.json() == {"email": "johndoe@example.com"} 1abcde

66 

67 

68def test_filter_second_level_model(): 1abcde

69 response = client.get("/pets/1") 1abcde

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

71 "name": "Nibbler", 

72 "owner": {"email": "johndoe@example.com"}, 

73 } 

74 

75 

76def test_list_of_models(): 1abcde

77 response = client.get("/pets/") 1abcde

78 assert response.json() == [ 1abcde

79 {"name": "Nibbler", "owner": {"email": "johndoe@example.com"}}, 

80 {"name": "Zoidberg", "owner": {"email": "johndoe@example.com"}}, 

81 ]