| 1 |
from fastapi import FastAPI |
| 2 |
from fastapi.testclient import TestClient |
| 3 |
from pydantic import BaseModel |
| 4 |
|
| 5 |
app = FastAPI() |
| 6 |
|
| 7 |
|
| 8 |
class UserBase(BaseModel): |
| 9 |
email: str |
| 10 |
|
| 11 |
|
| 12 |
class UserCreate(UserBase): |
| 13 |
password: str |
| 14 |
|
| 15 |
|
| 16 |
class UserDB(UserBase): |
| 17 |
hashed_password: str |
| 18 |
|
| 19 |
|
| 20 |
class PetDB(BaseModel): |
| 21 |
name: str |
| 22 |
owner: UserDB |
| 23 |
|
| 24 |
|
| 25 |
class PetOut(BaseModel): |
| 26 |
name: str |
| 27 |
owner: UserBase |
| 28 |
|
| 29 |
|
| 30 |
@app.post("/users/", response_model=UserBase) |
| 31 |
async def create_user(user: UserCreate): |
| 32 |
return user |
| 33 |
|
| 34 |
|
| 35 |
@app.get("/pets/{pet_id}", response_model=PetOut) |
| 36 |
async def read_pet(pet_id: int): |
| 37 |
user = UserDB( |
| 38 |
email="[email protected]", |
| 39 |
hashed_password="secrethashed", |
| 40 |
) |
| 41 |
pet = PetDB(name="Nibbler", owner=user) |
| 42 |
return pet |
| 43 |
|
| 44 |
|
| 45 |
@app.get("/pets/", response_model=list[PetOut]) |
| 46 |
async def read_pets(): |
| 47 |
user = UserDB( |
| 48 |
email="[email protected]", |
| 49 |
hashed_password="secrethashed", |
| 50 |
) |
| 51 |
pet1 = PetDB(name="Nibbler", owner=user) |
| 52 |
pet2 = PetDB(name="Zoidberg", owner=user) |
| 53 |
return [pet1, pet2] |
| 54 |
|
| 55 |
|
| 56 |
client = TestClient(app) |
| 57 |
|
| 58 |
|
| 59 |
def test_filter_top_level_model(): |
| 60 |
response = client.post( |
| 61 |
"/users", json={"email": "[email protected]", "password": "secret"} |
| 62 |
) |
| 63 |
assert response.json() == {"email": "[email protected]"} |
| 64 |
|
| 65 |
|
| 66 |
def test_filter_second_level_model(): |
| 67 |
response = client.get("/pets/1") |
| 68 |
assert response.json() == { |
| 69 |
"name": "Nibbler", |
| 70 |
"owner": {"email": "[email protected]"}, |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
def test_list_of_models(): |
| 75 |
response = client.get("/pets/") |
| 76 |
assert response.json() == [ |
| 77 |
{"name": "Nibbler", "owner": {"email": "[email protected]"}}, |
| 78 |
{"name": "Zoidberg", "owner": {"email": "[email protected]"}}, |
| 79 |
] |