Skip to content

Commit c664b4e

Browse files
authored
test: restore previously removed integ tests (#2580)
Two integration test cases were removed by #2415. This PR restore those tests because the tests still have values in ensuring templates are rendered as expected. The expected templates are modified to mirror the changes made in ##2536 By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
1 parent de7dc32 commit c664b4e

File tree

3 files changed

+79
-57
lines changed

3 files changed

+79
-57
lines changed

internal/pkg/deploy/cloudformation/stack/lb_web_service_integration_test.go

Lines changed: 74 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -25,71 +25,93 @@ import (
2525

2626
const (
2727
svcManifestPath = "svc-manifest.yml"
28-
svcStackPath = "svc-test.stack.yml"
29-
svcParamsPath = "svc-test.params.json"
3028

3129
dynamicDesiredCountPath = "custom-resources/desired-count-delegation.js"
3230
rulePriorityPath = "custom-resources/alb-rule-priority-generator.js"
3331
)
3432

3533
func TestLoadBalancedWebService_Template(t *testing.T) {
34+
testCases := map[string]struct {
35+
envName string
36+
svcStackPath string
37+
svcParamsPath string
38+
}{
39+
"default env": {
40+
envName: "test",
41+
svcStackPath: "svc-test.stack.yml",
42+
svcParamsPath: "svc-test.params.json",
43+
},
44+
"staging env": {
45+
envName: "staging",
46+
svcStackPath: "svc-staging.stack.yml",
47+
svcParamsPath: "svc-staging.params.json",
48+
},
49+
"prod env": {
50+
envName: "prod",
51+
svcStackPath: "svc-prod.stack.yml",
52+
svcParamsPath: "svc-prod.params.json",
53+
},
54+
}
3655
path := filepath.Join("testdata", "workloads", svcManifestPath)
3756
manifestBytes, err := ioutil.ReadFile(path)
3857
require.NoError(t, err)
3958
mft, err := manifest.UnmarshalWorkload(manifestBytes)
4059
require.NoError(t, err)
41-
envMft, err := mft.ApplyEnv(envName)
42-
require.NoError(t, err)
43-
v, ok := envMft.(*manifest.LoadBalancedWebService)
44-
require.True(t, ok)
45-
46-
serializer, err := stack.NewHTTPSLoadBalancedWebService(v, envName, appName, stack.RuntimeConfig{})
4760

48-
tpl, err := serializer.Template()
49-
require.NoError(t, err, "template should render")
50-
regExpGUID := regexp.MustCompile(`([a-f\d]{8}-)([a-f\d]{4}-){3}([a-f\d]{12})`) // Matches random guids
51-
testName := fmt.Sprintf("CF Template should be equal")
52-
parser := template.New()
53-
envController, err := parser.Read(envControllerPath)
54-
require.NoError(t, err)
55-
envControllerZipFile := envController.String()
56-
dynamicDesiredCount, err := parser.Read(dynamicDesiredCountPath)
57-
require.NoError(t, err)
58-
dynamicDesiredCountZipFile := dynamicDesiredCount.String()
59-
rulePriority, err := parser.Read(rulePriorityPath)
60-
require.NoError(t, err)
61-
rulePriorityZipFile := rulePriority.String()
62-
63-
t.Run(testName, func(t *testing.T) {
64-
actualBytes := []byte(tpl)
65-
// Cut random GUID from template.
66-
actualBytes = regExpGUID.ReplaceAll(actualBytes, []byte("RandomGUID"))
67-
actualString := string(actualBytes)
68-
// Cut out zip file for more readable output
69-
actualString = strings.ReplaceAll(actualString, envControllerZipFile, "mockEnvControllerZipFile")
70-
actualString = strings.ReplaceAll(actualString, dynamicDesiredCountZipFile, "mockDynamicDesiredCountZipFile")
71-
actualString = strings.ReplaceAll(actualString, rulePriorityZipFile, "mockRulePriorityZipFile")
72-
actualBytes = []byte(actualString)
73-
mActual := make(map[interface{}]interface{})
74-
require.NoError(t, yaml.Unmarshal(actualBytes, mActual))
75-
76-
expected, err := ioutil.ReadFile(filepath.Join("testdata", "workloads", svcStackPath))
77-
require.NoError(t, err, "should be able to read expected bytes")
78-
expectedBytes := []byte(expected)
79-
mExpected := make(map[interface{}]interface{})
80-
require.NoError(t, yaml.Unmarshal(expectedBytes, mExpected))
81-
require.Equal(t, mExpected, mActual)
82-
})
83-
84-
testName = fmt.Sprintf("Parameter values should render properly")
85-
t.Run(testName, func(t *testing.T) {
86-
actualParams, err := serializer.SerializedParameters()
61+
for name, tc := range testCases {
62+
envMft, err := mft.ApplyEnv(tc.envName)
8763
require.NoError(t, err)
64+
v, ok := envMft.(*manifest.LoadBalancedWebService)
65+
require.True(t, ok)
8866

89-
path := filepath.Join("testdata", "workloads", svcParamsPath)
90-
wantedCFNParamsBytes, err := ioutil.ReadFile(path)
91-
require.NoError(t, err)
67+
serializer, err := stack.NewHTTPSLoadBalancedWebService(v, tc.envName, appName, stack.RuntimeConfig{})
9268

93-
require.Equal(t, string(wantedCFNParamsBytes), actualParams)
94-
})
69+
tpl, err := serializer.Template()
70+
require.NoError(t, err, "template should render")
71+
regExpGUID := regexp.MustCompile(`([a-f\d]{8}-)([a-f\d]{4}-){3}([a-f\d]{12})`) // Matches random guids
72+
testName := fmt.Sprintf("CF Template should be equal/%s", name)
73+
parser := template.New()
74+
envController, err := parser.Read(envControllerPath)
75+
require.NoError(t, err)
76+
envControllerZipFile := envController.String()
77+
dynamicDesiredCount, err := parser.Read(dynamicDesiredCountPath)
78+
require.NoError(t, err)
79+
dynamicDesiredCountZipFile := dynamicDesiredCount.String()
80+
rulePriority, err := parser.Read(rulePriorityPath)
81+
require.NoError(t, err)
82+
rulePriorityZipFile := rulePriority.String()
83+
84+
t.Run(testName, func(t *testing.T) {
85+
actualBytes := []byte(tpl)
86+
// Cut random GUID from template.
87+
actualBytes = regExpGUID.ReplaceAll(actualBytes, []byte("RandomGUID"))
88+
actualString := string(actualBytes)
89+
// Cut out zip file for more readable output
90+
actualString = strings.ReplaceAll(actualString, envControllerZipFile, "mockEnvControllerZipFile")
91+
actualString = strings.ReplaceAll(actualString, dynamicDesiredCountZipFile, "mockDynamicDesiredCountZipFile")
92+
actualString = strings.ReplaceAll(actualString, rulePriorityZipFile, "mockRulePriorityZipFile")
93+
actualBytes = []byte(actualString)
94+
mActual := make(map[interface{}]interface{})
95+
require.NoError(t, yaml.Unmarshal(actualBytes, mActual))
96+
97+
expected, err := ioutil.ReadFile(filepath.Join("testdata", "workloads", tc.svcStackPath))
98+
require.NoError(t, err, "should be able to read expected bytes")
99+
expectedBytes := []byte(expected)
100+
mExpected := make(map[interface{}]interface{})
101+
require.NoError(t, yaml.Unmarshal(expectedBytes, mExpected))
102+
require.Equal(t, mExpected, mActual)
103+
})
104+
105+
testName = fmt.Sprintf("Parameter values should render properly/%s", name)
106+
t.Run(testName, func(t *testing.T) {
107+
actualParams, err := serializer.SerializedParameters()
108+
require.NoError(t, err)
109+
110+
path := filepath.Join("testdata", "workloads", tc.svcParamsPath)
111+
wantedCFNParamsBytes, err := ioutil.ReadFile(path)
112+
require.NoError(t, err)
113+
114+
require.Equal(t, string(wantedCFNParamsBytes), actualParams)
115+
})
116+
}
95117
}

internal/pkg/deploy/cloudformation/stack/testdata/workloads/svc-prod.stack.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ Resources:
218218
Properties:
219219
Code:
220220
ZipFile: |
221-
"use strict";const aws=require("aws-sdk");let defaultResponseURL,report=function(a,b,c,d,e,f){return new Promise((g,h)=>{const i=require("https"),{URL:j}=require("url");var k=JSON.stringify({Status:c,Reason:f,PhysicalResourceId:d||b.logStreamName,StackId:a.StackId,RequestId:a.RequestId,LogicalResourceId:a.LogicalResourceId,Data:e});const l=new j(a.ResponseURL||defaultResponseURL),m={hostname:l.hostname,port:443,path:l.pathname+l.search,method:"PUT",headers:{"Content-Type":"","Content-Length":k.length}};i.request(m).on("error",h).on("response",a=>{a.resume(),400<=a.statusCode?h(new Error(`Error ${a.statusCode}: ${a.statusMessage}`)):g()}).end(k,"utf8")})};const getRunningTaskCount=async function(a,b,c,d,e){var f=new aws.ResourceGroupsTaggingAPI;const g=await f.getResources({ResourceTypeFilters:["ecs:service"],TagFilters:[{Key:"copilot-application",Values:[c]},{Key:"copilot-environment",Values:[d]},{Key:"copilot-service",Values:[e]}]}).promise(),h=g.ResourceTagMappingList;if(1!==h.length)return a;const i=h[0].ResourceARN;var j=new aws.ECS;const k=await j.describeServices({cluster:b,services:[i]}).promise();return 1===k.services.length?k.services[0].desiredCount:a};exports.handler=async function(a,b){var c,d={};const e=a.ResourceProperties;try{switch(a.RequestType){case"Create":d.DesiredCount=await getRunningTaskCount(e.DefaultDesiredCount,e.Cluster,e.App,e.Env,e.Svc),c=`copilot/apps/${e.App}/envs/${e.Env}/services/${e.Svc}/autoscaling`;break;case"Update":d.DesiredCount=await getRunningTaskCount(e.DefaultDesiredCount,e.Cluster,e.App,e.Env,e.Svc),c=a.PhysicalResourceId;break;case"Delete":c=a.PhysicalResourceId;break;default:throw new Error(`Unsupported request type ${a.RequestType}`);}await report(a,b,"SUCCESS",c,d)}catch(f){d.DesiredCount=e.DefaultDesiredCount,console.log(`Caught error ${f}. Set back desired count to ${d.DesiredCount}`),await report(a,b,"SUCCESS",c,d)}},exports.withDefaultResponseURL=function(a){defaultResponseURL=a};
221+
mockDynamicDesiredCountZipFile
222222
Handler: "index.handler"
223223
Timeout: 600
224224
MemorySize: 512
@@ -275,7 +275,7 @@ Resources:
275275
Properties:
276276
Code:
277277
ZipFile: |
278-
Abracadabra
278+
mockEnvControllerZipFile
279279
Handler: "index.handler"
280280
Timeout: 900
281281
MemorySize: 512
@@ -392,7 +392,7 @@ Resources:
392392
Properties:
393393
Code:
394394
ZipFile: |
395-
"use strict";const aws=require("aws-sdk"),priorityForRootRule="50000";let defaultResponseURL,report=function(a,b,c,d,e,f){return new Promise((g,h)=>{const i=require("https"),{URL:j}=require("url");var k=JSON.stringify({Status:c,Reason:f,PhysicalResourceId:d||b.logStreamName,StackId:a.StackId,RequestId:a.RequestId,LogicalResourceId:a.LogicalResourceId,Data:e});const l=new j(a.ResponseURL||defaultResponseURL),m={hostname:l.hostname,port:443,path:l.pathname+l.search,method:"PUT",headers:{"Content-Type":"","Content-Length":k.length}};i.request(m).on("error",h).on("response",a=>{a.resume(),400<=a.statusCode?h(new Error(`Error ${a.statusCode}: ${a.statusMessage}`)):g()}).end(k,"utf8")})};const calculateNextRulePriority=async function(a){var b,c=new aws.ELBv2,d=[];do{const e=await c.describeRules({ListenerArn:a,Marker:b}).promise();d=d.concat(e.Rules),b=e.NextMarker}while(b);let e=1;if(0<d.length){const a=d.map(a=>"default"===a.Priority||a.Priority===priorityForRootRule?0:parseInt(a.Priority)),b=Math.max(...a);e=b+1}return e};exports.nextAvailableRulePriorityHandler=async function(a,b){var c,d,e={};try{switch(a.RequestType){case"Create":d=await calculateNextRulePriority(a.ResourceProperties.ListenerArn),e.Priority=d,c=`alb-rule-priority-${a.LogicalResourceId}`;break;case"Update":case"Delete":c=a.PhysicalResourceId;break;default:throw new Error(`Unsupported request type ${a.RequestType}`);}await report(a,b,"SUCCESS",c,e)}catch(d){console.log(`Caught error ${d}.`),await report(a,b,"FAILED",c,null,d.message)}},exports.withDefaultResponseURL=function(a){defaultResponseURL=a};
395+
mockRulePriorityZipFile
396396
Handler: "index.nextAvailableRulePriorityHandler"
397397
Timeout: 600
398398
MemorySize: 512

internal/pkg/deploy/cloudformation/stack/testdata/workloads/svc-staging.stack.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ Resources:
216216
Properties:
217217
Code:
218218
ZipFile: |
219-
Abracadabra
219+
mockEnvControllerZipFile
220220
Handler: "index.handler"
221221
Timeout: 900
222222
MemorySize: 512
@@ -330,7 +330,7 @@ Resources:
330330
Properties:
331331
Code:
332332
ZipFile: |
333-
"use strict";const aws=require("aws-sdk"),priorityForRootRule="50000";let defaultResponseURL,report=function(a,b,c,d,e,f){return new Promise((g,h)=>{const i=require("https"),{URL:j}=require("url");var k=JSON.stringify({Status:c,Reason:f,PhysicalResourceId:d||b.logStreamName,StackId:a.StackId,RequestId:a.RequestId,LogicalResourceId:a.LogicalResourceId,Data:e});const l=new j(a.ResponseURL||defaultResponseURL),m={hostname:l.hostname,port:443,path:l.pathname+l.search,method:"PUT",headers:{"Content-Type":"","Content-Length":k.length}};i.request(m).on("error",h).on("response",a=>{a.resume(),400<=a.statusCode?h(new Error(`Error ${a.statusCode}: ${a.statusMessage}`)):g()}).end(k,"utf8")})};const calculateNextRulePriority=async function(a){var b,c=new aws.ELBv2,d=[];do{const e=await c.describeRules({ListenerArn:a,Marker:b}).promise();d=d.concat(e.Rules),b=e.NextMarker}while(b);let e=1;if(0<d.length){const a=d.map(a=>"default"===a.Priority||a.Priority===priorityForRootRule?0:parseInt(a.Priority)),b=Math.max(...a);e=b+1}return e};exports.nextAvailableRulePriorityHandler=async function(a,b){var c,d,e={};try{switch(a.RequestType){case"Create":d=await calculateNextRulePriority(a.ResourceProperties.ListenerArn),e.Priority=d,c=`alb-rule-priority-${a.LogicalResourceId}`;break;case"Update":case"Delete":c=a.PhysicalResourceId;break;default:throw new Error(`Unsupported request type ${a.RequestType}`);}await report(a,b,"SUCCESS",c,e)}catch(d){console.log(`Caught error ${d}.`),await report(a,b,"FAILED",c,null,d.message)}},exports.withDefaultResponseURL=function(a){defaultResponseURL=a};
333+
mockRulePriorityZipFile
334334
Handler: "index.nextAvailableRulePriorityHandler"
335335
Timeout: 600
336336
MemorySize: 512

0 commit comments

Comments
 (0)