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
« prev ^ index » next coverage.py v7.13.3, created at 2026-04-06 01:24 +0000
1import uuid 1efgh
3import pytest 1efgh
4from fastapi import FastAPI 1efgh
5from fastapi.testclient import TestClient 1efgh
6from pydantic import BaseModel 1efgh
9class MyUuid: 1efgh
10 def __init__(self, uuid_string: str): 1efgh
11 self.uuid = uuid_string 1adbc
13 def __str__(self): 1efgh
14 return self.uuid 1adbc
16 @property # type: ignore 1efgh
17 def __class__(self): 1efgh
18 return uuid.UUID 1adbc
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
27def test_pydanticv2(): 1efgh
28 from pydantic import field_serializer 1adbc
30 app = FastAPI() 1adbc
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
41 class SomeCustomClass(BaseModel): 1adbc
42 model_config = {"arbitrary_types_allowed": True} 1adbc
44 a_uuid: MyUuid 1abc
46 @field_serializer("a_uuid") 1adbc
47 def serialize_a_uuid(self, v): 1adbc
48 return str(v) 1adbc
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
55 client = TestClient(app) 1adbc
57 with client: 1adbc
58 response_simple = client.get("/fast_uuid") 1adbc
59 response_pydantic = client.get("/get_custom_class") 1adbc
61 assert response_simple.json() == { 1adbc
62 "fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
63 }
65 assert response_pydantic.json() == { 1adbc
66 "a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
67 }