Coverage for tests / test_inherited_custom_class.py: 100%

42 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1import uuid 1efgh

2 

3import pytest 1efgh

4from fastapi import FastAPI 1efgh

5from fastapi.testclient import TestClient 1efgh

6from pydantic import BaseModel 1efgh

7 

8 

9class MyUuid: 1efgh

10 def __init__(self, uuid_string: str): 1efgh

11 self.uuid = uuid_string 1adbc

12 

13 def __str__(self): 1efgh

14 return self.uuid 1adbc

15 

16 @property # type: ignore 1efgh

17 def __class__(self): 1efgh

18 return uuid.UUID 1adbc

19 

20 @property 1efgh

21 def __dict__(self): 1efgh

22 """Spoof a missing __dict__ by raising TypeError, this is how 

23 asyncpg.pgroto.pgproto.UUID behaves""" 

24 raise TypeError("vars() argument must have __dict__ attribute") 1adbc

25 

26 

27def test_pydanticv2(): 1efgh

28 from pydantic import field_serializer 1adbc

29 

30 app = FastAPI() 1adbc

31 

32 @app.get("/fast_uuid") 1adbc

33 def return_fast_uuid(): 1adbc

34 asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") 1adbc

35 assert isinstance(asyncpg_uuid, uuid.UUID) 1adbc

36 assert type(asyncpg_uuid) is not uuid.UUID 1adbc

37 with pytest.raises(TypeError): 1adbc

38 vars(asyncpg_uuid) 1adbc

39 return {"fast_uuid": asyncpg_uuid} 1adbc

40 

41 class SomeCustomClass(BaseModel): 1adbc

42 model_config = {"arbitrary_types_allowed": True} 1adbc

43 

44 a_uuid: MyUuid 1abc

45 

46 @field_serializer("a_uuid") 1adbc

47 def serialize_a_uuid(self, v): 1adbc

48 return str(v) 1adbc

49 

50 @app.get("/get_custom_class") 1adbc

51 def return_some_user(): 1adbc

52 # Test that the fix also works for custom pydantic classes 

53 return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01")) 1adbc

54 

55 client = TestClient(app) 1adbc

56 

57 with client: 1adbc

58 response_simple = client.get("/fast_uuid") 1adbc

59 response_pydantic = client.get("/get_custom_class") 1adbc

60 

61 assert response_simple.json() == { 1adbc

62 "fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51" 

63 } 

64 

65 assert response_pydantic.json() == { 1adbc

66 "a_uuid": "b8799909-f914-42de-91bc-95c819218d01" 

67 }