Coverage for tests/test_response_model_data_filter_no_inheritance.py: 100%

43 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 UserCreate(BaseModel): 1abcde

11 email: str 1abcde

12 password: str 1abcde

13 

14 

15class UserDB(BaseModel): 1abcde

16 email: str 1abcde

17 hashed_password: str 1abcde

18 

19 

20class User(BaseModel): 1abcde

21 email: str 1abcde

22 

23 

24class PetDB(BaseModel): 1abcde

25 name: str 1abcde

26 owner: UserDB 1abcde

27 

28 

29class PetOut(BaseModel): 1abcde

30 name: str 1abcde

31 owner: User 1abcde

32 

33 

34@app.post("/users/", response_model=User) 1abcde

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

36 return user 1abcde

37 

38 

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

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

41 user = UserDB( 1abcde

42 email="johndoe@example.com", 

43 hashed_password="secrethashed", 

44 ) 

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

46 return pet 1abcde

47 

48 

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

50async def read_pets(): 1abcde

51 user = UserDB( 1abcde

52 email="johndoe@example.com", 

53 hashed_password="secrethashed", 

54 ) 

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

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

57 return [pet1, pet2] 1abcde

58 

59 

60client = TestClient(app) 1abcde

61 

62 

63def test_filter_top_level_model(): 1abcde

64 response = client.post( 1abcde

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

66 ) 

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

68 

69 

70def test_filter_second_level_model(): 1abcde

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

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

73 "name": "Nibbler", 

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

75 } 

76 

77 

78def test_list_of_models(): 1abcde

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

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

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

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

83 ]