Coverage for tests/test_validate_response_dataclass.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 

3import pytest 1abcde

4from fastapi import FastAPI 1abcde

5from fastapi.exceptions import ResponseValidationError 1abcde

6from fastapi.testclient import TestClient 1abcde

7from pydantic.dataclasses import dataclass 1abcde

8 

9app = FastAPI() 1abcde

10 

11 

12@dataclass 1abcde

13class Item: 1abcde

14 name: str 1abcde

15 price: Optional[float] = None 1abcde

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

17 

18 

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

20def get_invalid(): 1abcde

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

22 

23 

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

25def get_innerinvalid(): 1abcde

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

27 

28 

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

30def get_invalidlist(): 1abcde

31 return [ 1abcde

32 {"name": "foo"}, 

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

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

35 ] 

36 

37 

38client = TestClient(app) 1abcde

39 

40 

41def test_invalid(): 1abcde

42 with pytest.raises(ResponseValidationError): 1abcde

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

44 

45 

46def test_double_invalid(): 1abcde

47 with pytest.raises(ResponseValidationError): 1abcde

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

49 

50 

51def test_invalid_list(): 1abcde

52 with pytest.raises(ResponseValidationError): 1abcde

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