Coverage for tests / test_read_with_orm_mode.py: 100%

31 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from typing import Any 1defg

2 

3from fastapi import FastAPI 1defg

4from fastapi.testclient import TestClient 1defg

5from pydantic import BaseModel, ConfigDict 1defg

6 

7 

8def test_read_with_orm_mode() -> None: 1defg

9 class PersonBase(BaseModel): 1abc

10 name: str 1abc

11 lastname: str 1abc

12 

13 class Person(PersonBase): 1abc

14 @property 1abc

15 def full_name(self) -> str: 1abc

16 return f"{self.name} {self.lastname}" 1abc

17 

18 model_config = ConfigDict(from_attributes=True) 1abc

19 

20 class PersonCreate(PersonBase): 1abc

21 pass 1abc

22 

23 class PersonRead(PersonBase): 1abc

24 full_name: str 1abc

25 

26 model_config = {"from_attributes": True} 1abc

27 

28 app = FastAPI() 1abc

29 

30 @app.post("/people/", response_model=PersonRead) 1abc

31 def create_person(person: PersonCreate) -> Any: 1abc

32 db_person = Person.model_validate(person) 1abc

33 return db_person 1abc

34 

35 client = TestClient(app) 1abc

36 

37 person_data = {"name": "Dive", "lastname": "Wilson"} 1abc

38 response = client.post("/people/", json=person_data) 1abc

39 data = response.json() 1abc

40 assert response.status_code == 200, response.text 1abc

41 assert data["name"] == person_data["name"] 1abc

42 assert data["lastname"] == person_data["lastname"] 1abc

43 assert data["full_name"] == person_data["name"] + " " + person_data["lastname"] 1abc