-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathtest_openapi_params.py
547 lines (393 loc) · 15.6 KB
/
test_openapi_params.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
from dataclasses import dataclass
from datetime import datetime
from typing import List
from pydantic import BaseModel, Field
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver, Response, Router
from aws_lambda_powertools.event_handler.openapi.models import (
Example,
Parameter,
ParameterInType,
Schema,
)
from aws_lambda_powertools.event_handler.openapi.params import (
Body,
Header,
Param,
ParamTypes,
Query,
_create_model_field,
)
JSON_CONTENT_TYPE = "application/json"
def test_openapi_no_params():
app = APIGatewayRestResolver()
@app.get("/")
def handler():
raise NotImplementedError()
schema = app.get_openapi_schema()
assert schema.info.title == "Powertools API"
assert schema.info.version == "1.0.0"
assert len(schema.paths.keys()) == 1
assert "/" in schema.paths
path = schema.paths["/"]
assert path.get
get = path.get
assert get.summary == "GET /"
assert get.operationId == "handler__get"
assert get.deprecated is None
assert get.responses is not None
assert 200 in get.responses.keys()
response = get.responses[200]
assert response.description == "Successful Response"
assert JSON_CONTENT_TYPE in response.content
json_response = response.content[JSON_CONTENT_TYPE]
assert json_response.schema_ is None
assert not json_response.examples
assert not json_response.encoding
def test_openapi_with_scalar_params():
app = APIGatewayRestResolver()
@app.get("/users/<user_id>")
def handler(user_id: str, include_extra: bool = False):
raise NotImplementedError()
schema = app.get_openapi_schema(title="My API", version="0.2.2")
assert schema.info.title == "My API"
assert schema.info.version == "0.2.2"
assert len(schema.paths.keys()) == 1
assert "/users/{user_id}" in schema.paths
path = schema.paths["/users/{user_id}"]
assert path.get
get = path.get
assert get.summary == "GET /users/{user_id}"
assert get.operationId == "handler_users__user_id__get"
assert len(get.parameters) == 2
parameter = get.parameters[0]
assert isinstance(parameter, Parameter)
assert parameter.in_ == ParameterInType.path
assert parameter.name == "user_id"
assert parameter.required is True
assert parameter.schema_.default is None
assert parameter.schema_.type == "string"
assert parameter.schema_.title == "User Id"
parameter = get.parameters[1]
assert isinstance(parameter, Parameter)
assert parameter.in_ == ParameterInType.query
assert parameter.name == "include_extra"
assert parameter.required is False
assert parameter.schema_.default is False
assert parameter.schema_.type == "boolean"
assert parameter.schema_.title == "Include Extra"
def test_openapi_with_custom_params():
app = APIGatewayRestResolver()
@app.get("/users", summary="Get Users", operation_id="GetUsers", description="Get paginated users", tags=["Users"])
def handler(
count: Annotated[
int,
Query(gt=0, lt=100, examples=[Example(summary="Example 1", value=10)]),
] = 1,
):
print(count)
raise NotImplementedError()
schema = app.get_openapi_schema()
get = schema.paths["/users"].get
assert len(get.parameters) == 1
assert get.summary == "Get Users"
assert get.operationId == "GetUsers"
assert get.description == "Get paginated users"
assert get.tags == ["Users"]
parameter = get.parameters[0]
assert parameter.required is False
assert parameter.name == "count"
assert parameter.in_ == ParameterInType.query
assert parameter.schema_.type == "integer"
assert parameter.schema_.default == 1
assert parameter.schema_.title == "Count"
assert parameter.schema_.exclusiveMinimum == 0
assert parameter.schema_.exclusiveMaximum == 100
assert len(parameter.schema_.examples) == 1
example = Example(**parameter.schema_.examples[0])
assert example.summary == "Example 1"
assert example.value == 10
def test_openapi_with_scalar_returns():
app = APIGatewayRestResolver()
@app.get("/")
def handler() -> str:
return "Hello, world"
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert get.parameters is None
response = get.responses[200].content[JSON_CONTENT_TYPE]
assert response.schema_.title == "Return"
assert response.schema_.type == "string"
def test_openapi_with_response_returns():
app = APIGatewayRestResolver()
@app.get("/")
def handler() -> Response[Annotated[str, Body(title="Response title")]]:
return Response(body="Hello, world", status_code=200)
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert get.parameters is None
response = get.responses[200].content[JSON_CONTENT_TYPE]
assert response.schema_.title == "Response title"
assert response.schema_.type == "string"
def test_openapi_with_omitted_param():
app = APIGatewayRestResolver()
@app.get("/")
def handler(page: Annotated[str, Query(include_in_schema=False)]):
return page
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert get.parameters is None
def test_openapi_with_list_param():
app = APIGatewayRestResolver()
@app.get("/")
def handler(page: Annotated[List[str], Query()]):
return page
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert get.parameters[0].schema_.type == "array"
def test_openapi_with_description():
app = APIGatewayRestResolver()
@app.get("/")
def handler(page: Annotated[str, Query(description="This is a description")]):
return page
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert len(get.parameters) == 1
parameter = get.parameters[0]
assert parameter.description == "This is a description"
def test_openapi_with_deprecated():
app = APIGatewayRestResolver()
@app.get("/")
def handler(page: Annotated[str, Query(deprecated=True)]):
return page
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert len(get.parameters) == 1
parameter = get.parameters[0]
assert parameter.deprecated is True
def test_openapi_with_pydantic_returns():
app = APIGatewayRestResolver()
class User(BaseModel):
name: str
@app.get("/")
def handler() -> User:
return User(name="Ruben Fonseca")
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert get.parameters is None
response = get.responses[200].content[JSON_CONTENT_TYPE]
reference = response.schema_
assert reference.ref == "#/components/schemas/User"
assert "User" in schema.components.schemas
user_schema = schema.components.schemas["User"]
assert isinstance(user_schema, Schema)
assert user_schema.title == "User"
assert "name" in user_schema.properties
def test_openapi_with_pydantic_nested_returns():
app = APIGatewayRestResolver()
class Order(BaseModel):
date: datetime
class User(BaseModel):
name: str
orders: List[Order]
@app.get("/")
def handler() -> User:
return User(name="Ruben Fonseca", orders=[Order(date=datetime.now())])
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
assert "User" in schema.components.schemas
assert "Order" in schema.components.schemas
user_schema = schema.components.schemas["User"]
assert "orders" in user_schema.properties
assert user_schema.properties["orders"].type == "array"
def test_openapi_with_dataclass_return():
app = APIGatewayRestResolver()
@dataclass
class User:
surname: str
@app.get("/")
def handler() -> User:
return User(surname="Fonseca")
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
get = schema.paths["/"].get
assert get.parameters is None
response = get.responses[200].content[JSON_CONTENT_TYPE]
reference = response.schema_
assert reference.ref == "#/components/schemas/User"
assert "User" in schema.components.schemas
user_schema = schema.components.schemas["User"]
assert isinstance(user_schema, Schema)
assert user_schema.title == "User"
assert "surname" in user_schema.properties
def test_openapi_with_body_param():
app = APIGatewayRestResolver()
class User(BaseModel):
name: str
@app.post("/users")
def handler(user: User):
print(user)
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
post = schema.paths["/users"].post
assert post.parameters is None
assert post.requestBody is not None
request_body = post.requestBody
assert request_body.required is True
assert request_body.content[JSON_CONTENT_TYPE].schema_.ref == "#/components/schemas/User"
def test_openapi_with_embed_body_param():
app = APIGatewayRestResolver()
class User(BaseModel):
name: str
@app.post("/users")
def handler(user: Annotated[User, Body(embed=True)]):
print(user)
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
post = schema.paths["/users"].post
assert post.parameters is None
assert post.requestBody is not None
request_body = post.requestBody
assert request_body.required is True
# Notice here we craft a specific schema for the embedded user
assert request_body.content[JSON_CONTENT_TYPE].schema_.ref == "#/components/schemas/Body_handler_users_post"
# Ensure that the custom body schema actually points to the real user class
components = schema.components
assert "Body_handler_users_post" in components.schemas
body_post_handler_schema = components.schemas["Body_handler_users_post"]
assert body_post_handler_schema.properties["user"].ref == "#/components/schemas/User"
def test_openapi_with_body_description():
app = APIGatewayRestResolver()
class User(BaseModel):
name: str
@app.post("/users")
def handler(user: Annotated[User, Body(description="This is a user")]):
print(user)
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 1
post = schema.paths["/users"].post
assert post.parameters is None
assert post.requestBody is not None
request_body = post.requestBody
# Description should appear in two places: on the request body and on the schema
assert request_body.description == "This is a user"
assert request_body.content[JSON_CONTENT_TYPE].schema_.description == "This is a user"
def test_openapi_with_deprecated_operations():
app = APIGatewayRestResolver()
@app.get("/", deprecated=True)
def handler():
raise NotImplementedError()
schema = app.get_openapi_schema()
get = schema.paths["/"].get
assert get.deprecated is True
def test_openapi_with_excluded_operations():
app = APIGatewayRestResolver()
@app.get("/secret", include_in_schema=False)
def secret():
return "password"
schema = app.get_openapi_schema()
assert len(schema.paths.keys()) == 0
def test_openapi_with_router_response():
router = Router()
@router.put("/example-resource", responses={200: {"description": "Custom response"}})
def handler():
pass
app = APIGatewayRestResolver(enable_validation=True)
app.include_router(router)
schema = app.get_openapi_schema()
put = schema.paths["/example-resource"].put
assert 200 in put.responses.keys()
assert put.responses[200].description == "Custom response"
def test_openapi_with_router_tags():
router = Router()
@router.put("/example-resource", tags=["Example"])
def handler():
pass
app = APIGatewayRestResolver(enable_validation=True)
app.include_router(router)
schema = app.get_openapi_schema()
tags = schema.paths["/example-resource"].put.tags
assert len(tags) == 1
assert tags[0] == "Example"
def test_create_header():
header = Header(convert_underscores=True)
assert header.convert_underscores is True
def test_create_body():
body = Body(embed=True, examples=[Example(summary="Example 1", value=10)])
assert body.embed is True
# Tests that when we try to create a model without a field type, we return None
def test_create_empty_model_field():
result = _create_model_field(None, int, "name", False)
assert result is None
# Tests that when we try to crate a param model without a source, we default to "query"
def test_create_model_field_with_empty_in():
field_info = Param()
result = _create_model_field(field_info, int, "name", False)
assert result.field_info.in_ == ParamTypes.query
# Tests that when we try to create a model field with convert_underscore, we convert the field name
def test_create_model_field_convert_underscore():
field_info = Header(alias=None, convert_underscores=True)
result = _create_model_field(field_info, int, "user_id", False)
assert result.alias == "user-id"
def test_openapi_with_example_as_list():
app = APIGatewayRestResolver()
@app.get("/users", summary="Get Users", operation_id="GetUsers", description="Get paginated users", tags=["Users"])
def handler(
count: Annotated[
int,
Query(gt=0, lt=100, examples=["Example 1"]),
] = 1,
):
print(count)
raise NotImplementedError()
schema = app.get_openapi_schema()
get = schema.paths["/users"].get
assert len(get.parameters) == 1
assert get.summary == "Get Users"
assert get.operationId == "GetUsers"
assert get.description == "Get paginated users"
assert get.tags == ["Users"]
parameter = get.parameters[0]
assert parameter.required is False
assert parameter.name == "count"
assert parameter.in_ == ParameterInType.query
assert parameter.schema_.type == "integer"
assert parameter.schema_.default == 1
assert parameter.schema_.title == "Count"
assert parameter.schema_.exclusiveMinimum == 0
assert parameter.schema_.exclusiveMaximum == 100
assert len(parameter.schema_.examples) == 1
assert parameter.schema_.examples[0] == "Example 1"
def test_openapi_with_examples_of_base_model_field():
app = APIGatewayRestResolver()
class Todo(BaseModel):
id: int = Field(examples=[1])
title: str = Field(examples=["Example 1"])
priority: float = Field(examples=[0.5])
completed: bool = Field(examples=[True])
@app.get("/")
def handler() -> Todo:
return Todo(id=0, title="", priority=0.0, completed=False)
schema = app.get_openapi_schema()
assert "Todo" in schema.components.schemas
todo_schema = schema.components.schemas["Todo"]
assert isinstance(todo_schema, Schema)
assert "id" in todo_schema.properties
id_property = todo_schema.properties["id"]
assert id_property.examples == [1]
assert "title" in todo_schema.properties
title_property = todo_schema.properties["title"]
assert title_property.examples == ["Example 1"]
assert "priority" in todo_schema.properties
priority_property = todo_schema.properties["priority"]
assert priority_property.examples == [0.5]
assert "completed" in todo_schema.properties
completed_property = todo_schema.properties["completed"]
assert completed_property.examples == [True]