fastapi

Форк
0
/
test_inherited_custom_class.py 
111 строк · 3.0 Кб
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
from .utils import needs_pydanticv1, needs_pydanticv2
9

10

11
class MyUuid:
12
    def __init__(self, uuid_string: str):
13
        self.uuid = uuid_string
14

15
    def __str__(self):
16
        return self.uuid
17

18
    @property  # type: ignore
19
    def __class__(self):
20
        return uuid.UUID
21

22
    @property
23
    def __dict__(self):
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")
27

28

29
@needs_pydanticv2
30
def test_pydanticv2():
31
    from pydantic import field_serializer
32

33
    app = FastAPI()
34

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):
41
            vars(asyncpg_uuid)
42
        return {"fast_uuid": asyncpg_uuid}
43

44
    class SomeCustomClass(BaseModel):
45
        model_config = {"arbitrary_types_allowed": True}
46

47
        a_uuid: MyUuid
48

49
        @field_serializer("a_uuid")
50
        def serialize_a_uuid(self, v):
51
            return str(v)
52

53
    @app.get("/get_custom_class")
54
    def return_some_user():
55
        # Test that the fix also works for custom pydantic classes
56
        return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01"))
57

58
    client = TestClient(app)
59

60
    with client:
61
        response_simple = client.get("/fast_uuid")
62
        response_pydantic = client.get("/get_custom_class")
63

64
    assert response_simple.json() == {
65
        "fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
66
    }
67

68
    assert response_pydantic.json() == {
69
        "a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
70
    }
71

72

73
# TODO: remove when deprecating Pydantic v1
74
@needs_pydanticv1
75
def test_pydanticv1():
76
    app = FastAPI()
77

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):
84
            vars(asyncpg_uuid)
85
        return {"fast_uuid": asyncpg_uuid}
86

87
    class SomeCustomClass(BaseModel):
88
        class Config:
89
            arbitrary_types_allowed = True
90
            json_encoders = {uuid.UUID: str}
91

92
        a_uuid: MyUuid
93

94
    @app.get("/get_custom_class")
95
    def return_some_user():
96
        # Test that the fix also works for custom pydantic classes
97
        return SomeCustomClass(a_uuid=MyUuid("b8799909-f914-42de-91bc-95c819218d01"))
98

99
    client = TestClient(app)
100

101
    with client:
102
        response_simple = client.get("/fast_uuid")
103
        response_pydantic = client.get("/get_custom_class")
104

105
    assert response_simple.json() == {
106
        "fast_uuid": "a10ff360-3b1e-4984-a26f-d3ab460bdb51"
107
    }
108

109
    assert response_pydantic.json() == {
110
        "a_uuid": "b8799909-f914-42de-91bc-95c819218d01"
111
    }
112

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.