forked from zappa/Zappa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_handler.py
398 lines (334 loc) · 13.6 KB
/
test_handler.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
import sys
import unittest
from mock import Mock
from zappa.handler import LambdaHandler
from zappa.utilities import merge_headers
def no_args():
return
def one_arg(first):
return first
def two_args(first, second):
return first, second
def var_args(*args):
return args
def var_args_with_one(first, *args):
return first, args[0]
def unsupported(first, second, third):
return first, second, third
def raises_exception(*args, **kwargs):
raise Exception("app exception")
def handle_bot_intent(event, context):
return "Success"
mocked_exception_handler = Mock()
class TestZappa(unittest.TestCase):
def setUp(self):
mocked_exception_handler.reset_mock()
def tearDown(self):
LambdaHandler._LambdaHandler__instance = None
LambdaHandler.settings = None
LambdaHandler.settings_name = None
def test_run_function(self):
self.assertIsNone(LambdaHandler.run_function(no_args, "e", "c"))
self.assertEqual(LambdaHandler.run_function(one_arg, "e", "c"), "e")
self.assertEqual(LambdaHandler.run_function(two_args, "e", "c"), ("e", "c"))
self.assertEqual(LambdaHandler.run_function(var_args, "e", "c"), ("e", "c"))
self.assertEqual(
LambdaHandler.run_function(var_args_with_one, "e", "c"), ("e", "c")
)
try:
LambdaHandler.run_function(unsupported, "e", "c")
self.fail("Exception expected")
except RuntimeError as e:
pass
def test_run_fuction_with_type_hint(self):
scope = {}
exec("def f_with_type_hint() -> None: return", scope)
f_with_type_hint = scope["f_with_type_hint"]
self.assertIsNone(LambdaHandler.run_function(f_with_type_hint, "e", "c"))
def test_wsgi_script_name_on_aws_url(self):
"""
Ensure that requests to the amazonaws.com host for an API with a
domain have the correct request.url
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"body": "",
"resource": "/{proxy+}",
"requestContext": {},
"queryStringParameters": {},
"headers": {
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
},
"pathParameters": {"proxy": "return/request/url"},
"httpMethod": "GET",
"stageVariables": {},
"path": "/return/request/url",
}
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 200)
self.assertEqual(
response["body"],
"https://1234567890.execute-api.us-east-1.amazonaws.com/dev/return/request/url",
)
def test_wsgi_script_name_on_domain_url(self):
"""
Ensure that requests to the amazonaws.com host for an API with a
domain have the correct request.url
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"body": "",
"resource": "/{proxy+}",
"requestContext": {},
"queryStringParameters": {},
"headers": {
"Host": "example.com",
},
"pathParameters": {"proxy": "return/request/url"},
"httpMethod": "GET",
"stageVariables": {},
"path": "/return/request/url",
}
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 200)
self.assertEqual(response["body"], "https://example.com/return/request/url")
def test_wsgi_script_name_with_multi_value_header(self):
"""
Ensure that requests generated with multivalued headers (such as
from an ALB with Multi Valued Headers enabled) succeed.
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"body": "",
"resource": "/{proxy+}",
"requestContext": {},
"queryStringParameters": {},
"multiValueHeaders": {
"Host": ["example.com"],
},
"pathParameters": {"proxy": "return/request/url"},
"httpMethod": "GET",
"stageVariables": {},
"path": "/return/request/url",
}
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 200)
self.assertIn("multiValueHeaders", response)
def test_wsgi_script_name_with_multi_value_querystring(self):
"""
Ensure that requests generated with multivalue querystrings succeed.
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"body": "",
"resource": "/{proxy+}",
"requestContext": {},
"multiValueQueryStringParameters": {"multi": ["value", "qs"]},
"multiValueHeaders": {
"Host": ["example.com"],
},
"pathParameters": {"proxy": "return/request/url"},
"httpMethod": "GET",
"stageVariables": {},
"path": "/return/request/url",
}
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 200)
self.assertEqual(
response["body"],
"https://example.com/return/request/url?multi=value&multi=qs",
)
def test_wsgi_script_name_on_test_request(self):
"""
Ensure that requests sent by the "Send test request" button behaves
sensibly
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"body": "",
"resource": "/{proxy+}",
"requestContext": {},
"queryStringParameters": {},
"headers": {},
"pathParameters": {"proxy": "return/request/url"},
"httpMethod": "GET",
"stageVariables": {},
"path": "/return/request/url",
}
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 200)
self.assertEqual(response["body"], "https://zappa:80/return/request/url")
def test_exception_handler_on_web_request(self):
"""
Ensure that app exceptions triggered by web requests use the exception_handler.
"""
lh = LambdaHandler("tests.test_exception_handler_settings")
event = {
"body": "",
"resource": "/{proxy+}",
"requestContext": {},
"queryStringParameters": {},
"headers": {
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
},
"pathParameters": {"proxy": "return/request/url"},
"httpMethod": "GET",
"stageVariables": {},
"path": "/return/request/url",
}
mocked_exception_handler.assert_not_called()
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 500)
mocked_exception_handler.assert_called()
def test_wsgi_script_on_cognito_event_request(self):
"""
Ensure that requests sent by cognito behave sensibly
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"version": "1",
"region": "eu-west-1",
"userPoolId": "region_poolID",
"userName": "uuu-id-here",
"callerContext": {
"awsSdkVersion": "aws-sdk-js-2.149.0",
"clientId": "client-id-here",
},
"triggerSource": "PreSignUp_SignUp",
"request": {
"userAttributes": {"email": "[email protected]"},
"validationData": None,
},
"response": {
"autoConfirmUser": False,
"autoVerifyEmail": False,
"autoVerifyPhone": False,
},
}
response = lh.handler(event, None)
self.assertEqual(response["response"]["autoConfirmUser"], False)
def test_bot_triggered_event(self):
"""
Ensure that bot triggered events are handled as in the settings
"""
lh = LambdaHandler("tests.test_bot_handler_being_triggered")
# from : https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-lex
event = {
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "user-id specified in the POST request to Amazon Lex.",
"sessionAttributes": {
"key1": "value1",
"key2": "value2",
},
"bot": {"name": "bot-name", "alias": "bot-alias", "version": "bot-version"},
"outputDialogMode": "Text or Voice, based on ContentType request header in runtime API request",
"currentIntent": {
"name": "intent-name",
"slots": {
"slot-name": "value",
"slot-name": "value",
"slot-name": "value",
},
"confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)",
},
}
response = lh.handler(event, None)
self.assertEqual(response, "Success")
def test_exception_in_bot_triggered_event(self):
"""
Ensure that bot triggered exceptions are handled as defined in the settings.
"""
lh = LambdaHandler("tests.test_bot_exception_handler_settings")
# from : https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-lex
event = {
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "user-id specified in the POST request to Amazon Lex.",
"sessionAttributes": {
"key1": "value1",
"key2": "value2",
},
"bot": {"name": "bot-name", "alias": "bot-alias", "version": "bot-version"},
"outputDialogMode": "Text or Voice, based on ContentType request header in runtime API request",
"currentIntent": {
"name": "intent-name",
"slots": {
"slot-name": "value",
"slot-name": "value",
"slot-name": "value",
},
"confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)",
},
}
response = lh.lambda_handler(event, None)
mocked_exception_handler.assert_called
def test_wsgi_script_name_on_alb_event(self):
"""
Ensure ALB-triggered events are properly handled by LambdaHandler
ALB-forwarded events have a slightly different request structure than API-Gateway
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
"""
lh = LambdaHandler("tests.test_wsgi_script_name_settings")
event = {
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:region:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09"
}
},
"httpMethod": "GET",
"path": "/return/request/url",
"queryStringParameters": {},
"headers": {
"accept": "text/html,application/xhtml+xml",
"accept-language": "en-US,en;q=0.8",
"content-type": "text/plain",
"cookie": "cookies",
"host": "1234567890.execute-api.us-east-1.amazonaws.com",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)",
"x-amzn-trace-id": "Root=1-5bdb40ca-556d8b0c50dc66f0511bf520",
"x-forwarded-for": "72.21.198.66",
"x-forwarded-port": "443",
"x-forwarded-proto": "https",
},
"isBase64Encoded": False,
"body": "",
}
response = lh.handler(event, None)
self.assertEqual(response["statusCode"], 200)
self.assertEqual(response["statusDescription"], "200 OK")
self.assertEqual(response["isBase64Encoded"], False)
self.assertEqual(
response["body"],
"https://1234567890.execute-api.us-east-1.amazonaws.com/return/request/url",
)
def test_merge_headers_no_multi_value(self):
event = {"headers": {"a": "b"}}
merged = merge_headers(event)
self.assertEqual(merged["a"], "b")
def test_merge_headers_combine_values(self):
event = {
"headers": {"a": "b", "z": "q"},
"multiValueHeaders": {"a": ["c"], "x": ["y"]},
}
merged = merge_headers(event)
self.assertEqual(merged["a"], "c")
self.assertEqual(merged["x"], "y")
self.assertEqual(merged["z"], "q")
def test_merge_headers_no_single_value(self):
event = {"multiValueHeaders": {"a": ["c", "d"], "x": ["y", "z", "f"]}}
merged = merge_headers(event)
self.assertEqual(merged["a"], "c, d")
self.assertEqual(merged["x"], "y, z, f")
def test_cloudwatch_subscription_event(self):
"""
Test that events sent in the format used by CloudWatch logs via
subscription filters are handled properly.
The actual payload that Lambda receives is in the following format
{ "awslogs": {"data": "BASE64ENCODED_GZIP_COMPRESSED_DATA"} }
https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html
"""
lh = LambdaHandler("tests.test_event_script_settings")
event = {"awslogs": {"data": "some-data-not-important-for-test"}}
response = lh.handler(event, None)
self.assertEqual(response, True)