-
Notifications
You must be signed in to change notification settings - Fork 473
Expand file tree
/
Copy pathtest_openapi_params.py
More file actions
1653 lines (1257 loc) · 50.6 KB
/
test_openapi_params.py
File metadata and controls
1653 lines (1257 loc) · 50.6 KB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional, Tuple
import pytest
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,
Form,
Header,
Param,
ParamTypes,
Query,
_create_model_field,
)
JSON_CONTENT_TYPE = "application/json"
def test_openapi_pydantic_query_params():
"""Test that Pydantic models in Query parameters are expanded into individual fields in OpenAPI schema"""
app = APIGatewayRestResolver()
class QueryParams(BaseModel):
limit: int = Field(default=10, ge=1, le=100, description="Number of items to return")
offset: int = Field(default=0, ge=0, description="Number of items to skip")
search: Optional[str] = Field(default=None, description="Search term")
@app.get("/search")
def search_handler(params: Annotated[QueryParams, Query()]):
return {"message": "success"}
schema = app.get_openapi_schema()
# Check that the path exists
assert "/search" in schema.paths
path = schema.paths["/search"]
assert path.get is not None
# Check that parameters are expanded
get_operation = path.get
assert get_operation.parameters is not None
assert len(get_operation.parameters) == 3
# Check individual parameters
param_names = [param.name for param in get_operation.parameters]
assert "limit" in param_names
assert "offset" in param_names
assert "search" in param_names
# Check parameter details
for param in get_operation.parameters:
assert param.in_ == ParameterInType.query
if param.name == "limit":
assert param.required is False # Has default value
assert param.description == "Number of items to return"
assert param.schema_.type == "integer"
elif param.name == "offset":
assert param.required is False # Has default value
assert param.description == "Number of items to skip"
assert param.schema_.type == "integer"
elif param.name == "search":
assert param.required is False # Optional field
assert param.description == "Search term"
assert param.schema_.type == "string"
def test_openapi_pydantic_header_params():
"""Test that Pydantic models in Header parameters are expanded into individual fields in OpenAPI schema"""
app = APIGatewayRestResolver()
class HeaderParams(BaseModel):
authorization: str = Field(description="Authorization token")
user_agent: str = Field(default="PowerTools/1.0", description="User agent")
language: Optional[str] = Field(default=None, alias="accept-language", description="Language preference")
@app.get("/protected")
def protected_handler(headers: Annotated[HeaderParams, Header()]):
return {"message": "success"}
schema = app.get_openapi_schema()
# Check that the path exists
assert "/protected" in schema.paths
path = schema.paths["/protected"]
assert path.get is not None
# Check that parameters are expanded
get_operation = path.get
assert get_operation.parameters is not None
assert len(get_operation.parameters) == 3
# Check individual parameters
param_names = [param.name for param in get_operation.parameters]
assert "authorization" in param_names
assert "user-agent" in param_names # headers are always spinal-case
assert "accept-language" in param_names # Should use alias
# Check parameter details
for param in get_operation.parameters:
assert param.in_ == ParameterInType.header
if param.name == "authorization":
assert param.required is True # No default value
assert param.description == "Authorization token"
assert param.schema_.type == "string"
elif param.name == "user_agent":
assert param.required is False # Has default value
assert param.description == "User agent"
assert param.schema_.type == "string"
elif param.name == "accept-language":
assert param.required is False # Optional field
assert param.description == "Language preference"
assert param.schema_.type == "string"
def test_openapi_pydantic_mixed_params():
"""Test that mixed Pydantic models (Query + Header) work together"""
app = APIGatewayRestResolver()
class QueryParams(BaseModel):
q: str = Field(description="Search query")
limit: int = Field(default=10, description="Number of results")
class HeaderParams(BaseModel):
authorization: str = Field(description="Bearer token")
@app.get("/mixed")
def mixed_handler(query: Annotated[QueryParams, Query()], headers: Annotated[HeaderParams, Header()]):
return {"message": "success"}
schema = app.get_openapi_schema()
# Check that the path exists
assert "/mixed" in schema.paths
path = schema.paths["/mixed"]
assert path.get is not None
# Check that all parameters are expanded
get_operation = path.get
assert get_operation.parameters is not None
assert len(get_operation.parameters) == 3 # 2 query + 1 header
# Check parameter types
query_params = [p for p in get_operation.parameters if p.in_ == ParameterInType.query]
header_params = [p for p in get_operation.parameters if p.in_ == ParameterInType.header]
assert len(query_params) == 2
assert len(header_params) == 1
# Check specific parameters
query_names = [p.name for p in query_params]
assert "q" in query_names
assert "limit" in query_names
header_names = [p.name for p in header_params]
assert "authorization" in header_names
def test_openapi_no_params():
app = APIGatewayRestResolver()
@app.get("/")
def handler():
raise NotImplementedError()
schema = app.get_openapi_schema()
assert schema.info.title == "Powertools for AWS Lambda (Python) 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_tuple_returns():
app = APIGatewayRestResolver()
@app.get("/")
def handler() -> Tuple[str, int]:
return "Hello, world", 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 == "Return"
assert response.schema_.type == "string"
def test_openapi_with_tuple_annotated_returns():
app = APIGatewayRestResolver()
@app.get("/")
def handler() -> Tuple[Annotated[str, Body(title="Response title")], int]:
return "Hello, world", 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="Powertools")
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_body_examples():
app = APIGatewayRestResolver()
first_example = Example(summary="Example1", description="Example1", value={"name": "Alice"})
second_example = Example(summary="Example2", description="Example2", value={"name": "Bob"})
class User(BaseModel):
name: str
@app.post("/users")
def handler(
user: Annotated[
User,
Body(
openapi_examples={
"example1": first_example,
"example2": second_example,
},
),
],
):
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
# Examples should appear in the request_body content schema
request_body_examples = request_body.content[JSON_CONTENT_TYPE].examples
assert request_body_examples["example1"] == first_example
assert request_body_examples["example2"] == second_example
def test_openapi_with_deprecated_operations():
app = APIGatewayRestResolver()
@app.get("/", deprecated=True)
def _get():
raise NotImplementedError()
@app.post("/", deprecated=True)
def _post():
raise NotImplementedError()
schema = app.get_openapi_schema()
get = schema.paths["/"].get
assert get.deprecated is True
post = schema.paths["/"].post
assert post.deprecated is True
def test_openapi_without_deprecated_operations():
app = APIGatewayRestResolver()
@app.get("/")
def _get():
raise NotImplementedError()
@app.post("/", deprecated=False)
def _post():
raise NotImplementedError()
schema = app.get_openapi_schema()
get = schema.paths["/"].get
assert get.deprecated is None
post = schema.paths["/"].post
assert post.deprecated is None
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]
def test_openapi_with_openapi_example():
app = APIGatewayRestResolver()
first_example = Example(summary="Example1", description="Example1", value="a")
second_example = Example(summary="Example2", description="Example2", value="b")
@app.get("/users", summary="Get Users", operation_id="GetUsers", description="Get paginated users", tags=["Users"])
def handler(
count: Annotated[
int,
Query(
openapi_examples={
"first_example": first_example,
"second_example": second_example,
},
),
] = 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.examples["first_example"] == first_example
assert parameter.examples["second_example"] == second_example
assert parameter.in_ == ParameterInType.query
assert parameter.schema_.type == "integer"
assert parameter.schema_.default == 1
assert parameter.schema_.title == "Count"
def test_openapi_form_only_parameters():
"""Test Form parameters generate application/x-www-form-urlencoded content type."""
app = APIGatewayRestResolver(enable_validation=True)
@app.post("/form-data")
def create_form_data(
name: Annotated[str, Form(description="User name")],
email: Annotated[str, Form(description="User email")] = "test@example.com",
):
return {"name": name, "email": email}
schema = app.get_openapi_schema()
# Check that the endpoint is present
assert "/form-data" in schema.paths
post_op = schema.paths["/form-data"].post
assert post_op is not None
# Check request body
request_body = post_op.requestBody
assert request_body is not None
# Check content type is application/x-www-form-urlencoded
assert "application/x-www-form-urlencoded" in request_body.content
# Get the schema reference
form_content = request_body.content["application/x-www-form-urlencoded"]
assert form_content.schema_ is not None
# Check that it references a component schema
schema_ref = form_content.schema_.ref
assert schema_ref is not None
assert schema_ref.startswith("#/components/schemas/")
# Get the component schema
component_name = schema_ref.split("/")[-1]
assert component_name in schema.components.schemas
component_schema = schema.components.schemas[component_name]
properties = component_schema.properties
# Check form parameters
assert "name" in properties
name_prop = properties["name"]
assert name_prop.type == "string"
assert name_prop.description == "User name"
assert "email" in properties
email_prop = properties["email"]
assert email_prop.type == "string"
assert email_prop.description == "User email"
assert email_prop.default == "test@example.com"
# Check required fields (only name should be required since email has default)
assert component_schema.required == ["name"]
def test_openapi_mixed_body_media_types():
"""Test mixed Body parameters with different media types."""
class UserData(BaseModel):
name: str
email: str
app = APIGatewayRestResolver(enable_validation=True)
@app.post("/mixed-body")
def mixed_body_endpoint(user_data: Annotated[UserData, Body(media_type="application/json")]):
return {"status": "created"}
schema = app.get_openapi_schema()
# Check that the endpoint uses the specified media type
assert "/mixed-body" in schema.paths
post_op = schema.paths["/mixed-body"].post
request_body = post_op.requestBody
# Should use the specified media type
assert "application/json" in request_body.content
def test_openapi_form_parameter_edge_cases():
"""Test Form parameters with various edge cases."""
app = APIGatewayRestResolver(enable_validation=True)
@app.post("/form-edge-cases")
def form_edge_cases(
required_field: Annotated[str, Form(description="Required field")],
optional_field: Annotated[Optional[str], Form(description="Optional field")] = None,
field_with_default: Annotated[str, Form(description="Field with default")] = "default_value",
):
return {"required": required_field, "optional": optional_field, "default": field_with_default}
schema = app.get_openapi_schema()
# Check that the endpoint is present
assert "/form-edge-cases" in schema.paths
post_op = schema.paths["/form-edge-cases"].post
request_body = post_op.requestBody
# Should use application/x-www-form-urlencoded for form-only parameters
assert "application/x-www-form-urlencoded" in request_body.content
# Get the component schema
form_content = request_body.content["application/x-www-form-urlencoded"]
schema_ref = form_content.schema_.ref
component_name = schema_ref.split("/")[-1]
component_schema = schema.components.schemas[component_name]
properties = component_schema.properties
# Check all fields are present
assert "required_field" in properties
assert "optional_field" in properties
assert "field_with_default" in properties
# Check required vs optional handling
assert "required_field" in component_schema.required
assert "optional_field" not in component_schema.required # Optional
assert "field_with_default" not in component_schema.required # Has default
def test_openapi_pydantic_query_with_constraints():
"""Test that Pydantic field constraints are preserved in OpenAPI schema"""
app = APIGatewayRestResolver()
class QueryParams(BaseModel):
limit: int = Field(ge=1, le=100, description="Number of items")
name: str = Field(min_length=1, max_length=50, description="Name filter")
@app.get("/items")
def get_items(params: Annotated[QueryParams, Query()]):
return {"message": "success"}
schema = app.get_openapi_schema()
path = schema.paths["/items"]
get_operation = path.get
# Find the limit parameter
limit_param = next(p for p in get_operation.parameters if p.name == "limit")
assert limit_param.schema_.type == "integer"
assert limit_param.description == "Number of items"
# Find the name parameter
name_param = next(p for p in get_operation.parameters if p.name == "name")
assert name_param.schema_.type == "string"
assert name_param.description == "Name filter"
def test_openapi_pydantic_header_with_alias():
"""Test that Pydantic field aliases work correctly in Header parameters"""
app = APIGatewayRestResolver()
class HeaderParams(BaseModel):
content_type: str = Field(alias="content-type", description="Content type")
user_agent: str = Field(alias="user-agent", description="User agent")
@app.get("/test")
def test_handler(headers: Annotated[HeaderParams, Header()]):
return {"message": "success"}
schema = app.get_openapi_schema()