forked from awslabs/goformation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goformation_test.go
1255 lines (994 loc) · 38.6 KB
/
goformation_test.go
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
package goformation_test
import (
"fmt"
"encoding/json"
"github.com/sanathkr/yaml"
"github.com/awslabs/goformation/v4"
"github.com/awslabs/goformation/v4/cloudformation"
"github.com/awslabs/goformation/v4/cloudformation/lambda"
"github.com/awslabs/goformation/v4/cloudformation/policies"
"github.com/awslabs/goformation/v4/cloudformation/route53"
"github.com/awslabs/goformation/v4/cloudformation/s3"
"github.com/awslabs/goformation/v4/cloudformation/serverless"
"github.com/awslabs/goformation/v4/cloudformation/sns"
"github.com/awslabs/goformation/v4/intrinsics"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gstruct"
)
func Example_to_json() {
// Create a new CloudFormation template
template := cloudformation.NewTemplate()
// Create an Amazon SNS topic, with a unique name based off the current timestamp
template.Resources["MyTopic"] = &sns.Topic{
TopicName: "my-topic-1575143839",
}
// Create a subscription, connected to our topic, that forwards notifications to an email address
template.Resources["MyTopicSubscription"] = &sns.Subscription{
TopicArn: cloudformation.Ref("MyTopic"),
Protocol: "email",
Endpoint: "[email protected]",
}
// Let's see the JSON AWS CloudFormation template
j, err := template.JSON()
if err != nil {
fmt.Printf("Failed to generate JSON: %s\n", err)
} else {
fmt.Printf("%s\n", string(j))
}
// Output:
// {
// "AWSTemplateFormatVersion": "2010-09-09",
// "Resources": {
// "MyTopic": {
// "Properties": {
// "TopicName": "my-topic-1575143839"
// },
// "Type": "AWS::SNS::Topic"
// },
// "MyTopicSubscription": {
// "Properties": {
// "Endpoint": "[email protected]",
// "Protocol": "email",
// "TopicArn": {
// "Ref": "MyTopic"
// }
// },
// "Type": "AWS::SNS::Subscription"
// }
// }
// }
}
func Example_to_yaml() {
// Create a new CloudFormation template
template := cloudformation.NewTemplate()
// Create an Amazon SNS topic, with a unique name based off the current timestamp
template.Resources["MyTopic"] = &sns.Topic{
TopicName: "my-topic-1575143970",
}
// Create a subscription, connected to our topic, that forwards notifications to an email address
template.Resources["MyTopicSubscription"] = &sns.Subscription{
TopicArn: cloudformation.Ref("MyTopic"),
Protocol: "email",
Endpoint: "[email protected]",
}
// Let's see the YAML AWS CloudFormation template
y, err := template.YAML()
if err != nil {
fmt.Printf("Failed to generate YAML: %s\n", err)
} else {
fmt.Printf("%s\n", string(y))
}
// Output:
// AWSTemplateFormatVersion: 2010-09-09
// Resources:
// MyTopic:
// Properties:
// TopicName: my-topic-1575143970
// Type: AWS::SNS::Topic
// MyTopicSubscription:
// Properties:
// Endpoint: [email protected]
// Protocol: email
// TopicArn:
// Ref: MyTopic
// Type: AWS::SNS::Subscription
}
func Example_to_go() {
// Open a template from file (can be JSON or YAML)
template, err := goformation.Open("example/yaml-to-go/template.yaml")
if err != nil {
fmt.Printf("There was an error processing the template: %s", err)
return
}
// You can extract all resources of a certain type
// Each AWS CloudFormation resource is a strongly typed struct
topics := template.GetAllSNSTopicResources()
for name, topic := range topics {
// E.g. Found a AWS::SNS::Topic with Logical ID ExampleTopic and TopicName 'example'
fmt.Printf("Found a %s with Logical ID %s and TopicName %s\n", topic.AWSCloudFormationType(), name, topic.TopicName)
}
// You can also search for specific resources by their logicalId
search := "ExampleTopic"
topic, err := template.GetSNSTopicWithName(search)
if err != nil {
fmt.Printf("SNS topic with logical ID %s not found", search)
return
}
// E.g. Found a AWS::Serverless::Function named GetHelloWorld (runtime: nodejs6.10)
fmt.Printf("Found a %s with Logical ID %s and TopicName %s\n", topic.AWSCloudFormationType(), search, topic.TopicName)
// Output:
// Found a AWS::SNS::Topic with Logical ID ExampleTopic and TopicName example
// Found a AWS::SNS::Topic with Logical ID ExampleTopic and TopicName example
}
var _ = Describe("Goformation", func() {
Context("with a Serverless function matching 2016-10-31 specification", func() {
template, err := goformation.Open("test/yaml/aws-serverless-function-2016-10-31.yaml")
It("should successfully validate the SAM template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
functions := template.GetAllServerlessFunctionResources()
It("should have exactly one function", func() {
Expect(functions).To(HaveLen(1))
Expect(functions).To(HaveKey("Function20161031"))
})
f := functions["Function20161031"]
It("should correctly parse all of the function properties", func() {
Expect(f.Handler).To(Equal("file.method"))
Expect(f.Runtime).To(Equal("nodejs"))
Expect(f.FunctionName).To(Equal("functionname"))
Expect(f.Description).To(Equal("description"))
Expect(f.MemorySize).To(Equal(128))
Expect(f.Timeout).To(Equal(30))
Expect(f.Role).To(Equal("aws::arn::123456789012::some/role"))
Expect((*f.Policies.SAMPolicyTemplateArray)[0].DynamoDBCrudPolicy.TableName).To(Equal("table_arn"))
Expect(f.Environment).ToNot(BeNil())
Expect(f.Environment.Variables).To(HaveKeyWithValue("NAME", "VALUE"))
})
It("should correctly parse all of the function API event sources/endpoints", func() {
Expect(f.Events).ToNot(BeNil())
Expect(f.Events).To(HaveKey("TestApi"))
Expect(f.Events["TestApi"].Type).To(Equal("Api"))
Expect(f.Events["TestApi"].Properties.ApiEvent).ToNot(BeNil())
event := f.Events["TestApi"].Properties.ApiEvent
Expect(event.Method).To(Equal("any"))
Expect(event.Path).To(Equal("/testing"))
})
It("should correctly parse all of the function S3 event source", func() {
Expect(f.Events).ToNot(BeNil())
Expect(f.Events).To(HaveKey("TestS3"))
Expect(f.Events["TestS3"].Type).To(Equal("S3"))
Expect(f.Events["TestS3"].Properties.S3Event).ToNot(BeNil())
event := f.Events["TestS3"].Properties.S3Event
Expect(event.Bucket).To(Equal("my-photo-bucket"))
Expect(event.Events.String).To(PointTo(Equal("s3:ObjectCreated:*")))
Expect(event.Filter.S3Key.Rules).To(HaveLen(1))
Expect(event.Filter.S3Key.Rules[0].Name).To(Equal("prefix|suffix"))
Expect(event.Filter.S3Key.Rules[0].Value).To(Equal("my-prefix|my-suffix"))
})
})
Context("with a JSON template that contains a resource with tags", func() {
template, err := goformation.Open("test/json/resource-with-tags.json")
It("should successfully validate the template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
resources := template.GetAllAutoScalingAutoScalingGroupResources()
It("should have exactly one resource", func() {
Expect(resources).To(HaveLen(1))
Expect(resources).To(HaveKey("EcsClusterDefaultAutoScalingGroupASGC1A785DB"))
})
asg := resources["EcsClusterDefaultAutoScalingGroupASGC1A785DB"]
It("should have exactly one tag defined", func() {
Expect(asg.Tags).To(HaveLen(1))
})
It("should have the correct tag properties set", func() {
Expect(asg.Tags[0].PropagateAtLaunch).To(Equal(true))
Expect(asg.Tags[0].Key).To(Equal("Name"))
Expect(asg.Tags[0].Value).To(Equal("aws-ecs-integ-ecs/EcsCluster/DefaultAutoScalingGroup"))
})
})
Context("with a Custom Resource template", func() {
template, err := goformation.Open("test/yaml/custom-resource.yaml")
It("should successfully validate the template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
resources := template.GetAllCustomResources()
It("should have exactly one resource", func() {
Expect(resources).To(HaveLen(1))
Expect(resources).To(HaveKey("MyCustomResource"))
})
It("should correctly Marshal the custom resource", func() {
data, err := template.JSON()
Expect(err).To(BeNil())
var result map[string]interface{}
if err := json.Unmarshal(data, &result); err != nil {
Fail(err.Error())
}
resources, ok := result["Resources"].(map[string]interface{})
Expect(ok).To(BeTrue())
Expect(resources).To(HaveLen(1))
Expect(resources).To(HaveKey("MyCustomResource"))
mcr := resources["MyCustomResource"].(map[string]interface{})
Expect(mcr["Properties"]).To(HaveKey("CustomProperty"))
})
})
Context("with an AWS CloudFormation template that contains multiple resources", func() {
Context("described as Go structs", func() {
template := cloudformation.NewTemplate()
template.Resources["MySNSTopic"] = &sns.Topic{
DisplayName: "test-sns-topic-display-name",
TopicName: "test-sns-topic-name",
Subscription: []sns.Topic_Subscription{
sns.Topic_Subscription{
Endpoint: "test-sns-topic-subscription-endpoint",
Protocol: "test-sns-topic-subscription-protocol",
},
},
}
template.Resources["MyRoute53HostedZone"] = &route53.HostedZone{
Name: "example.com",
}
topics := template.GetAllSNSTopicResources()
It("should have one AWS::SNS::Topic resource", func() {
Expect(topics).To(HaveLen(1))
Expect(topics).To(HaveKey("MySNSTopic"))
})
topic, err := template.GetSNSTopicWithName("MySNSTopic")
It("should be able to find the AWS::SNS::Topic by name", func() {
Expect(topic).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct AWS::SNS::Topic values", func() {
Expect(topic.DisplayName).To(Equal("test-sns-topic-display-name"))
Expect(topic.TopicName).To(Equal("test-sns-topic-name"))
Expect(topic.Subscription).To(HaveLen(1))
Expect(topic.Subscription[0].Endpoint).To(Equal("test-sns-topic-subscription-endpoint"))
Expect(topic.Subscription[0].Protocol).To(Equal("test-sns-topic-subscription-protocol"))
})
zones := template.GetAllRoute53HostedZoneResources()
It("should have one AWS::Route53::HostedZone resource", func() {
Expect(zones).To(HaveLen(1))
Expect(zones).To(HaveKey("MyRoute53HostedZone"))
})
zone, err := template.GetRoute53HostedZoneWithName("MyRoute53HostedZone")
It("should be able to find the AWS::Route53::HostedZone by name", func() {
Expect(zone).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct AWS::Route53::HostedZone values", func() {
Expect(zone.Name).To(Equal("example.com"))
})
})
Context("described as JSON", func() {
template := []byte(`{"AWSTemplateFormatVersion":"2010-09-09","Resources":{"MyRoute53HostedZone":{"Type":"AWS::Route53::HostedZone","Properties":{"Name":"example.com"}},"MySNSTopic":{"Type":"AWS::SNS::Topic","Properties":{"DisplayName":"test-sns-topic-display-name","Subscription":[{"Endpoint":"test-sns-topic-subscription-endpoint","Protocol":"test-sns-topic-subscription-protocol"}],"TopicName":"test-sns-topic-name"}}}}`)
expected := cloudformation.NewTemplate()
expected.Resources["MySNSTopic"] = &sns.Topic{
DisplayName: "test-sns-topic-display-name",
TopicName: "test-sns-topic-name",
Subscription: []sns.Topic_Subscription{
sns.Topic_Subscription{
Endpoint: "test-sns-topic-subscription-endpoint",
Protocol: "test-sns-topic-subscription-protocol",
},
},
}
expected.Resources["MyRoute53HostedZone"] = &route53.HostedZone{
Name: "example.com",
}
result, err := goformation.ParseJSON(template)
It("should marshal to Go structs successfully", func() {
Expect(err).To(BeNil())
})
topics := result.GetAllSNSTopicResources()
It("should have one AWS::SNS::Topic resource", func() {
Expect(topics).To(HaveLen(1))
Expect(topics).To(HaveKey("MySNSTopic"))
})
topic, err := result.GetSNSTopicWithName("MySNSTopic")
It("should be able to find the AWS::SNS::Topic by name", func() {
Expect(topic).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct AWS::SNS::Topic values", func() {
Expect(topic.DisplayName).To(Equal("test-sns-topic-display-name"))
Expect(topic.TopicName).To(Equal("test-sns-topic-name"))
Expect(topic.Subscription).To(HaveLen(1))
Expect(topic.Subscription[0].Endpoint).To(Equal("test-sns-topic-subscription-endpoint"))
Expect(topic.Subscription[0].Protocol).To(Equal("test-sns-topic-subscription-protocol"))
})
zones := result.GetAllRoute53HostedZoneResources()
It("should have one AWS::Route53::HostedZone resource", func() {
Expect(zones).To(HaveLen(1))
Expect(zones).To(HaveKey("MyRoute53HostedZone"))
})
zone, err := result.GetRoute53HostedZoneWithName("MyRoute53HostedZone")
It("should be able to find the AWS::Route53::HostedZone by name", func() {
Expect(zone).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct AWS::Route53::HostedZone values", func() {
Expect(zone.Name).To(Equal("example.com"))
})
})
})
Context("with the official AWS SAM example templates", func() {
inputs := []string{
"test/yaml/sam-official-samples/alexa_skill/template.yaml",
"test/yaml/sam-official-samples/api_backend/template.yaml",
"test/yaml/sam-official-samples/api_swagger_cors/template.yaml",
"test/yaml/sam-official-samples/encryption_proxy/template.yaml",
"test/yaml/sam-official-samples/hello_world/template.yaml",
"test/yaml/sam-official-samples/inline_swagger/template.yaml",
"test/yaml/sam-official-samples/iot_backend/template.yaml",
"test/yaml/sam-official-samples/s3_processor/template.yaml",
"test/yaml/sam-official-samples/schedule/template.yaml",
"test/yaml/sam-official-samples/stream_processor/template.yaml",
}
for _, filename := range inputs {
Context("including "+filename, func() {
template, err := goformation.Open(filename)
It("should successfully parse the SAM template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
})
}
})
Context("with the default AWS CodeStar templates", func() {
inputs := []string{
"test/yaml/codestar/nodejs.yml",
"test/yaml/codestar/python.yml",
"test/yaml/codestar/java.yml",
}
for _, filename := range inputs {
Context("including "+filename, func() {
template, err := goformation.Open(filename)
It("should successfully validate the SAM template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
})
}
})
// pmaddox@ 2017-08-17:
// Commented out until we have support for YAML tag intrinsic functions (e.g. !Sub)
Context("with a YAML template containing intrinsic tags (e.g. !Sub)", func() {
template, err := goformation.Open("test/yaml/yaml-intrinsic-tags.yaml")
It("should successfully validate the SAM template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(PointTo(BeNil()))
})
function, err := template.GetServerlessFunctionWithName("IntrinsicFunctionTest")
It("should have a function named 'IntrinsicFunctionTest'", func() {
Expect(function).To(Not(BeNil()))
Expect(err).To(BeNil())
})
It("it should have the correct values", func() {
Expect(function.Runtime).To(Equal("4.3"))
Expect(function.Timeout).To(Equal(10))
})
})
Context("with a Serverless template containing different CORS configuration formats", func() {
template, err := goformation.Open("test/yaml/aws-serverless-api-string-or-cors-configuration.yaml")
It("should successfully parse the template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
apis := template.GetAllServerlessApiResources()
It("should have exactly two APIs", func() {
Expect(apis).To(HaveLen(2))
Expect(apis).To(HaveKey("RestApiWithCorsConfiguration"))
Expect(apis).To(HaveKey("RestApiWithCorsString"))
})
api1 := apis["RestApiWithCorsConfiguration"]
It("should parse a Cors configuration object", func() {
Expect(api1.Cors.CorsConfiguration.AllowHeaders).To(Equal("'Authorization,authorization'"))
Expect(api1.Cors.CorsConfiguration.AllowOrigin).To(Equal("'*'"))
})
api2 := apis["RestApiWithCorsString"]
It("should parse a Cors string", func() {
Expect(api2.Cors.String).To(PointTo(Equal("'www.example.com'")))
})
})
Context("with a Serverless template containing different CodeUri formats", func() {
template, err := goformation.Open("test/yaml/aws-serverless-function-string-or-s3-location.yaml")
It("should successfully parse the template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
functions := template.GetAllServerlessFunctionResources()
It("should have exactly three functions", func() {
Expect(functions).To(HaveLen(3))
Expect(functions).To(HaveKey("CodeUriWithS3LocationSpecifiedAsString"))
Expect(functions).To(HaveKey("CodeUriWithS3LocationSpecifiedAsObject"))
Expect(functions).To(HaveKey("CodeUriWithString"))
})
f1 := functions["CodeUriWithS3LocationSpecifiedAsString"]
It("should parse a CodeUri property with an S3 location specified as a string", func() {
Expect(f1.CodeUri.String).To(PointTo(Equal("s3://testbucket/testkey.zip")))
})
f2 := functions["CodeUriWithS3LocationSpecifiedAsObject"]
It("should parse a CodeUri property with an S3 location specified as an object", func() {
Expect(f2.CodeUri.S3Location.Key).To(Equal("testkey.zip"))
Expect(f2.CodeUri.S3Location.Version).To(Equal(5))
})
f3 := functions["CodeUriWithString"]
It("should parse a CodeUri property with a string", func() {
Expect(f3.CodeUri.String).To(PointTo(Equal("./testfolder")))
})
})
Context("with a template defined as Go code", func() {
template := &cloudformation.Template{
Resources: cloudformation.Resources{
"MyLambdaFunction": &lambda.Function{
Handler: "nodejs6.10",
},
},
}
functions := template.GetAllLambdaFunctionResources()
It("should be able to retrieve all Lambda functions with GetAllLambdaFunction(template)", func() {
Expect(functions).To(HaveLen(1))
})
function, err := template.GetLambdaFunctionWithName("MyLambdaFunction")
It("should be able to retrieve a specific Lambda function with GetLambdaFunctionWithName(template, name)", func() {
Expect(err).To(BeNil())
Expect(function).To(BeAssignableToTypeOf(&lambda.Function{}))
})
It("should have the correct Handler property", func() {
Expect(function.Handler).To(Equal("nodejs6.10"))
})
})
Context("with a template that defines an AWS::Serverless::Function", func() {
Context("that has a CodeUri property set as an S3 Location", func() {
template := &cloudformation.Template{
Resources: cloudformation.Resources{
"MySAMFunction": &serverless.Function{
Handler: "nodejs6.10",
CodeUri: &serverless.Function_CodeUri{
S3Location: &serverless.Function_S3Location{
Bucket: "test-bucket",
Key: "test-key",
Version: 100,
},
},
},
},
}
function, err := template.GetServerlessFunctionWithName("MySAMFunction")
It("should have an AWS::Serverless::Function called MySAMFunction", func() {
Expect(function).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct S3 bucket/key/version", func() {
Expect(function.CodeUri.S3Location.Bucket).To(Equal("test-bucket"))
Expect(function.CodeUri.S3Location.Key).To(Equal("test-key"))
Expect(function.CodeUri.S3Location.Version).To(Equal(100))
})
})
Context("that has a CodeUri property set as a string", func() {
codeuri := "./some-folder"
template := &cloudformation.Template{
Resources: cloudformation.Resources{
"MySAMFunction": &serverless.Function{
Handler: "nodejs6.10",
CodeUri: &serverless.Function_CodeUri{
String: &codeuri,
},
},
},
}
function, err := template.GetServerlessFunctionWithName("MySAMFunction")
It("should have an AWS::Serverless::Function called MySAMFunction", func() {
Expect(function).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct CodeUri", func() {
Expect(function.CodeUri.String).To(PointTo(Equal("./some-folder")))
})
})
})
Context("with a YAML template that contains AWS::Serverless::SimpleTable resource(s)", func() {
template, err := goformation.Open("test/yaml/aws-serverless-simpletable.yaml")
It("should parse the template successfully", func() {
Expect(template).ToNot(BeNil())
Expect(err).To(BeNil())
})
table, err := template.GetServerlessSimpleTableWithName("TestSimpleTable")
It("should have a table named 'TestSimpleTable'", func() {
Expect(table).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have a primary key set", func() {
Expect(table.PrimaryKey).ToNot(BeNil())
})
It("should have the correct value for the primary key name", func() {
Expect(table.PrimaryKey.Name).To(Equal("test-primary-key-name"))
})
It("should have the correct value for the primary key type", func() {
Expect(table.PrimaryKey.Type).To(Equal("test-primary-key-type"))
})
It("should have provisioned throughput set", func() {
Expect(table.ProvisionedThroughput).ToNot(BeNil())
})
It("should have the correct value for ReadCapacityUnits", func() {
Expect(table.ProvisionedThroughput.ReadCapacityUnits).To(Equal(100))
})
It("should have the correct value for WriteCapacityUnits", func() {
Expect(table.ProvisionedThroughput.WriteCapacityUnits).To(Equal(200))
})
It("should have a table named 'TestSimpleTableNoProperties'", func() {
nopropertiesTable, err := template.GetServerlessSimpleTableWithName("TestSimpleTableNoProperties")
Expect(nopropertiesTable).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct DeletionPolicy", func() {
Expect(table.AWSCloudFormationDeletionPolicy).To(Equal(policies.DeletionPolicy("Retain")))
})
})
Context("with a YAML template that contains AWS::Serverless::Api resource(s)", func() {
template, err := goformation.Open("test/yaml/aws-serverless-api.yaml")
It("should parse the template successfully", func() {
Expect(template).ToNot(BeNil())
Expect(err).To(BeNil())
})
api1, err := template.GetServerlessApiWithName("ServerlessApiWithDefinitionUriAsString")
It("should have an AWS::Serverless::Api named 'ServerlessApiWithDefinitionUriAsString'", func() {
Expect(api1).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct value for Name", func() {
Expect(api1.Name).To(Equal("test-name"))
})
It("should have the correct value for StageName", func() {
Expect(api1.StageName).To(Equal("test-stage-name"))
})
It("should have the correct value for DefinitionUri", func() {
Expect(api1.DefinitionUri.String).To(PointTo(Equal("test-definition-uri")))
})
It("should have the correct value for CacheClusterEnabled", func() {
Expect(api1.CacheClusterEnabled).To(Equal(true))
})
It("should have the correct value for CacheClusterSize", func() {
Expect(api1.CacheClusterSize).To(Equal("test-cache-cluster-size"))
})
It("should have the correct value for Variables", func() {
Expect(api1.Variables).To(HaveKeyWithValue("NAME", "VALUE"))
})
api2, err := template.GetServerlessApiWithName("ServerlessApiWithDefinitionUriAsS3Location")
It("should have an AWS::Serverless::Api named 'ServerlessApiWithDefinitionUriAsS3Location'", func() {
Expect(api2).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct value for DefinitionUri", func() {
Expect(api2.DefinitionUri.S3Location.Bucket).To(Equal("test-bucket"))
Expect(api2.DefinitionUri.S3Location.Key).To(Equal("test-key"))
Expect(api2.DefinitionUri.S3Location.Version).To(Equal(1))
})
api3, err := template.GetServerlessApiWithName("ServerlessApiWithDefinitionBodyAsJSON")
It("should have an AWS::Serverless::Api named 'ServerlessApiWithDefinitionBodyAsJSON'", func() {
Expect(api3).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct value for DefinitionBody", func() {
Expect(api3.DefinitionBody).To(Equal("{\n \"DefinitionKey\": \"test-definition-value\"\n}\n"))
})
api4, err := template.GetServerlessApiWithName("ServerlessApiWithDefinitionBodyAsYAML")
It("should have an AWS::Serverless::Api named 'ServerlessApiWithDefinitionBodyAsYAML'", func() {
Expect(api4).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct value for DefinitionBody", func() {
var expected map[string]interface{}
expected = map[string]interface{}{
"DefinitionKey": "test-definition-value",
}
Expect(api4.DefinitionBody).To(Equal(expected))
})
api5, err := template.GetServerlessApiWithName("ServerlessApiWithAccessLogSettingAsYAML")
It("should have an AWS::Serverless::Api named 'ServerlessApiWithAccessLogSettingAsYAML'", func() {
Expect(api5).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should have the correct value for AccessLogSetting", func() {
Expect(api5.AccessLogSetting.DestinationArn).To(Equal("arn:test"))
Expect(api5.AccessLogSetting.Format).To(Equal("{customKey: $context.Key}"))
})
})
Context("with a YAML template with single transform macro", func() {
template, err := goformation.Open("test/yaml/transform-single.yaml")
It("should parse the template successfully", func() {
Expect(template).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should parse transform macro into String field", func() {
Expect(*template.Transform.String).To(Equal("MyTranformMacro"))
})
It("should StringArray remain nil", func() {
Expect(template.Transform.StringArray).To(BeNil())
})
})
Context("with a YAML template with multiple transform macros", func() {
template, err := goformation.Open("test/yaml/transform-multiple.yaml")
It("should parse the template successfully", func() {
Expect(template).ToNot(BeNil())
Expect(err).To(BeNil())
})
It("should parse transform macro into StringArray field", func() {
Expect(*template.Transform.StringArray).To(Equal([]string{"FirstMacro", "SecondMacro"}))
})
It("should String remain nil", func() {
Expect(template.Transform.String).To(BeNil())
})
})
Context("with a YAML template with paramter overrides", func() {
template, err := goformation.OpenWithOptions("test/yaml/aws-serverless-function-env-vars.yaml", &intrinsics.ProcessorOptions{
ParameterOverrides: map[string]interface{}{"ExampleParameter": "SomeNewValue"},
})
It("should successfully validate the SAM template", func() {
Expect(err).To(BeNil())
Expect(template).ShouldNot(BeNil())
})
function, err := template.GetServerlessFunctionWithName("IntrinsicEnvironmentVariableTestFunction")
It("should have a function named 'IntrinsicEnvironmentVariableTestFunction'", func() {
Expect(function).To(Not(BeNil()))
Expect(err).To(BeNil())
})
It("it should have the correct values", func() {
Expect(function.Environment.Variables).To(HaveKeyWithValue("REF_ENV_VAR", "SomeNewValue"))
})
})
Context("with a SNS event source", func() {
event := serverless.Function_Properties{
SNSEvent: &serverless.Function_SNSEvent{
Topic: "MyTopic",
},
}
It("should marshal properties correctly", func() {
bytes, err := event.MarshalJSON()
Expect(err).To(BeNil())
Expect(string(bytes)).To(Equal(`{"Topic":"MyTopic"}`))
})
})
Context("with an SNS event source created from JSON", func() {
eventString := `{"Topic":"MyTopic"}`
eventJson := []byte(eventString)
event := serverless.Function_Properties{}
event.UnmarshalJSON(eventJson)
It("should marshal properties correctly", func() {
bytes, err := event.MarshalJSON()
Expect(err).To(BeNil())
Expect(string(bytes)).To(Equal(eventString))
})
})
Context("with a template that contains a reference to another resource within the template", func() {
template := &cloudformation.Template{
Resources: cloudformation.Resources{
"TestBucket": &s3.Bucket{
BucketName: "test-bucket",
},
"TestBucketPolicy": &s3.BucketPolicy{
Bucket: cloudformation.Ref("TestBucket"),
},
},
}
It("should have the correct reference object when converted to JSON", func() {
data, err := template.JSON()
Expect(err).To(BeNil())
var result map[string]interface{}
if err := json.Unmarshal(data, &result); err != nil {
Fail(err.Error())
}
resources, ok := result["Resources"].(map[string]interface{})
Expect(ok).To(BeTrue())
bucket, ok := resources["TestBucketPolicy"].(map[string]interface{})
Expect(ok).To(BeTrue())
properties, ok := bucket["Properties"].(map[string]interface{})
Expect(ok).To(BeTrue())
reference, ok := properties["Bucket"].(map[string]interface{})
Expect(ok).To(BeTrue())
Expect(reference["Ref"]).To(Equal("TestBucket"))
})
It("should have the correct reference object when converted to YAML", func() {
data, err := template.YAML()
Expect(err).To(BeNil())
var result map[string]interface{}
if err := yaml.Unmarshal(data, &result); err != nil {
Fail(err.Error())
}
resources, ok := result["Resources"].(map[string]interface{})
Expect(ok).To(BeTrue())
bucket, ok := resources["TestBucketPolicy"].(map[string]interface{})
Expect(ok).To(BeTrue())
properties, ok := bucket["Properties"].(map[string]interface{})
Expect(ok).To(BeTrue())
reference, ok := properties["Bucket"].(map[string]interface{})
Expect(ok).To(BeTrue())
Expect(reference["Ref"]).To(Equal("TestBucket"))
})
})
Context("with a template that is composed with all of the intrinsics", func() {
tests := []struct {
Name string
Input string
Expected map[string]interface{}
}{
{
Name: "Ref",
Input: cloudformation.Ref("test-reference"),
Expected: map[string]interface{}{
"Ref": "test-reference",
},
},
{
Name: "Fn::GetAtt",
Input: cloudformation.GetAtt("resource", "property"),
Expected: map[string]interface{}{
"Fn::GetAtt": []interface{}{"resource", "property"},
},
},
{
Name: "Fn::ImportValue",
Input: cloudformation.ImportValue("test-import"),
Expected: map[string]interface{}{
"Fn::ImportValue": "test-import",
},
},
{
Name: "Fn::Base64",
Input: cloudformation.Base64("test-base64"),
Expected: map[string]interface{}{
"Fn::Base64": "test-base64",
},
},
{
Name: "Fn::Cidr",
Input: cloudformation.CIDR("test-ip-block", "test-count", "test-cidr-bits"),
Expected: map[string]interface{}{
"Fn::Cidr": []interface{}{"test-ip-block", "test-count", "test-cidr-bits"},
},
},
{
Name: "Fn::FindInMap",
Input: cloudformation.FindInMap("test-map", "test-top-level-key", "test-second-level-key"),
Expected: map[string]interface{}{
"Fn::FindInMap": []interface{}{"test-map", "test-top-level-key", "test-second-level-key"},
},
},
{
Name: "Fn::GetAZs",
Input: cloudformation.GetAZs("test-region"),
Expected: map[string]interface{}{
"Fn::GetAZs": "test-region",
},
},
{
Name: "Fn::Join",
Input: cloudformation.Join("test-delimiter", []string{"test-join-value-1", "test-join-value-2"}),
Expected: map[string]interface{}{
"Fn::Join": []interface{}{
"test-delimiter",
[]interface{}{
"test-join-value-1",
"test-join-value-2",
},
},
},
},
{
Name: "Fn::Select",
Input: cloudformation.Select("test-index", []string{"test-select-value-1", "test-select-value-2"}),
Expected: map[string]interface{}{
"Fn::Select": []interface{}{
"test-index",
[]interface{}{
"test-select-value-1",
"test-select-value-2",
},
},
},
},
{
Name: "Fn::Split",
Input: cloudformation.Split("test-delimiter", "test-split-source"),
Expected: map[string]interface{}{
"Fn::Split": []interface{}{"test-delimiter", "test-split-source"},
},