4
from fastapi import FastAPI
5
from fastapi.testclient import TestClient
6
from pydantic import BaseModel
8
from .utils import needs_pydanticv1, needs_pydanticv2
12
def __init__(self, uuid_string: str):
13
self.uuid = uuid_string
24
"""Spoof a missing __dict__ by raising TypeError, this is how
25
asyncpg.pgroto.pgproto.UUID behaves"""
26
raise TypeError("vars() argument must have __dict__ attribute")
31
from pydantic import field_serializer
35
@app.get("/fast_uuid")
36
def return_fast_uuid():
37
asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51")
38
assert isinstance(asyncpg_uuid, uuid.UUID)
39
assert type(asyncpg_uuid) != uuid.UUID
40
with pytest.raises(TypeError):
42
return {"fast_uuid": asyncpg_uuid}
44
class SomeCustomClass(BaseModel):
45
model_config = {"arbitrary_types_allowed": True}
49
@field_serializer("a_uuid")
50
def serialize_a_uuid(self, v):
53
@app.get("/get_custom_class")
54
def return_some_user():
56
return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01"))
58
client = TestClient(app)
61
response_simple = client.get("/fast_uuid")
62
response_pydantic = client.get("/get_custom_class")
64
assert response_simple.json() == {
65
"fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
68
assert response_pydantic.json() == {
69
"a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
78
@app.get("/fast_uuid")
79
def return_fast_uuid():
80
asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51")
81
assert isinstance(asyncpg_uuid, uuid.UUID)
82
assert type(asyncpg_uuid) != uuid.UUID
83
with pytest.raises(TypeError):
85
return {"fast_uuid": asyncpg_uuid}
87
class SomeCustomClass(BaseModel):
89
arbitrary_types_allowed = True
90
json_encoders = {uuid.UUID: str}
94
@app.get("/get_custom_class")
95
def return_some_user():
97
return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01"))
99
client = TestClient(app)
102
response_simple = client.get("/fast_uuid")
103
response_pydantic = client.get("/get_custom_class")
105
assert response_simple.json() == {
106
"fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
109
assert response_pydantic.json() == {
110
"a_uuid": "b8799909-f914-42de-91bc-95c819218d01"