-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtest_package.py
More file actions
2088 lines (1898 loc) · 80.9 KB
/
Copy pathtest_package.py
File metadata and controls
2088 lines (1898 loc) · 80.9 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 os
import json
import mock
import pytest
from chalice.config import Config
from chalice import package
from chalice.constants import LAMBDA_TRUST_POLICY
from chalice.deploy.appgraph import ApplicationGraphBuilder, DependencyBuilder
from chalice.awsclient import TypedAWSClient
from chalice.deploy.deployer import BuildStage
from chalice.deploy import models
from chalice.deploy.swagger import SwaggerGenerator
from chalice.package import PackageOptions
from chalice.utils import OSUtils
@pytest.fixture
def mock_swagger_generator():
return mock.Mock(spec=SwaggerGenerator)
def test_can_create_app_packager():
config = Config()
options = PackageOptions(mock.Mock(spec=TypedAWSClient))
packager = package.create_app_packager(config, options)
assert isinstance(packager, package.AppPackager)
def test_can_create_terraform_app_packager():
config = Config()
options = PackageOptions(mock.Mock(spec=TypedAWSClient))
packager = package.create_app_packager(config, options, 'terraform')
assert isinstance(packager, package.AppPackager)
def test_template_post_processor_moves_files_once():
mock_osutils = mock.Mock(spec=OSUtils)
p = package.SAMCodeLocationPostProcessor(mock_osutils)
template = {
'Resources': {
'foo': {
'Type': 'AWS::Serverless::Function',
'Properties': {
'CodeUri': 'old-dir.zip',
}
},
'bar': {
'Type': 'AWS::Serverless::Function',
'Properties': {
'CodeUri': 'old-dir.zip',
}
},
}
}
p.process(template, config=None,
outdir='outdir', chalice_stage_name='dev')
mock_osutils.copy.assert_called_with(
'old-dir.zip', os.path.join('outdir', 'deployment.zip'))
assert mock_osutils.copy.call_count == 1
assert template['Resources']['foo']['Properties']['CodeUri'] == (
'./deployment.zip'
)
assert template['Resources']['bar']['Properties']['CodeUri'] == (
'./deployment.zip'
)
def test_terraform_post_processor_moves_files_once():
mock_osutils = mock.Mock(spec=OSUtils)
p = package.TerraformCodeLocationPostProcessor(mock_osutils)
template = {
'resource': {
'aws_lambda_function': {
'foo': {'filename': 'old-dir.zip'},
'bar': {'filename': 'old-dir.zip'},
}
}
}
p.process(template, config=None,
outdir='outdir', chalice_stage_name='dev')
mock_osutils.copy.assert_called_with(
'old-dir.zip', os.path.join('outdir', 'deployment.zip'))
assert mock_osutils.copy.call_count == 1
assert template['resource']['aws_lambda_function'][
'foo']['filename'] == ('${path.module}/deployment.zip')
assert template['resource']['aws_lambda_function'][
'bar']['filename'] == ('${path.module}/deployment.zip')
def test_template_generator_default():
tgen = package.TemplateGenerator(Config(),
PackageOptions(
mock.Mock(spec=TypedAWSClient)
))
with pytest.raises(package.UnsupportedFeatureError):
tgen.dispatch(models.Model(), {})
class TestTemplateMergePostProcessor(object):
def _test_can_call_merge(self, file_template, template_name):
mock_osutils = mock.Mock(spec=OSUtils)
mock_osutils.get_file_contents.return_value = json.dumps(file_template)
mock_merger = mock.Mock(spec=package.TemplateMerger)
mock_merger.merge.return_value = {}
p = package.TemplateMergePostProcessor(
mock_osutils, mock_merger, package.JSONTemplateSerializer(),
merge_template=template_name)
template = {
'Resources': {
'foo': {
'Type': 'AWS::Serverless::Function',
'Properties': {
'CodeUri': 'old-dir.zip',
}
},
'bar': {
'Type': 'AWS::Serverless::Function',
'Properties': {
'CodeUri': 'old-dir.zip',
}
},
}
}
config = mock.MagicMock(spec=Config)
p.process(
template, config=config, outdir='outdir', chalice_stage_name='dev')
assert mock_osutils.file_exists.call_count == 1
assert mock_osutils.get_file_contents.call_count == 1
mock_merger.merge.assert_called_once_with(file_template, template)
def test_can_call_merge(self):
file_template = {
"Resources": {
"foo": {
"Properties": {
"Environment": {
"Variables": {"Name": "Foo"}
}
}
}
}
}
self._test_can_call_merge(file_template, 'extras.json')
def test_can_call_merge_with_yaml(self):
file_template = '''
Resources:
foo:
Properties:
Environment:
Variables:
Name: Foo
'''
self._test_can_call_merge(file_template, 'extras.yaml')
def test_raise_on_bad_json(self):
mock_osutils = mock.Mock(spec=OSUtils)
mock_osutils.get_file_contents.return_value = (
'{'
' "Resources": {'
' "foo": {'
' "Properties": {'
' "Environment": {'
' "Variables": {"Name": "Foo"}'
''
)
mock_merger = mock.Mock(spec=package.TemplateMerger)
p = package.TemplateMergePostProcessor(
mock_osutils, mock_merger, package.JSONTemplateSerializer(),
merge_template='extras.json')
template = {}
config = mock.MagicMock(spec=Config)
with pytest.raises(RuntimeError) as e:
p.process(
template,
config=config,
outdir='outdir',
chalice_stage_name='dev',
)
assert str(e.value).startswith('Expected')
assert 'to be valid JSON template' in str(e.value)
assert mock_merger.merge.call_count == 0
def test_raise_on_bad_yaml(self):
mock_osutils = mock.Mock(spec=OSUtils)
mock_osutils.get_file_contents.return_value = (
'---'
'Resources:'
' foo:'
' Properties:'
' Environment:'
' - 123'
''
)
mock_merger = mock.Mock(spec=package.TemplateMerger)
p = package.TemplateMergePostProcessor(
mock_osutils, mock_merger, package.YAMLTemplateSerializer(),
merge_template='extras.yaml')
template = {}
config = mock.MagicMock(spec=Config)
with pytest.raises(RuntimeError) as e:
p.process(
template,
config=config,
outdir='outdir',
chalice_stage_name='dev',
)
assert str(e.value).startswith('Expected')
assert 'to be valid YAML template' in str(e.value)
assert mock_merger.merge.call_count == 0
def test_raise_if_file_does_not_exist(self):
mock_osutils = mock.Mock(spec=OSUtils)
mock_osutils.file_exists.return_value = False
mock_merger = mock.Mock(spec=package.TemplateMerger)
p = package.TemplateMergePostProcessor(
mock_osutils, mock_merger, package.JSONTemplateSerializer(),
merge_template='extras.json')
template = {}
config = mock.MagicMock(spec=Config)
with pytest.raises(RuntimeError) as e:
p.process(
template,
config=config,
outdir='outdir',
chalice_stage_name='dev',
)
assert str(e.value).startswith('Cannot find template file:')
assert mock_merger.merge.call_count == 0
class TestCompositePostProcessor(object):
def test_can_call_no_processors(self):
processor = package.CompositePostProcessor([])
template = {}
config = mock.MagicMock(spec=Config)
processor.process(template, config, 'out', 'dev')
assert template == {}
def test_does_call_processors_once(self):
mock_processor_a = mock.Mock(spec=package.TemplatePostProcessor)
mock_processor_b = mock.Mock(spec=package.TemplatePostProcessor)
processor = package.CompositePostProcessor(
[mock_processor_a, mock_processor_b])
template = {}
config = mock.MagicMock(spec=Config)
processor.process(template, config, 'out', 'dev')
mock_processor_a.process.assert_called_once_with(
template, config, 'out', 'dev')
mock_processor_b.process.assert_called_once_with(
template, config, 'out', 'dev')
class TemplateTestBase(object):
template_gen_factory = None
def setup_method(self, stubbed_session):
self.resource_builder = package.ResourceBuilder(
application_builder=ApplicationGraphBuilder(),
deps_builder=DependencyBuilder(),
build_stage=mock.Mock(spec=BuildStage)
)
client = TypedAWSClient(None)
m_client = mock.Mock(wraps=client, spec=TypedAWSClient)
type(m_client).region_name = mock.PropertyMock(
return_value='us-west-2')
self.pkg_options = PackageOptions(m_client)
self.template_gen = self.template_gen_factory(
Config(), self.pkg_options)
def generate_template(self, config, chalice_stage_name='dev',
options=None):
resources = self.resource_builder.construct_resources(
config, chalice_stage_name)
if options is None:
options = self.pkg_options
return self.template_gen_factory(config, options).generate(resources)
def lambda_function(self):
return models.LambdaFunction(
resource_name='foo',
function_name='app-dev-foo',
environment_variables={},
runtime='python27',
handler='app.app',
tags={'foo': 'bar'},
timeout=120,
xray=None,
memory_size=128,
deployment_package=models.DeploymentPackage(filename='foo.zip'),
role=models.PreCreatedIAMRole(role_arn='role:arn'),
security_group_ids=[],
subnet_ids=[],
layers=[],
reserved_concurrency=None,
)
def managed_layer(self):
return models.LambdaLayer(
resource_name='layer',
layer_name='bar',
runtime='python2.7',
deployment_package=models.DeploymentPackage(filename='layer.zip')
)
class TestPackageOptions(object):
def test_service_principal(self):
awsclient = mock.Mock(spec=TypedAWSClient)
awsclient.region_name = 'us-east-1'
awsclient.endpoint_dns_suffix.return_value = 'amazonaws.com'
awsclient.service_principal.return_value = 'lambda.amazonaws.com'
options = package.PackageOptions(awsclient)
principal = options.service_principal('lambda')
assert principal == 'lambda.amazonaws.com'
awsclient.endpoint_dns_suffix.assert_called_once_with('lambda',
'us-east-1')
awsclient.service_principal.assert_called_once_with('lambda',
'us-east-1',
'amazonaws.com')
class TestTerraformTemplate(TemplateTestBase):
template_gen_factory = package.TerraformGenerator
EmptyPolicy = {
'Version': '2012-10-18',
'Statement': {
'Sid': '',
'Effect': 'Allow',
'Action': 'lambda:*'
}
}
def generate_template(self, config, chalice_stage_name='dev',
options=None):
resources = self.resource_builder.construct_resources(
config, chalice_stage_name)
# Patch up resources that have mocks (due to build stage)
# that we need to serialize to json.
for r in resources:
# For terraform rest api construction, we need a swagger
# doc on the api resource as we'll be serializing it to
# json.
if isinstance(r, models.RestAPI):
r.swagger_doc = {
'info': {'title': 'some-app'},
'x-amazon-apigateway-binary-media-types': []
}
if (isinstance(r, models.RestAPI) and
config.api_gateway_endpoint_type == 'PRIVATE'):
r.swagger_doc['x-amazon-apigateway-policy'] = (
r.policy.document)
# Same for iam policies on roles
elif isinstance(r, models.FileBasedIAMPolicy):
r.document = self.EmptyPolicy
if options is None:
options = self.pkg_options
return self.template_gen_factory(config, options).generate(resources)
def get_function(self, template):
functions = list(template['resource'][
'aws_lambda_function'].values())
assert len(functions) == 1
return functions[0]
def test_supports_precreated_role(self):
builder = DependencyBuilder()
resources = builder.build_dependencies(
models.Application(
stage='dev',
resources=[self.lambda_function()],
)
)
template = self.template_gen.generate(resources)
assert template['resource'][
'aws_lambda_function']['foo']['role'] == 'role:arn'
def test_adds_env_vars_when_provided(self, sample_app):
function = self.lambda_function()
function.environment_variables = {'foo': 'bar'}
template = self.template_gen.generate([function])
tf_resource = self.get_function(template)
assert tf_resource['environment'] == {
'variables': {
'foo': 'bar'
}
}
def test_adds_vpc_config_when_provided(self):
function = self.lambda_function()
function.security_group_ids = ['sg1', 'sg2']
function.subnet_ids = ['sn1', 'sn2']
template = self.template_gen.generate([function])
tf_resource = self.get_function(template)
assert tf_resource['vpc_config'] == {
'subnet_ids': ['sn1', 'sn2'],
'security_group_ids': ['sg1', 'sg2']}
def test_adds_layers_when_provided(self):
function = self.lambda_function()
function.layers = layers = ['arn://layer1', 'arn://layer2']
template = self.template_gen.generate([function])
tf_resource = self.get_function(template)
assert tf_resource['layers'] == layers
def test_adds_managed_layer_when_provided(self):
function = self.lambda_function()
function.layers = ['arn://layer1', 'arn://layer2']
function.managed_layer = self.managed_layer()
template = self.template_gen.generate(
[function.managed_layer, function])
tf_resource = self.get_function(template)
assert tf_resource['layers'] == [
'${aws_lambda_layer_version.layer.arn}',
'arn://layer1',
'arn://layer2',
]
assert template['resource']['aws_lambda_layer_version']['layer'] == {
'layer_name': 'bar',
'compatible_runtimes': ['python2.7'],
'filename': 'layer.zip',
}
def test_adds_reserved_concurrency_when_provided(self, sample_app):
function = self.lambda_function()
function.reserved_concurrency = 5
template = self.template_gen.generate([function])
tf_resource = self.get_function(template)
assert tf_resource['reserved_concurrent_executions'] == 5
def test_adds_log_group_resource_when_configured(self, sample_app):
function = self.lambda_function()
name = function.resource_name + '-log-group'
function.log_group = models.LogGroup(
resource_name=name,
log_group_name='/aws/lambda/%s' % function.function_name,
retention_in_days=7)
template = self.template_gen.generate([function])
log_resource = template['resource']['aws_cloudwatch_log_group'][name]
assert log_resource == {
'name': name,
'retention_in_days': 7,
}
def test_can_add_tracing_config(self, sample_app):
function = self.lambda_function()
function.xray = True
template = self.template_gen.generate([function])
tf_resource = self.get_function(template)
assert tf_resource['tracing_config']['mode'] == 'Active'
def test_can_generate_cloudwatch_event(self):
function = self.lambda_function()
event = models.CloudWatchEvent(
resource_name='foo-event',
rule_name='myrule',
event_pattern='{"source": ["aws.ec2"]}',
lambda_function=function,
)
template = self.template_gen.generate(
[function, event]
)
rule = template['resource'][
'aws_cloudwatch_event_rule'][event.resource_name]
assert rule == {
'name': event.resource_name,
'event_pattern': event.event_pattern}
target = template['resource'][
'aws_cloudwatch_event_target'][event.resource_name]
assert target == {
'target_id': 'foo-event',
'rule': '${aws_cloudwatch_event_rule.foo-event.name}',
'arn': '${aws_lambda_function.foo.arn}',
}
def test_can_generate_scheduled_event(self):
function = self.lambda_function()
event = models.ScheduledEvent(
resource_name='foo-event',
rule_name='myrule',
schedule_expression='rate(5 minutes)',
lambda_function=function,
rule_description='description',
)
template = self.template_gen.generate(
[function, event]
)
rule = template['resource'][
'aws_cloudwatch_event_rule'][event.resource_name]
assert rule == {
'name': event.resource_name,
'schedule_expression': 'rate(5 minutes)',
'description': 'description',
}
def test_can_generate_rest_api(self, sample_app_with_auth):
config = Config.create(chalice_app=sample_app_with_auth,
project_dir='.',
minimum_compression_size=8192,
api_gateway_endpoint_type='PRIVATE',
api_gateway_endpoint_vpce='vpce-abc123',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
resources = template['resource']
# Lambda function should be created.
assert resources['aws_lambda_function']
# Along with permission to invoke from API Gateway.
assert list(resources['aws_lambda_permission'].values())[0] == {
'function_name': '${aws_lambda_function.api_handler.arn}',
'action': 'lambda:InvokeFunction',
'principal': 'apigateway.amazonaws.com',
'source_arn': (
'${aws_api_gateway_rest_api.rest_api.execution_arn}/*')
}
assert 'aws_api_gateway_rest_api' in resources
assert 'rest_api' in resources['aws_api_gateway_rest_api']
resource_policy = resources[
'aws_api_gateway_rest_api']['rest_api']['policy']
assert json.loads(resource_policy) == {
'Version': '2012-10-17',
'Statement': [
{
'Action': 'execute-api:Invoke',
'Resource': 'arn:*:execute-api:*:*:*',
'Effect': 'Allow',
'Condition': {
'StringEquals': {
'aws:SourceVpce': 'vpce-abc123'
}
},
'Principal': '*'
}
]
}
assert resources['aws_api_gateway_rest_api'][
'rest_api']['minimum_compression_size'] == 8192
assert resources['aws_api_gateway_rest_api'][
'rest_api']['endpoint_configuration'] == {'types': ['PRIVATE']}
assert 'aws_api_gateway_stage' not in resources
assert resources['aws_api_gateway_deployment']['rest_api'] == {
'rest_api_id': '${aws_api_gateway_rest_api.rest_api.id}',
'stage_description': (
'${md5(local.chalice_api_swagger)}'),
'stage_name': 'api',
'lifecycle': {'create_before_destroy': True}
}
# We should also create the auth lambda function.
assert 'myauth' in resources['aws_lambda_function']
# Along with permission to invoke from API Gateway.
assert resources['aws_lambda_permission']['myauth_invoke'] == {
'action': 'lambda:InvokeFunction',
'function_name': '${aws_lambda_function.myauth.arn}',
'principal': 'apigateway.amazonaws.com',
'source_arn': (
'${aws_api_gateway_rest_api.rest_api.execution_arn}/*')
}
# Also verify we add the expected outputs when using
# a Rest API.
assert template['output'] == {
'EndpointURL': {
'value': '${aws_api_gateway_deployment.rest_api.invoke_url}'},
'RestAPIId': {
'value': '${aws_api_gateway_rest_api.rest_api.id}'}
}
def test_can_package_s3_event_handler_with_tf_ref(self, sample_app):
@sample_app.on_s3_event(
bucket='${aws_s3_bucket.my_data_bucket.id}')
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource']['aws_s3_bucket_notification'][
'my_data_bucket_notify'] == {
'bucket': '${aws_s3_bucket.my_data_bucket.id}',
'lambda_function': [{
'events': ['s3:ObjectCreated:*'],
'lambda_function_arn': (
'${aws_lambda_function.handler.arn}')
}]
}
def test_can_generate_chalice_terraform_static_data(self, sample_app):
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='myfoo',
api_gateway_stage='dev')
template = self.generate_template(config)
assert 'chalice_app' in template['locals']
assert 'chalice_stage' in template['locals']
assert 'chalice_api_swagger' in template['locals']
assert template['locals']['chalice_app'] == 'myfoo'
assert template['locals']['chalice_stage'] == 'dev'
assert template['locals']['chalice_api_swagger'] == (
'{"info": {"title": "some-app"}, "x-amazon-apigateway-binary-media-types": []}'
)
def test_can_package_s3_event_handler_sans_filters(self, sample_app):
@sample_app.on_s3_event(bucket='foo')
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource']['aws_s3_bucket_notification'][
'foo_notify'] == {
'bucket': 'foo',
'lambda_function': [{
'events': ['s3:ObjectCreated:*'],
'lambda_function_arn': (
'${aws_lambda_function.handler.arn}')
}]
}
def test_can_package_s3_event_handler(self, sample_app):
@sample_app.on_s3_event(
bucket='foo', prefix='incoming', suffix='.csv')
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource']['aws_lambda_permission'][
'handler-s3event'] == {
'action': 'lambda:InvokeFunction',
'function_name': '${aws_lambda_function.handler.arn}',
'principal': 's3.amazonaws.com',
'source_account': (
'${data.aws_caller_identity.chalice.account_id}'),
'source_arn': (
'arn:${data.aws_partition.chalice.partition}:s3:::foo'),
'statement_id': 'handler-s3event'
}
assert template['resource']['aws_s3_bucket_notification'][
'foo_notify'] == {
'bucket': 'foo',
'lambda_function': [{
'events': ['s3:ObjectCreated:*'],
'filter_prefix': 'incoming',
'filter_suffix': '.csv',
'lambda_function_arn': (
'${aws_lambda_function.handler.arn}')
}]
}
def test_can_package_sns_handler(self, sample_app):
@sample_app.on_sns_message(topic='foo')
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource']['aws_sns_topic_subscription'][
'handler-sns-subscription'] == {
'topic_arn': (
'arn:${data.aws_partition.chalice.partition}:sns'
':${data.aws_region.chalice.name}:'
'${data.aws_caller_identity.chalice.account_id}:foo'),
'protocol': 'lambda',
'endpoint': '${aws_lambda_function.handler.arn}'
}
def test_can_package_sns_arn_handler(self, sample_app):
arn = 'arn:aws:sns:space-leo-1:1234567890:foo'
@sample_app.on_sns_message(topic=arn)
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource']['aws_sns_topic_subscription'][
'handler-sns-subscription'] == {
'topic_arn': arn,
'protocol': 'lambda',
'endpoint': '${aws_lambda_function.handler.arn}'
}
assert template['resource']['aws_lambda_permission'][
'handler-sns-subscription'] == {
'function_name': '${aws_lambda_function.handler.arn}',
'action': 'lambda:InvokeFunction',
'principal': 'sns.amazonaws.com',
'source_arn': 'arn:aws:sns:space-leo-1:1234567890:foo'
}
def test_can_package_sqs_handler(self, sample_app):
@sample_app.on_sqs_message(queue='foo', batch_size=5)
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource'][
'aws_lambda_event_source_mapping'][
'handler-sqs-event-source'] == {
'event_source_arn': (
'arn:${data.aws_partition.chalice.partition}:sqs'
':${data.aws_region.chalice.name}:'
'${data.aws_caller_identity.chalice.account_id}:foo'),
'function_name': '${aws_lambda_function.handler.arn}',
'batch_size': 5,
'maximum_batching_window_in_seconds': 0
}
def test_sqs_arn_does_not_use_fn_sub(self, sample_app):
@sample_app.on_sqs_message(queue_arn='arn:foo:bar', batch_size=5)
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource'][
'aws_lambda_event_source_mapping'][
'handler-sqs-event-source'] == {
'event_source_arn': 'arn:foo:bar',
'function_name': '${aws_lambda_function.handler.arn}',
'batch_size': 5,
'maximum_batching_window_in_seconds': 0
}
def test_can_package_kinesis_handler(self, sample_app):
@sample_app.on_kinesis_record(stream='mystream', batch_size=5,
starting_position='TRIM_HORIZON')
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource'][
'aws_lambda_event_source_mapping'][
'handler-kinesis-event-source'] == {
'event_source_arn': (
'arn:${data.aws_partition.chalice.partition}:kinesis'
':${data.aws_region.chalice.name}:'
'${data.aws_caller_identity.chalice.account_id}'
':stream/mystream'),
'function_name': '${aws_lambda_function.handler.arn}',
'starting_position': 'TRIM_HORIZON',
'batch_size': 5,
'maximum_batching_window_in_seconds': 0
}
def test_can_package_dynamodb_handler(self, sample_app):
@sample_app.on_dynamodb_record(stream_arn='arn:aws:...:stream',
batch_size=5,
starting_position='TRIM_HORIZON')
def handler(event):
pass
config = Config.create(chalice_app=sample_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['resource'][
'aws_lambda_event_source_mapping'][
'handler-dynamodb-event-source'] == {
'event_source_arn': 'arn:aws:...:stream',
'function_name': '${aws_lambda_function.handler.arn}',
'starting_position': 'TRIM_HORIZON',
'batch_size': 5,
'maximum_batching_window_in_seconds': 0
}
def test_can_generate_websockets_api(self, sample_websocket_app):
config = Config.create(chalice_app=sample_websocket_app,
project_dir='.',
app_name='sample_app',
api_gateway_stage='api')
template = self.generate_template(config)
assert template['output'] == {
'WebsocketAPIId': {
'value': '${aws_apigatewayv2_api.websocket_api.id}'
},
'WebsocketConnectHandlerArn': {
'value': '${aws_lambda_function.websocket_connect.arn}'
},
'WebsocketConnectHandlerName': {
'value': (
'${aws_lambda_function.websocket_connect.function_name}')
},
'WebsocketMessageHandlerArn': {
'value': '${aws_lambda_function.websocket_message.arn}'
},
'WebsocketMessageHandlerName': {
'value': (
'${aws_lambda_function.websocket_message.function_name}')
},
'WebsocketDisconnectHandlerArn': {
'value': '${aws_lambda_function.websocket_disconnect.arn}'
},
'WebsocketDisconnectHandlerName': {
'value': (
'${aws_lambda_function.websocket_disconnect'
'.function_name}')
},
'WebsocketConnectEndpointURL': {
'value': 'wss://${aws_apigatewayv2_api.websocket_api.id}'
'.execute-api.${data.aws_region.chalice.name}'
'.amazonaws.com/api/'
}
}
assert template['resource']['aws_apigatewayv2_api'] == {
'websocket_api': {
'name': 'sample_app-dev-websocket-api',
'route_selection_expression': '$request.body.action',
'protocol_type': 'WEBSOCKET'
}
}
assert template['resource']['aws_apigatewayv2_integration'] == {
'websocket_connect_api_integration': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'connection_type': 'INTERNET',
'content_handling_strategy': 'CONVERT_TO_TEXT',
'integration_type': 'AWS_PROXY',
'integration_uri': 'arn:${data.aws_partition.chalice'
'.partition}:apigateway:'
'${data.aws_region.chalice.name}'
':lambda:path/2015-03-31/functions/arn'
':${data.aws_partition.chalice.partition}'
':lambda:${data.aws_region.chalice.name}'
':${data.aws_caller_identity'
'.chalice.account_id}:function'
':${aws_lambda_function.websocket_connect'
'.function_name}/invocations'
},
'websocket_message_api_integration': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'connection_type': 'INTERNET',
'content_handling_strategy': 'CONVERT_TO_TEXT',
'integration_type': 'AWS_PROXY',
'integration_uri': 'arn:${data.aws_partition.chalice'
'.partition}:apigateway'
':${data.aws_region.chalice.name}'
':lambda:path/2015-03-31/functions/arn'
':${data.aws_partition.chalice.partition}'
':lambda:${data.aws_region.chalice.name}'
':${data.aws_caller_identity.chalice'
'.account_id}:function'
':${aws_lambda_function.websocket_message'
'.function_name}/invocations'
},
'websocket_disconnect_api_integration': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'connection_type': 'INTERNET',
'content_handling_strategy': 'CONVERT_TO_TEXT',
'integration_type': 'AWS_PROXY',
'integration_uri': 'arn:${data.aws_partition'
'.chalice.partition}:apigateway'
':${data.aws_region.chalice.name}'
':lambda:path/2015-03-31/functions/arn'
':${data.aws_partition.chalice.partition}'
':lambda:${data.aws_region.chalice.name}'
':${data.aws_caller_identity'
'.chalice.account_id}:function'
':${aws_lambda_function'
'.websocket_disconnect.function_name}'
'/invocations'
}
}
assert template['resource']['aws_lambda_permission'] == {
'websocket_connect_invoke_permission': {
'function_name': '${aws_lambda_function.websocket_connect'
'.function_name}',
'action': 'lambda:InvokeFunction',
'principal': 'apigateway.amazonaws.com',
'source_arn': 'arn:${data.aws_partition.chalice.partition}'
':execute-api:${data.aws_region.chalice.name}'
':${data.aws_caller_identity.chalice.account_id}'
':${aws_apigatewayv2_api.websocket_api.id}/*'
},
'websocket_message_invoke_permission': {
'function_name': '${aws_lambda_function.websocket_message'
'.function_name}',
'action': 'lambda:InvokeFunction',
'principal': 'apigateway.amazonaws.com',
'source_arn': 'arn:${data.aws_partition.chalice.partition}'
':execute-api:${data.aws_region.chalice.name}'
':${data.aws_caller_identity.chalice.account_id}'
':${aws_apigatewayv2_api.websocket_api.id}/*'
},
'websocket_disconnect_invoke_permission': {
'function_name': '${aws_lambda_function.websocket_disconnect'
'.function_name}',
'action': 'lambda:InvokeFunction',
'principal': 'apigateway.amazonaws.com',
'source_arn': 'arn:${data.aws_partition.chalice.partition}'
':execute-api:${data.aws_region.chalice.name}'
':${data.aws_caller_identity.chalice.account_id}'
':${aws_apigatewayv2_api.websocket_api.id}/*'
}
}
assert template['resource']['aws_apigatewayv2_route'] == {
'websocket_connect_route': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'route_key': '$connect',
'target': 'integrations/${aws_apigatewayv2_integration'
'.websocket_connect_api_integration.id}'
},
'websocket_message_route': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'route_key': '$default',
'target': 'integrations/${aws_apigatewayv2_integration'
'.websocket_message_api_integration.id}'
},
'websocket_disconnect_route': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'route_key': '$disconnect',
'target': 'integrations/${aws_apigatewayv2_integration'
'.websocket_disconnect_api_integration.id}'
}
}
assert template['resource']['aws_apigatewayv2_deployment'] == {
'websocket_api_deployment': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'depends_on': [
'aws_apigatewayv2_route.websocket_connect_route',
'aws_apigatewayv2_route.websocket_message_route',
'aws_apigatewayv2_route.websocket_disconnect_route'
]}}
assert template['resource']['aws_apigatewayv2_stage'] == {
'websocket_api_stage': {
'api_id': '${aws_apigatewayv2_api.websocket_api.id}',
'deployment_id': '${aws_apigatewayv2_deployment'
'.websocket_api_deployment.id}',
'name': 'api'
}
}
def test_can_generate_custom_domain_name(self, sample_app):
config = Config.create(
chalice_app=sample_app,
project_dir='.',
api_gateway_stage='api',
api_gateway_endpoint_type='EDGE',
api_gateway_custom_domain={