fastapi

Форк
0
/
test_infer_param_optionality.py 
357 строк · 13.3 Кб
1
from typing import Optional
2

3
from dirty_equals import IsDict
4
from fastapi import APIRouter, FastAPI
5
from fastapi.testclient import TestClient
6

7
app = FastAPI()
8

9

10
user_router = APIRouter()
11
item_router = APIRouter()
12

13

14
@user_router.get("/")
15
def get_users():
16
    return [{"user_id": "u1"}, {"user_id": "u2"}]
17

18

19
@user_router.get("/{user_id}")
20
def get_user(user_id: str):
21
    return {"user_id": user_id}
22

23

24
@item_router.get("/")
25
def get_items(user_id: Optional[str] = None):
26
    if user_id is None:
27
        return [{"item_id": "i1", "user_id": "u1"}, {"item_id": "i2", "user_id": "u2"}]
28
    else:
29
        return [{"item_id": "i2", "user_id": user_id}]
30

31

32
@item_router.get("/{item_id}")
33
def get_item(item_id: str, user_id: Optional[str] = None):
34
    if user_id is None:
35
        return {"item_id": item_id}
36
    else:
37
        return {"item_id": item_id, "user_id": user_id}
38

39

40
app.include_router(user_router, prefix="/users")
41
app.include_router(item_router, prefix="/items")
42

43
app.include_router(item_router, prefix="/users/{user_id}/items")
44

45

46
client = TestClient(app)
47

48

49
def test_get_users():
50
    """Check that /users returns expected data"""
51
    response = client.get("/users")
52
    assert response.status_code == 200, response.text
53
    assert response.json() == [{"user_id": "u1"}, {"user_id": "u2"}]
54

55

56
def test_get_user():
57
    """Check that /users/{user_id} returns expected data"""
58
    response = client.get("/users/abc123")
59
    assert response.status_code == 200, response.text
60
    assert response.json() == {"user_id": "abc123"}
61

62

63
def test_get_items_1():
64
    """Check that /items returns expected data"""
65
    response = client.get("/items")
66
    assert response.status_code == 200, response.text
67
    assert response.json() == [
68
        {"item_id": "i1", "user_id": "u1"},
69
        {"item_id": "i2", "user_id": "u2"},
70
    ]
71

72

73
def test_get_items_2():
74
    """Check that /items returns expected data with user_id specified"""
75
    response = client.get("/items?user_id=abc123")
76
    assert response.status_code == 200, response.text
77
    assert response.json() == [{"item_id": "i2", "user_id": "abc123"}]
78

79

80
def test_get_item_1():
81
    """Check that /items/{item_id} returns expected data"""
82
    response = client.get("/items/item01")
83
    assert response.status_code == 200, response.text
84
    assert response.json() == {"item_id": "item01"}
85

86

87
def test_get_item_2():
88
    """Check that /items/{item_id} returns expected data with user_id specified"""
89
    response = client.get("/items/item01?user_id=abc123")
90
    assert response.status_code == 200, response.text
91
    assert response.json() == {"item_id": "item01", "user_id": "abc123"}
92

93

94
def test_get_users_items():
95
    """Check that /users/{user_id}/items returns expected data"""
96
    response = client.get("/users/abc123/items")
97
    assert response.status_code == 200, response.text
98
    assert response.json() == [{"item_id": "i2", "user_id": "abc123"}]
99

100

101
def test_get_users_item():
102
    """Check that /users/{user_id}/items returns expected data"""
103
    response = client.get("/users/abc123/items/item01")
104
    assert response.status_code == 200, response.text
105
    assert response.json() == {"item_id": "item01", "user_id": "abc123"}
106

107

108
def test_openapi_schema():
109
    response = client.get("/openapi.json")
110
    assert response.status_code == 200, response.text
