Coverage for tests / test_inherited_custom_class.py: 100%

42 statements  

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

1import uuid 1defg

2 

3import pytest 1defg

4from fastapi import FastAPI 1defg

5from fastapi.testclient import TestClient 1defg

6from pydantic import BaseModel 1defg

7 

8 

9class MyUuid: 1defg

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

11 self.uuid = uuid_string 1abc

12 

13 def __str__(self): 1defg

14 return self.uuid 1abc

15 

16 @property # type: ignore 1defg

17 def __class__(self): 1defg

18 return uuid.UUID 1abc

19 

20 @property 1defg

21 def __dict__(self): 1defg

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") 1abc

25 

26 

27def test_pydanticv2(): 1defg

28 from pydantic import field_serializer 1abc

29 

30 app = FastAPI() 1abc

31 

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

33 def return_fast_uuid(): 1abc

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

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

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

37 with pytest.raises(TypeError): 1abc

38 vars(asyncpg_uuid) 1abc

39 return {"fast_uuid": asyncpg_uuid} 1abc

40 

41 class SomeCustomClass(BaseModel): 1abc

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

43 

44 a_uuid: MyUuid 1abc

45 

46 @field_serializer("a_uuid") 1abc

47 def serialize_a_uuid(self, v): 1abc

48 return str(v) 1abc

49 

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

51 def return_some_user(): 1abc

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

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

54 

55 client = TestClient(app) 1abc

56 

57 with client: 1abc

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

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

60 

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

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

63 } 

64 

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

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

67 }