Coverage for tests/test_validate_response.py: 100%

51 statements  

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

1from typing import List, Optional, Union 1abcde

2 

3import pytest 1abcde

4from fastapi import FastAPI 1abcde

5from fastapi.exceptions import ResponseValidationError 1abcde

6from fastapi.testclient import TestClient 1abcde

7from pydantic import BaseModel 1abcde

8 

9app = FastAPI() 1abcde

10 

11 

12class Item(BaseModel): 1abcde

13 name: str 1abcde

14 price: Optional[float] = None 1abcde

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

16 

17 

18@app.get("/items/invalid", response_model=Item) 1abcde

19def get_invalid(): 1abcde

20 return {"name": "invalid", "price": "foo"} 1abcde

21 

22 

23@app.get("/items/invalidnone", response_model=Item) 1abcde

24def get_invalid_none(): 1abcde

25 return None 1abcde

26 

27 

28@app.get("/items/validnone", response_model=Union[Item, None]) 1abcde

29def get_valid_none(send_none: bool = False): 1abcde

30 if send_none: 1abcde

31 return None 1abcde

32 else: 

33 return {"name": "invalid", "price": 3.2} 1abcde

34 

35 

36@app.get("/items/innerinvalid", response_model=Item) 1abcde

37def get_innerinvalid(): 1abcde

38 return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]} 1abcde

39 

40 

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

42def get_invalidlist(): 1abcde

43 return [ 1abcde

44 {"name": "foo"}, 

45 {"name": "bar", "price": "bar"}, 

46 {"name": "baz", "price": "baz"}, 

47 ] 

48 

49 

50client = TestClient(app) 1abcde

51 

52 

53def test_invalid(): 1abcde

54 with pytest.raises(ResponseValidationError): 1abcde

55 client.get("/items/invalid") 1abcde

56 

57 

58def test_invalid_none(): 1abcde

59 with pytest.raises(ResponseValidationError): 1abcde

60 client.get("/items/invalidnone") 1abcde

61 

62 

63def test_valid_none_data(): 1abcde

64 response = client.get("/items/validnone") 1abcde

65 data = response.json() 1abcde

66 assert response.status_code == 200 1abcde

67 assert data == {"name": "invalid", "price": 3.2, "owner_ids": None} 1abcde

68 

69 

70def test_valid_none_none(): 1abcde

71 response = client.get("/items/validnone", params={"send_none": "true"}) 1abcde

72 data = response.json() 1abcde

73 assert response.status_code == 200 1abcde

74 assert data is None 1abcde

75 

76 

77def test_double_invalid(): 1abcde

78 with pytest.raises(ResponseValidationError): 1abcde

79 client.get("/items/innerinvalid") 1abcde

80 

81 

82def test_invalid_list(): 1abcde

83 with pytest.raises(ResponseValidationError): 1abcde

84 client.get("/items/invalidlist") 1abcde