forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_api_gateway.py
582 lines (454 loc) · 19.2 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
import base64
import json
import zlib
from decimal import Decimal
from pathlib import Path
from typing import Dict
from aws_lambda_powertools.event_handler.api_gateway import (
APPLICATION_JSON,
ApiGatewayResolver,
BadRequestError,
CORSConfig,
InternalServerError,
NotFoundError,
ProxyEventType,
Response,
ResponseBuilder,
ServiceError,
UnauthorizedError,
)
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")
TEXT_HTML = "text/html"
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, 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"] == 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, 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"] == 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, 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"] == 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, "plain/text", 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"] == "plain/text"
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, TEXT_HTML, my_id)
# WHEN calling the event handler
result = app(LOAD_GW_EVENT, {})
# THEN
assert result["statusCode"] == 200
assert result["headers"]["Content-Type"] == 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, TEXT_HTML, "test")
@app.get("/without-cors")
def without_cors() -> Response:
return Response(200, 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"] == 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, 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, "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, 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"] == 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, 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"] == 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"] == 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"] == 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=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"] == 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"] == 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"] == 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"] == 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"] == 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"] == APPLICATION_JSON
assert "Access-Control-Allow-Origin" in result["headers"]
expected = {"statusCode": 502, "message": "Something went wrong!"}
assert result["body"] == json_dump(expected)