| 1 |
import uuid |
| 2 |
|
| 3 |
import pytest |
| 4 |
from fastapi import FastAPI |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
from pydantic import BaseModel |
| 7 |
|
| 8 |
|
| 9 |
class MyUuid: |
| 10 |
def __init__(self, uuid_string: str): |
| 11 |
self.uuid = uuid_string |
| 12 |
|
| 13 |
def __str__(self): |
| 14 |
return self.uuid |
| 15 |
|
| 16 |
@property |
| 17 |
def __class__(self): |
| 18 |
return uuid.UUID |
| 19 |
|
| 20 |
@property |
| 21 |
def __dict__(self): |
| 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") |
| 25 |
|
| 26 |
|
| 27 |
def test_pydanticv2(): |
| 28 |
from pydantic import field_serializer |
| 29 |
|
| 30 |
app = FastAPI() |
| 31 |
|
| 32 |
@app.get("/fast_uuid") |
| 33 |
def return_fast_uuid(): |
| 34 |
asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") |
| 35 |
assert isinstance(asyncpg_uuid, uuid.UUID) |
| 36 |
assert type(asyncpg_uuid) is not uuid.UUID |
| 37 |
with pytest.raises(TypeError): |
| 38 |
vars(asyncpg_uuid) |
| 39 |
return {"fast_uuid": asyncpg_uuid} |
| 40 |
|
| 41 |
class SomeCustomClass(BaseModel): |
| 42 |
model_config = {"arbitrary_types_allowed": True} |
| 43 |
|
| 44 |
a_uuid: MyUuid |
| 45 |
|
| 46 |
@field_serializer("a_uuid") |
| 47 |
def serialize_a_uuid(self, v): |
| 48 |
return str(v) |
| 49 |
|
| 50 |
@app.get("/get_custom_class") |
| 51 |
def return_some_user(): |
| 52 |
# Test that the fix also works for custom pydantic classes |
| 53 |
return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01")) |
| 54 |
|
| 55 |
client = TestClient(app) |
| 56 |
|
| 57 |
with client: |
| 58 |
response_simple = client.get("/fast_uuid") |
| 59 |
response_pydantic = client.get("/get_custom_class") |
| 60 |
|
| 61 |
assert response_simple.json() == { |
| 62 |
"fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51" |
| 63 |
} |
| 64 |
|
| 65 |
assert response_pydantic.json() == { |
| 66 |
"a_uuid": "b8799909-f914-42de-91bc-95c819218d01" |
| 67 |
} |