forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_api_gateway.py
862 lines (669 loc) · 27.7 KB
/
test_api_gateway.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
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
import base64
import json
import zlib
from copy import deepcopy
from decimal import Decimal
from enum import Enum
from json import JSONEncoder
from pathlib import Path
from typing import Dict
import pytest
from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.api_gateway import (
ApiGatewayResolver,
CORSConfig,
ProxyEventType,
Response,
ResponseBuilder,
)
from aws_lambda_powertools.event_handler.exceptions import (
BadRequestError,
InternalServerError,
NotFoundError,
ServiceError,
UnauthorizedError,
)
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.json_encoder import Encoder
from aws_lambda_powertools.utilities.data_classes import ALBEvent, APIGatewayProxyEvent, APIGatewayProxyEventV2
from tests.functional.utils import load_event
def read_media(file_name: str) -> bytes:
path = Path(str(Path(__file__).parent.parent.parent.parent) + "/docs/media/" + file_name)
return path.read_bytes()
LOAD_GW_EVENT = load_event("apiGatewayProxyEvent.json")
def test_alb_event():
# GIVEN a Application Load Balancer proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.ALBEvent)
@app.get("/lambda")
def foo():
assert isinstance(app.current_event, ALBEvent)
assert app.lambda_context == {}
return Response(200, content_types.TEXT_HTML, "foo")
# WHEN calling the event handler
result = app(load_event("albEvent.json"), {})
# THEN process event correctly
# AND set the current_event type as ALBEvent
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.TEXT_HTML
assert result["body"] == "foo"
def test_api_gateway_v1():
# GIVEN a Http API V1 proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
@app.get("/my/path")
def get_lambda() -> Response:
assert isinstance(app.current_event, APIGatewayProxyEvent)
assert app.lambda_context == {}
return Response(200, content_types.APPLICATION_JSON, json.dumps({"foo": "value"}))
# WHEN calling the event handler
result = app(LOAD_GW_EVENT, {})
# THEN process event correctly
# AND set the current_event type as APIGatewayProxyEvent
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
def test_api_gateway():
# GIVEN a Rest API Gateway proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
@app.get("/my/path")
def get_lambda() -> Response:
assert isinstance(app.current_event, APIGatewayProxyEvent)
return Response(200, content_types.TEXT_HTML, "foo")
# WHEN calling the event handler
result = app(LOAD_GW_EVENT, {})
# THEN process event correctly
# AND set the current_event type as APIGatewayProxyEvent
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.TEXT_HTML
assert result["body"] == "foo"
def test_api_gateway_v2():
# GIVEN a Http API V2 proxy type event
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEventV2)
@app.post("/my/path")
def my_path() -> Response:
assert isinstance(app.current_event, APIGatewayProxyEventV2)
post_data = app.current_event.json_body
return Response(200, content_types.TEXT_PLAIN, post_data["username"])
# WHEN calling the event handler
result = app(load_event("apiGatewayProxyV2Event.json"), {})
# THEN process event correctly
# AND set the current_event type as APIGatewayProxyEventV2
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.TEXT_PLAIN
assert result["body"] == "tom"
def test_include_rule_matching():
# GIVEN
app = ApiGatewayResolver()
@app.get("/<name>/<my_id>")
def get_lambda(my_id: str, name: str) -> Response:
assert name == "my"
return Response(200, content_types.TEXT_HTML, my_id)
# WHEN calling the event handler
result = app(LOAD_GW_EVENT, {})
# THEN
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.TEXT_HTML
assert result["body"] == "path"
def test_no_matches():
# GIVEN an event that does not match any of the given routes
app = ApiGatewayResolver()
@app.get("/not_matching_get")
def get_func():
raise RuntimeError()
@app.post("/no_matching_post")
def post_func():
raise RuntimeError()
@app.put("/no_matching_put")
def put_func():
raise RuntimeError()
@app.delete("/no_matching_delete")
def delete_func():
raise RuntimeError()
@app.patch("/no_matching_patch")
def patch_func():
raise RuntimeError()
def handler(event, context):
return app.resolve(event, context)
# Also check check the route configurations
routes = app._routes
assert len(routes) == 5
for route in routes:
if route.func == get_func:
assert route.method == "GET"
elif route.func == post_func:
assert route.method == "POST"
elif route.func == put_func:
assert route.method == "PUT"
elif route.func == delete_func:
assert route.method == "DELETE"
elif route.func == patch_func:
assert route.method == "PATCH"
# WHEN calling the handler
# THEN return a 404
result = handler(LOAD_GW_EVENT, None)
assert result["statusCode"] == 404
# AND cors headers are not returned
assert "Access-Control-Allow-Origin" not in result["headers"]
def test_cors():
# GIVEN a function with cors=True
# AND http method set to GET
app = ApiGatewayResolver()
@app.get("/my/path", cors=True)
def with_cors() -> Response:
return Response(200, content_types.TEXT_HTML, "test")
@app.get("/without-cors")
def without_cors() -> Response:
return Response(200, content_types.TEXT_HTML, "test")
def handler(event, context):
return app.resolve(event, context)
# WHEN calling the event handler
result = handler(LOAD_GW_EVENT, None)
# THEN the headers should include cors headers
assert "headers" in result
headers = result["headers"]
assert headers["Content-Type"] == content_types.TEXT_HTML
assert headers["Access-Control-Allow-Origin"] == "*"
assert "Access-Control-Allow-Credentials" not in headers
assert headers["Access-Control-Allow-Headers"] == ",".join(sorted(CORSConfig._REQUIRED_HEADERS))
# THEN for routes without cors flag return no cors headers
mock_event = {"path": "/my/request", "httpMethod": "GET"}
result = handler(mock_event, None)
assert "Access-Control-Allow-Origin" not in result["headers"]
def test_compress():
# GIVEN a function that has compress=True
# AND an event with a "Accept-Encoding" that include gzip
app = ApiGatewayResolver()
mock_event = {"path": "/my/request", "httpMethod": "GET", "headers": {"Accept-Encoding": "deflate, gzip"}}
expected_value = '{"test": "value"}'
@app.get("/my/request", compress=True)
def with_compression() -> Response:
return Response(200, content_types.APPLICATION_JSON, expected_value)
def handler(event, context):
return app.resolve(event, context)
# WHEN calling the event handler
result = handler(mock_event, None)
# THEN then gzip the response and base64 encode as a string
assert result["isBase64Encoded"] is True
body = result["body"]
assert isinstance(body, str)
decompress = zlib.decompress(base64.b64decode(body), wbits=zlib.MAX_WBITS | 16).decode("UTF-8")
assert decompress == expected_value
headers = result["headers"]
assert headers["Content-Encoding"] == "gzip"
def test_base64_encode():
# GIVEN a function that returns bytes
app = ApiGatewayResolver()
mock_event = {"path": "/my/path", "httpMethod": "GET", "headers": {"Accept-Encoding": "deflate, gzip"}}
@app.get("/my/path", compress=True)
def read_image() -> Response:
return Response(200, "image/png", read_media("idempotent_sequence_exception.png"))
# WHEN calling the event handler
result = app(mock_event, None)
# THEN return the body and a base64 encoded string
assert result["isBase64Encoded"] is True
body = result["body"]
assert isinstance(body, str)
headers = result["headers"]
assert headers["Content-Encoding"] == "gzip"
def test_compress_no_accept_encoding():
# GIVEN a function with compress=True
# AND the request has no "Accept-Encoding" set to include gzip
app = ApiGatewayResolver()
expected_value = "Foo"
@app.get("/my/path", compress=True)
def return_text() -> Response:
return Response(200, content_types.TEXT_PLAIN, expected_value)
# WHEN calling the event handler
result = app({"path": "/my/path", "httpMethod": "GET", "headers": {}}, None)
# THEN don't perform any gzip compression
assert result["isBase64Encoded"] is False
assert result["body"] == expected_value
def test_cache_control_200():
# GIVEN a function with cache_control set
app = ApiGatewayResolver()
@app.get("/success", cache_control="max-age=600")
def with_cache_control() -> Response:
return Response(200, content_types.TEXT_HTML, "has 200 response")
def handler(event, context):
return app.resolve(event, context)
# WHEN calling the event handler
# AND the function returns a 200 status code
result = handler({"path": "/success", "httpMethod": "GET"}, None)
# THEN return the set Cache-Control
headers = result["headers"]
assert headers["Content-Type"] == content_types.TEXT_HTML
assert headers["Cache-Control"] == "max-age=600"
def test_cache_control_non_200():
# GIVEN a function with cache_control set
app = ApiGatewayResolver()
@app.delete("/fails", cache_control="max-age=600")
def with_cache_control_has_500() -> Response:
return Response(503, content_types.TEXT_HTML, "has 503 response")
def handler(event, context):
return app.resolve(event, context)
# WHEN calling the event handler
# AND the function returns a 503 status code
result = handler({"path": "/fails", "httpMethod": "DELETE"}, None)
# THEN return a Cache-Control of "no-cache"
headers = result["headers"]
assert headers["Content-Type"] == content_types.TEXT_HTML
assert headers["Cache-Control"] == "no-cache"
def test_rest_api():
# GIVEN a function that returns a Dict
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
expected_dict = {"foo": "value", "second": Decimal("100.01")}
@app.get("/my/path")
def rest_func() -> Dict:
return expected_dict
# WHEN calling the event handler
result = app(LOAD_GW_EVENT, {})
# THEN automatically process this as a json rest api response
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
expected_str = json.dumps(expected_dict, separators=(",", ":"), indent=None, cls=Encoder)
assert result["body"] == expected_str
def test_handling_response_type():
# GIVEN a function that returns Response
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
@app.get("/my/path")
def rest_func() -> Response:
return Response(
status_code=404,
content_type="used-if-not-set-in-header",
body="Not found",
headers={"Content-Type": "header-content-type-wins", "custom": "value"},
)
# WHEN calling the event handler
result = app(LOAD_GW_EVENT, {})
# THEN the result can include some additional field control like overriding http headers
assert result["statusCode"] == 404
assert result["headers"]["Content-Type"] == "header-content-type-wins"
assert result["headers"]["custom"] == "value"
assert result["body"] == "Not found"
def test_custom_cors_config():
# GIVEN a custom cors configuration
allow_header = ["foo2"]
cors_config = CORSConfig(
allow_origin="https://foo1",
expose_headers=["foo1"],
allow_headers=allow_header,
max_age=100,
allow_credentials=True,
)
app = ApiGatewayResolver(cors=cors_config)
event = {"path": "/cors", "httpMethod": "GET"}
@app.get("/cors")
def get_with_cors():
return {}
@app.get("/another-one", cors=False)
def another_one():
return {}
# WHEN calling the event handler
result = app(event, None)
# THEN routes by default return the custom cors headers
assert "headers" in result
headers = result["headers"]
assert headers["Content-Type"] == content_types.APPLICATION_JSON
assert headers["Access-Control-Allow-Origin"] == cors_config.allow_origin
expected_allows_headers = ",".join(sorted(set(allow_header + cors_config._REQUIRED_HEADERS)))
assert headers["Access-Control-Allow-Headers"] == expected_allows_headers
assert headers["Access-Control-Expose-Headers"] == ",".join(cors_config.expose_headers)
assert headers["Access-Control-Max-Age"] == str(cors_config.max_age)
assert "Access-Control-Allow-Credentials" in headers
assert headers["Access-Control-Allow-Credentials"] == "true"
# AND custom cors was set on the app
assert isinstance(app._cors, CORSConfig)
assert app._cors is cors_config
# AND routes without cors don't include "Access-Control" headers
event = {"path": "/another-one", "httpMethod": "GET"}
result = app(event, None)
headers = result["headers"]
assert "Access-Control-Allow-Origin" not in headers
def test_no_content_response():
# GIVEN a response with no content-type or body
response = Response(status_code=204, content_type=None, body=None, headers=None)
response_builder = ResponseBuilder(response)
# WHEN calling to_dict
result = response_builder.build(APIGatewayProxyEvent(LOAD_GW_EVENT))
# THEN return an None body and no Content-Type header
assert result["statusCode"] == response.status_code
assert result["body"] is None
headers = result["headers"]
assert "Content-Type" not in headers
def test_no_matches_with_cors():
# GIVEN an event that does not match any of the given routes
# AND cors enabled
app = ApiGatewayResolver(cors=CORSConfig())
# WHEN calling the handler
result = app({"path": "/another-one", "httpMethod": "GET"}, None)
# THEN return a 404
# AND cors headers are returned
assert result["statusCode"] == 404
assert "Access-Control-Allow-Origin" in result["headers"]
assert "Not found" in result["body"]
def test_cors_preflight():
# GIVEN an event for an OPTIONS call that does not match any of the given routes
# AND cors is enabled
app = ApiGatewayResolver(cors=CORSConfig())
@app.get("/foo")
def foo_cors():
...
@app.route(method="delete", rule="/foo")
def foo_delete_cors():
...
@app.post("/foo", cors=False)
def post_no_cors():
...
# WHEN calling the handler
result = app({"path": "/foo", "httpMethod": "OPTIONS"}, None)
# THEN return no content
# AND include Access-Control-Allow-Methods of the cors methods used
assert result["statusCode"] == 204
assert result["body"] is None
headers = result["headers"]
assert "Content-Type" not in headers
assert "Access-Control-Allow-Origin" in result["headers"]
assert headers["Access-Control-Allow-Methods"] == "DELETE,GET,OPTIONS"
def test_custom_preflight_response():
# GIVEN cors is enabled
# AND we have a custom preflight method
# AND the request matches this custom preflight route
app = ApiGatewayResolver(cors=CORSConfig())
@app.route(method="OPTIONS", rule="/some-call", cors=True)
def custom_preflight():
return Response(
status_code=200,
content_type=content_types.TEXT_HTML,
body="Foo",
headers={"Access-Control-Allow-Methods": "CUSTOM"},
)
@app.route(method="CUSTOM", rule="/some-call", cors=True)
def custom_method():
...
# WHEN calling the handler
result = app({"path": "/some-call", "httpMethod": "OPTIONS"}, None)
# THEN return the custom preflight response
assert result["statusCode"] == 200
assert result["body"] == "Foo"
headers = result["headers"]
assert headers["Content-Type"] == content_types.TEXT_HTML
assert "Access-Control-Allow-Origin" in result["headers"]
assert headers["Access-Control-Allow-Methods"] == "CUSTOM"
def test_service_error_responses():
# SCENARIO handling different kind of service errors being raised
app = ApiGatewayResolver(cors=CORSConfig())
def json_dump(obj):
return json.dumps(obj, separators=(",", ":"))
# GIVEN an BadRequestError
@app.get(rule="/bad-request-error", cors=False)
def bad_request_error():
raise BadRequestError("Missing required parameter")
# WHEN calling the handler
# AND path is /bad-request-error
result = app({"path": "/bad-request-error", "httpMethod": "GET"}, None)
# THEN return the bad request error response
# AND status code equals 400
assert result["statusCode"] == 400
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
expected = {"statusCode": 400, "message": "Missing required parameter"}
assert result["body"] == json_dump(expected)
# GIVEN an UnauthorizedError
@app.get(rule="/unauthorized-error", cors=False)
def unauthorized_error():
raise UnauthorizedError("Unauthorized")
# WHEN calling the handler
# AND path is /unauthorized-error
result = app({"path": "/unauthorized-error", "httpMethod": "GET"}, None)
# THEN return the unauthorized error response
# AND status code equals 401
assert result["statusCode"] == 401
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
expected = {"statusCode": 401, "message": "Unauthorized"}
assert result["body"] == json_dump(expected)
# GIVEN an NotFoundError
@app.get(rule="/not-found-error", cors=False)
def not_found_error():
raise NotFoundError
# WHEN calling the handler
# AND path is /not-found-error
result = app({"path": "/not-found-error", "httpMethod": "GET"}, None)
# THEN return the not found error response
# AND status code equals 404
assert result["statusCode"] == 404
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
expected = {"statusCode": 404, "message": "Not found"}
assert result["body"] == json_dump(expected)
# GIVEN an InternalServerError
@app.get(rule="/internal-server-error", cors=False)
def internal_server_error():
raise InternalServerError("Internal server error")
# WHEN calling the handler
# AND path is /internal-server-error
result = app({"path": "/internal-server-error", "httpMethod": "GET"}, None)
# THEN return the internal server error response
# AND status code equals 500
assert result["statusCode"] == 500
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
expected = {"statusCode": 500, "message": "Internal server error"}
assert result["body"] == json_dump(expected)
# GIVEN an ServiceError with a custom status code
@app.get(rule="/service-error", cors=True)
def service_error():
raise ServiceError(502, "Something went wrong!")
# WHEN calling the handler
# AND path is /service-error
result = app({"path": "/service-error", "httpMethod": "GET"}, None)
# THEN return the service error response
# AND status code equals 502
assert result["statusCode"] == 502
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
assert "Access-Control-Allow-Origin" in result["headers"]
expected = {"statusCode": 502, "message": "Something went wrong!"}
assert result["body"] == json_dump(expected)
def test_debug_unhandled_exceptions_debug_on():
# GIVEN debug is enabled
# AND an unhandled exception is raised
app = ApiGatewayResolver(debug=True)
assert app._debug
@app.get("/raises-error")
def raises_error():
raise RuntimeError("Foo")
# WHEN calling the handler
result = app({"path": "/raises-error", "httpMethod": "GET"}, None)
# THEN return a 500
# AND Content-Type is set to text/plain
# AND include the exception traceback in the response
assert result["statusCode"] == 500
assert "Traceback (most recent call last)" in result["body"]
headers = result["headers"]
assert headers["Content-Type"] == content_types.TEXT_PLAIN
def test_debug_unhandled_exceptions_debug_off():
# GIVEN debug is disabled
# AND an unhandled exception is raised
app = ApiGatewayResolver(debug=False)
assert not app._debug
@app.get("/raises-error")
def raises_error():
raise RuntimeError("Foo")
# WHEN calling the handler
# THEN raise the original exception
with pytest.raises(RuntimeError) as e:
app({"path": "/raises-error", "httpMethod": "GET"}, None)
# AND include the original error
assert e.value.args == ("Foo",)
def test_debug_mode_environment_variable(monkeypatch):
# GIVEN a debug mode environment variable is set
monkeypatch.setenv(constants.EVENT_HANDLER_DEBUG_ENV, "true")
app = ApiGatewayResolver()
# WHEN calling app._debug
# THEN the debug mode is enabled
assert app._debug
def test_debug_json_formatting():
# GIVEN debug is True
app = ApiGatewayResolver(debug=True)
response = {"message": "Foo"}
@app.get("/foo")
def foo():
return response
# WHEN calling the handler
result = app({"path": "/foo", "httpMethod": "GET"}, None)
# THEN return a pretty print json in the body
assert result["body"] == json.dumps(response, indent=4)
def test_debug_print_event(capsys):
# GIVE debug is True
app = ApiGatewayResolver(debug=True)
# WHEN calling resolve
event = {"path": "/foo", "httpMethod": "GET"}
app(event, None)
# THEN print the event
out, err = capsys.readouterr()
assert json.loads(out) == event
def test_similar_dynamic_routes():
# GIVEN
app = ApiGatewayResolver()
event = deepcopy(LOAD_GW_EVENT)
# WHEN
# r'^/accounts/(?P<account_id>\\w+\\b)$' # noqa: E800
@app.get("/accounts/<account_id>")
def get_account(account_id: str):
assert account_id == "single_account"
# r'^/accounts/(?P<account_id>\\w+\\b)/source_networks$' # noqa: E800
@app.get("/accounts/<account_id>/source_networks")
def get_account_networks(account_id: str):
assert account_id == "nested_account"
# r'^/accounts/(?P<account_id>\\w+\\b)/source_networks/(?P<network_id>\\w+\\b)$' # noqa: E800
@app.get("/accounts/<account_id>/source_networks/<network_id>")
def get_network_account(account_id: str, network_id: str):
assert account_id == "nested_account"
assert network_id == "network"
# THEN
event["resource"] = "/accounts/{account_id}"
event["path"] = "/accounts/single_account"
app.resolve(event, None)
event["resource"] = "/accounts/{account_id}/source_networks"
event["path"] = "/accounts/nested_account/source_networks"
app.resolve(event, None)
event["resource"] = "/accounts/{account_id}/source_networks/{network_id}"
event["path"] = "/accounts/nested_account/source_networks/network"
app.resolve(event, {})
@pytest.mark.parametrize(
"req",
[
pytest.param(123456789, id="num"),
pytest.param("[email protected]", id="email"),
pytest.param("-._~'!*:@,;()", id="safe-rfc3986"),
pytest.param("%<>[]{}|^", id="unsafe-rfc3986"),
],
)
def test_non_word_chars_route(req):
# GIVEN
app = ApiGatewayResolver()
event = deepcopy(LOAD_GW_EVENT)
# WHEN
@app.get("/accounts/<account_id>")
def get_account(account_id: str):
assert account_id == f"{req}"
# THEN
event["resource"] = "/accounts/{account_id}"
event["path"] = f"/accounts/{req}"
ret = app.resolve(event, None)
assert ret["statusCode"] == 200
def test_custom_serializer():
# GIVEN a custom serializer to handle enums and sets
class CustomEncoder(JSONEncoder):
def default(self, data):
if isinstance(data, Enum):
return data.value
try:
iterable = iter(data)
except TypeError:
pass
else:
return sorted(iterable)
return JSONEncoder.default(self, data)
def custom_serializer(data) -> str:
return json.dumps(data, cls=CustomEncoder)
app = ApiGatewayResolver(serializer=custom_serializer)
class Color(Enum):
RED = 1
BLUE = 2
@app.get("/colors")
def get_color() -> Dict:
return {
"color": Color.RED,
"variations": {"light", "dark"},
}
# WHEN calling handler
response = app({"httpMethod": "GET", "path": "/colors"}, None)
# THEN then use the custom serializer
body = response["body"]
expected = '{"color": 1, "variations": ["dark", "light"]}'
assert expected == body
@pytest.mark.parametrize(
"path",
[
pytest.param("/pay/foo", id="path matched pay prefix"),
pytest.param("/payment/foo", id="path matched payment prefix"),
pytest.param("/foo", id="path does not start with any of the prefixes"),
],
)
def test_remove_prefix(path: str):
# GIVEN events paths `/pay/foo`, `/payment/foo` or `/foo`
# AND a configured strip_prefixes of `/pay` and `/payment`
app = ApiGatewayResolver(strip_prefixes=["/pay", "/payment"])
@app.get("/pay/foo")
def pay_foo():
raise ValueError("should not be matching")
@app.get("/foo")
def foo():
...
# WHEN calling handler
response = app({"httpMethod": "GET", "path": path}, None)
# THEN a route for `/foo` should be found
assert response["statusCode"] == 200
@pytest.mark.parametrize(
"prefix",
[
pytest.param("/foo", id="String are not supported"),
pytest.param({"/foo"}, id="Sets are not supported"),
pytest.param({"foo": "/foo"}, id="Dicts are not supported"),
pytest.param(tuple("/foo"), id="Tuples are not supported"),
pytest.param([None, 1, "", False], id="List of invalid values"),
],
)
def test_ignore_invalid(prefix):
# GIVEN an invalid prefix
app = ApiGatewayResolver(strip_prefixes=prefix)
@app.get("/foo/status")
def foo():
...
# WHEN calling handler
response = app({"httpMethod": "GET", "path": "/foo/status"}, None)
# THEN a route for `/foo/status` should be found
# so no prefix was stripped from the request path
assert response["statusCode"] == 200
def test_api_gateway_v2_raw_path():
# GIVEN a Http API V2 proxy type event
# AND a custom stage name "dev" and raw path "/dev/foo"
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEventV2)
event = {"rawPath": "/dev/foo", "requestContext": {"http": {"method": "GET"}, "stage": "dev"}}
@app.get("/foo")
def foo():
return {}
# WHEN calling the event handler
# WITH a route "/foo"
result = app(event, {})
# THEN process event correctly
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
def test_api_gateway_request_path_equals_strip_prefix():
# GIVEN a strip_prefix matches the request path
app = ApiGatewayResolver(strip_prefixes=["/foo"])
event = {"httpMethod": "GET", "path": "/foo"}
@app.get("/")
def base():
return {}
# WHEN calling the event handler
# WITH a route "/"
result = app(event, {})
# THEN process event correctly
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON