Coverage for tests/test_serialize_response.py: 100%

31 statements  

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

1from typing import List, Optional 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 Item(BaseModel): 1abcde

11 name: str 1abcde

12 price: Optional[float] = None 1abcde

13 owner_ids: Optional[List[int]] = None 1abcde

14 

15 

16@app.get("/items/valid", response_model=Item) 1abcde

17def get_valid(): 1abcde

18 return {"name": "valid", "price": 1.0} 1abcde

19 

20 

21@app.get("/items/coerce", response_model=Item) 1abcde

22def get_coerce(): 1abcde

23 return {"name": "coerce", "price": "1.0"} 1abcde

24 

25 

26@app.get("/items/validlist", response_model=List[Item]) 1abcde

27def get_validlist(): 1abcde

28 return [ 1abcde

29 {"name": "foo"}, 

30 {"name": "bar", "price": 1.0}, 

31 {"name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, 

32 ] 

33 

34 

35client = TestClient(app) 1abcde

36 

37 

38def test_valid(): 1abcde

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

40 response.raise_for_status() 1abcde

41 assert response.json() == {"name": "valid", "price": 1.0, "owner_ids": None} 1abcde

42 

43 

44def test_coerce(): 1abcde

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

46 response.raise_for_status() 1abcde

47 assert response.json() == {"name": "coerce", "price": 1.0, "owner_ids": None} 1abcde

48 

49 

50def test_validlist(): 1abcde

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

52 response.raise_for_status() 1abcde

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

54 {"name": "foo", "price": None, "owner_ids": None}, 

55 {"name": "bar", "price": 1.0, "owner_ids": None}, 

56 {"name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]}, 

57 ]