fastapi

Форк
0
/
test_regex_deprecated_body.py 
182 строки · 6.3 Кб
1
import pytest
2
from dirty_equals import IsDict
3
from fastapi import FastAPI, Form
4
from fastapi.testclient import TestClient
5
from fastapi.utils import match_pydantic_error_url
6
from typing_extensions import Annotated
7

8
from .utils import needs_py310
9

10

11
def get_client():
12
    app = FastAPI()
13
    with pytest.warns(DeprecationWarning):
14

15
        @app.post("/items/")
16
        async def read_items(
17
            q: Annotated[str | None, Form(regex="^fixedquery$")] = None
18
        ):
19
            if q:
20
                return f"Hello {q}"
21
            else:
22
                return "Hello World"
23

24
    client = TestClient(app)
25
    return client
26

27

28
@needs_py310
29
def test_no_query():
30
    client = get_client()
31
    response = client.post("/items/")
32
    assert response.status_code == 200
33
    assert response.json() == "Hello World"
34

35

36
@needs_py310
37
def test_q_fixedquery():
38
    client = get_client()
39
    response = client.post("/items/", data={"q": "fixedquery"})
40
    assert response.status_code == 200
41
    assert response.json() == "Hello fixedquery"
42

43

44
@needs_py310
45
def test_query_nonregexquery():
46
    client = get_client()
47
    response = client.post("/items/", data={"q": "nonregexquery"})
48
    assert response.status_code == 422
49
    assert response.json() == IsDict(
50
        {
51
            "detail": [
52
                {
53
                    "type": "string_pattern_mismatch",
54
                    "loc": ["body", "q"],
55
                    "msg": "String should match pattern '^fixedquery$'",
56
                    "input": "nonregexquery",
57
                    "ctx": {"pattern": "^fixedquery$"},
58
                    "url": match_pydantic_error_url("string_pattern_mismatch"),
59
                }
60
            ]
61
        }
62
    ) | IsDict(
63
        # TODO: remove when deprecating Pydantic v1
64
        {
65
            "detail": [
66
                {
67
                    "ctx": {"pattern": "^fixedquery$"},
68
                    "loc": ["body", "q"],
69
                    "msg": 'string does not match regex "^fixedquery$"',
70
                    "type": "value_error.str.regex",
71
                }
72
            ]
73
        }
74
    )
75

76

77
@needs_py310
78
def test_openapi_schema():
79
    client = get_client()
80
    response = client.get("/openapi.json")
81
    assert response.status_code == 200, response.text
82
    # insert_assert(response.json())
83
    assert response.json() == {
84
        "openapi": "3.1.0",
85
        "info": {"title": "FastAPI", "version": "0.1.0"},
86
        "paths": {
87
            "/items/": {
88
                "post": {
89
                    "summary": "Read Items",
90
                    "operationId": "read_items_items__post",
91
                    "requestBody": {
92
                        "content": {
93
                            "application/x-www-form-urlencoded": {
94
                                "schema": IsDict(
95
                                    {
96
                                        "allOf": [
97
                                            {
98
                                                "$ref": "#/components/schemas/Body_read_items_items__post"
99
                                            }
100
                                        ],
101
                                        "title": "Body",
102
                                    }
103
                                )
104
                                | IsDict(
105
                                    # TODO: remove when deprecating Pydantic v1
106
                                    {
107
                                        "$ref": "#/components/schemas/Body_read_items_items__post"
108
                                    }
109
                                )
110
                            }
111
                        }
112
                    },
113
                    "responses": {
114
                        "200": {
115
                            "description": "Successful Response",
116
                            "content": {"application/json": {"schema": {}}},
117
                        },
118
                        "422": {
119
                            "description": "Validation Error",
120
                            "content": {
121
                                "application/json": {
122
                                    "schema": {
123
                                        "$ref": "#/components/schemas/HTTPValidationError"
124
                                    }
125
                                }
126
                            },
127
                        },
128
                    },
129
                }
130
            }
131
        },
132
        "components": {
133
            "schemas": {
134
                "Body_read_items_items__post": {
135
                    "properties": {
136
                        "q": IsDict(
137
                            {
138
                                "anyOf": [
139
                                    {"type": "string", "pattern": "^fixedquery$"},
140
                                    {"type": "null"},
141
                                ],
142
                                "title": "Q",
143
                            }
144
                        )
145
                        | IsDict(
146
                            # TODO: remove when deprecating Pydantic v1
147
                            {"type": "string", "pattern": "^fixedquery$", "title": "Q"}
148
                        )
149
                    },
150
                    "type": "object",
151
                    "title": "Body_read_items_items__post",
152
                },
153
                "HTTPValidationError": {
154
                    "properties": {
155
                        "detail": {
156
                            "items": {"$ref": "#/components/schemas/ValidationError"},
157
                            "type": "array",
158
                            "title": "Detail",
159
                        }
160
                    },
161
                    "type": "object",
162
                    "title": "HTTPValidationError",
163
                },
164
                "ValidationError": {
165
                    "properties": {
166
                        "loc": {
167
                            "items": {
168
                                "anyOf": [{"type": "string"}, {"type": "integer"}]
169
                            },
170
                            "type": "array",
171
                            "title": "Location",
172
                        },
173
                        "msg": {"type": "string", "title": "Message"},
174
                        "type": {"type": "string", "title": "Error Type"},
175
                    },
176
                    "type": "object",
177
                    "required": ["loc", "msg", "type"],
178
                    "title": "ValidationError",
179
                },
180
            }
181
        },
182
    }
183

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

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

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

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