111
    assert response.json() == {
112
        "openapi": "3.1.0",
113
        "info": {"title": "FastAPI", "version": "0.1.0"},
114
        "paths": {
115
            "/users/": {
116
                "get": {
117
                    "summary": "Get Users",
118
                    "operationId": "get_users_users__get",
119
                    "responses": {
120
                        "200": {
121
                            "description": "Successful Response",
122
                            "content": {"application/json": {"schema": {}}},
123
                        }
124
                    },
125
                }
126
            },
127
            "/users/{user_id}": {
128
                "get": {
129
                    "summary": "Get User",
130
                    "operationId": "get_user_users__user_id__get",
131
                    "parameters": [
132
                        {
133
                            "required": True,
134
                            "schema": {"title": "User Id", "type": "string"},
135
                            "name": "user_id",
136
                            "in": "path",
137
                        }
138
                    ],
139
                    "responses": {
140
                        "200": {
141
                            "description": "Successful Response",
142
                            "content": {"application/json": {"schema": {}}},
143
                        },
144
                        "422": {
145
                            "description": "Validation Error",
146
                            "content": {
147
                                "application/json": {
148
                                    "schema": {
149
                                        "$ref": "#/components/schemas/HTTPValidationError"
150
                                    }
151
                                }
152
                            },
153
                        },
154
                    },
155
                }
156
            },
157
            "/items/": {
158
                "get": {
159
                    "summary": "Get Items",
160
                    "operationId": "get_items_items__get",
161
                    "parameters": [
162
                        {
163
                            "required": False,
164
                            "name": "user_id",
165
                            "in": "query",
166
                            "schema": IsDict(
167
                                {
168
                                    "anyOf": [{"type": "string"}, {"type": "null"}],
169
                                    "title": "User Id",
170
                                }
171
                            )
172
                            | IsDict(
173
                                # TODO: remove when deprecating Pydantic v1
174
                                {"title": "User Id", "type": "string"}
175
                            ),
176
                        }
177
                    ],
178
                    "responses": {
179
                        "200": {
180
                            "description": "Successful Response",
181
                            "content": {"application/json": {"schema": {}}},
182
                        },
183
                        "422": {
184
                            "description": "Validation Error",
185
                            "content": {
186
                                "application/json": {
187
                                    "schema": {
188
                                        "$ref": "#/components/schemas/HTTPValidationError"
189
                                    }
190
                                }
191
                            },
192
                        },
193
                    },
194
                }
195
            },
196
            "/items/{item_id}": {
197
                "get": {
198
                    "summary": "Get Item",
199
                    "operationId": "get_item_items__item_id__get",
200
                    "parameters": [
201
                        {
202
                            "required": True,
203
                            "schema": {"title": "Item Id", "type": "string"},
204
                            "name": "item_id",
205
                            "in": "path",
206
                        },
207
                        {
208
                            "required": False,
209
                            "name": "user_id",
210
                            "in": "query",
211
                            "schema": IsDict(
212
                                {
213
                                    "anyOf": [{"type": "string"}, {"type": "null"}],
214
                                    "title": "User Id",
215
                                }
216
                            )
217
                            | IsDict(
218
                                # TODO: remove when deprecating Pydantic v1
219
                                {"title": "User Id", "type": "string"}
220
                            ),
221
                        },
222
                    ],
223
                    "responses": {
224
                        "200": {
225
                            "description": "Successful Response",
226
                            "content": {"application/json": {"schema": {}}},
227
                        },
228
                        "422": {
229
                            "description": "Validation Error",
230
                            "content": {
231
                                "application/json": {
232
                                    "schema": {
233
                                        "$ref": "#/components/schemas/HTTPValidationError"
234
                                    }
235
                                }
236
                            },
237
                        },
238
                    },
239
                }
240
            },
241
            "/users/{user_id}/items/": {
242
                "get": {
243
                    "summary": "Get Items",
244
                    "operationId": "get_items_users__user_id__items__get",
245
                    "parameters": [
246
                        {
247
                            "required": True,
248
                            "name": "user_id",
249
                            "in": "path",
250
                            "schema": IsDict(
251
                                {
252
                                    "anyOf": [{"type": "string"}, {"type": "null"}],
253
                                    "title": "User Id",
254
                                }
255
                            )
256
                            | IsDict(
257
                                # TODO: remove when deprecating Pydantic v1
258
                                {"title": "User Id", "type": "string"}
259
                            ),
260
                        }
261
                    ],
262
                    "responses": {
263
                        "200": {
264
                            "description": "Successful Response",
265
                            "content": {"application/json": {"schema": {}}},
266
                        },
267
                        "422": {
268
                            "description": "Validation Error",
269
                            "content": {
270
                                "application/json": {
271
                                    "schema": {
272
                                        "$ref": "#/components/schemas/HTTPValidationError"
273
                                    }
274
                                }
275
                            },
276
                        },
277
                    },
278
                }
279
            },
280
            "/users/{user_id}/items/{item_id}": {
281
                "get": {
282
                    "summary": "Get Item",
283
                    "operationId": "get_item_users__user_id__items__item_id__get",
284
                    "parameters": [
285
                        {
286
                            "required": True,
287
                            "schema": {"title": "Item Id", "type": "string"},
288
                            "name": "item_id",
289
                            "in": "path",
290
                        },
291
                        {
292
                            "required": True,
293
                            "name": "user_id",
294
                            "in": "path",
295
                            "schema": IsDict(
296
                                {
297
                                    "anyOf": [{"type": "string"}, {"type": "null"}],
298
                                    "title": "User Id",
299
                                }
300
                            )
301
                            | IsDict(
302
                                # TODO: remove when deprecating Pydantic v1
303
                                {"title": "User Id", "type": "string"}
304
                            ),
305
                        },
306
                    ],
307
                    "responses": {
308
                        "200": {
309
                            "description": "Successful Response",
310
                            "content": {"application/json": {"schema": {}}},
311
                        },
312
                        "422": {
313
                            "description": "Validation Error",
314
                            "content": {
315
                                "application/json": {
316
                                    "schema": {
317
                                        "$ref": "#/components/schemas/HTTPValidationError"
318
                                    }
319
                                }
320
                            },
321
                        },
322
                    },
323
                }
324
            },
325
        },
326
        "components": {
327
            "schemas": {
328
                "HTTPValidationError": {
329
                    "title": "HTTPValidationError",
330
                    "type": "object",
331
                    "properties": {
332
                        "detail": {
333
                            "title": "Detail",
334
                            "type": "array",
335
                            "items": {"$ref": "#/components/schemas/ValidationError"},
336
                        }
337
                    },
338
                },
339
                "ValidationError": {
340
                    "title": "ValidationError",
341
                    "required": ["loc", "msg", "type"],
342
                    "type": "object",
343
                    "properties": {
344
                        "loc": {
345
                            "title": "Location",
346
                            "type": "array",
347
                            "items": {
348
                                "anyOf": [{"type": "string"}, {"type": "integer"}]
349
                            },
350
                        },
351
                        "msg": {"title": "Message", "type": "string"},
352
                        "type": {"title": "Error Type", "type": "string"},
353
                    },
354
                },
355
            }
356
        },
357
    }
358

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

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

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

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