Skip to content

Commit

Permalink
test: restore previously removed integ tests (aws#2580)
Browse files Browse the repository at this point in the history
Two integration test cases were removed by aws#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 #aws#2536

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
  • Loading branch information
Lou1415926 committed Jul 9, 2021
1 parent de7dc32 commit c664b4e
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,71 +25,93 @@ import (

const (
svcManifestPath = "svc-manifest.yml"
svcStackPath = "svc-test.stack.yml"
svcParamsPath = "svc-test.params.json"

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

func TestLoadBalancedWebService_Template(t *testing.T) {
testCases := map[string]struct {
envName string
svcStackPath string
svcParamsPath string
}{
"default env": {
envName: "test",
svcStackPath: "svc-test.stack.yml",
svcParamsPath: "svc-test.params.json",
},
"staging env": {
envName: "staging",
svcStackPath: "svc-staging.stack.yml",
svcParamsPath: "svc-staging.params.json",
},
"prod env": {
envName: "prod",
svcStackPath: "svc-prod.stack.yml",
svcParamsPath: "svc-prod.params.json",
},
}
path := filepath.Join("testdata", "workloads", svcManifestPath)
manifestBytes, err := ioutil.ReadFile(path)
require.NoError(t, err)
mft, err := manifest.UnmarshalWorkload(manifestBytes)
require.NoError(t, err)
envMft, err := mft.ApplyEnv(envName)
require.NoError(t, err)
v, ok := envMft.(*manifest.LoadBalancedWebService)
require.True(t, ok)

serializer, err := stack.NewHTTPSLoadBalancedWebService(v, envName, appName, stack.RuntimeConfig{})

tpl, err := serializer.Template()
require.NoError(t, err, "template should render")
regExpGUID := regexp.MustCompile(`([a-f\d]{8}-)([a-f\d]{4}-){3}([a-f\d]{12})`) // Matches random guids
testName := fmt.Sprintf("CF Template should be equal")
parser := template.New()
envController, err := parser.Read(envControllerPath)
require.NoError(t, err)
envControllerZipFile := envController.String()
dynamicDesiredCount, err := parser.Read(dynamicDesiredCountPath)
require.NoError(t, err)
dynamicDesiredCountZipFile := dynamicDesiredCount.String()
rulePriority, err := parser.Read(rulePriorityPath)
require.NoError(t, err)
rulePriorityZipFile := rulePriority.String()

t.Run(testName, func(t *testing.T) {
actualBytes := []byte(tpl)
// Cut random GUID from template.
actualBytes = regExpGUID.ReplaceAll(actualBytes, []byte("RandomGUID"))
actualString := string(actualBytes)
// Cut out zip file for more readable output
actualString = strings.ReplaceAll(actualString, envControllerZipFile, "mockEnvControllerZipFile")
actualString = strings.ReplaceAll(actualString, dynamicDesiredCountZipFile, "mockDynamicDesiredCountZipFile")
actualString = strings.ReplaceAll(actualString, rulePriorityZipFile, "mockRulePriorityZipFile")
actualBytes = []byte(actualString)
mActual := make(map[interface{}]interface{})
require.NoError(t, yaml.Unmarshal(actualBytes, mActual))

expected, err := ioutil.ReadFile(filepath.Join("testdata", "workloads", svcStackPath))
require.NoError(t, err, "should be able to read expected bytes")
expectedBytes := []byte(expected)
mExpected := make(map[interface{}]interface{})
require.NoError(t, yaml.Unmarshal(expectedBytes, mExpected))
require.Equal(t, mExpected, mActual)
})

testName = fmt.Sprintf("Parameter values should render properly")
t.Run(testName, func(t *testing.T) {
actualParams, err := serializer.SerializedParameters()
for name, tc := range testCases {
envMft, err := mft.ApplyEnv(tc.envName)
require.NoError(t, err)
v, ok := envMft.(*manifest.LoadBalancedWebService)
require.True(t, ok)

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

require.Equal(t, string(wantedCFNParamsBytes), actualParams)
})
tpl, err := serializer.Template()
require.NoError(t, err, "template should render")
regExpGUID := regexp.MustCompile(`([a-f\d]{8}-)([a-f\d]{4}-){3}([a-f\d]{12})`) // Matches random guids
testName := fmt.Sprintf("CF Template should be equal/%s", name)
parser := template.New()
envController, err := parser.Read(envControllerPath)
require.NoError(t, err)
envControllerZipFile := envController.String()
dynamicDesiredCount, err := parser.Read(dynamicDesiredCountPath)
require.NoError(t, err)
dynamicDesiredCountZipFile := dynamicDesiredCount.String()
rulePriority, err := parser.Read(rulePriorityPath)
require.NoError(t, err)
rulePriorityZipFile := rulePriority.String()

t.Run(testName, func(t *testing.T) {
actualBytes := []byte(tpl)
// Cut random GUID from template.
actualBytes = regExpGUID.ReplaceAll(actualBytes, []byte("RandomGUID"))
actualString := string(actualBytes)
// Cut out zip file for more readable output
actualString = strings.ReplaceAll(actualString, envControllerZipFile, "mockEnvControllerZipFile")
actualString = strings.ReplaceAll(actualString, dynamicDesiredCountZipFile, "mockDynamicDesiredCountZipFile")
actualString = strings.ReplaceAll(actualString, rulePriorityZipFile, "mockRulePriorityZipFile")
actualBytes = []byte(actualString)
mActual := make(map[interface{}]interface{})
require.NoError(t, yaml.Unmarshal(actualBytes, mActual))

expected, err := ioutil.ReadFile(filepath.Join("testdata", "workloads", tc.svcStackPath))
require.NoError(t, err, "should be able to read expected bytes")
expectedBytes := []byte(expected)
mExpected := make(map[interface{}]interface{})
require.NoError(t, yaml.Unmarshal(expectedBytes, mExpected))
require.Equal(t, mExpected, mActual)
})

testName = fmt.Sprintf("Parameter values should render properly/%s", name)
t.Run(testName, func(t *testing.T) {
actualParams, err := serializer.SerializedParameters()
require.NoError(t, err)

path := filepath.Join("testdata", "workloads", tc.svcParamsPath)
wantedCFNParamsBytes, err := ioutil.ReadFile(path)
require.NoError(t, err)

require.Equal(t, string(wantedCFNParamsBytes), actualParams)
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ Resources:
Properties:
Code:
ZipFile: |
"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};
mockDynamicDesiredCountZipFile
Handler: "index.handler"
Timeout: 600
MemorySize: 512
Expand Down Expand Up @@ -275,7 +275,7 @@ Resources:
Properties:
Code:
ZipFile: |
Abracadabra
mockEnvControllerZipFile
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Expand Down Expand Up @@ -392,7 +392,7 @@ Resources:
Properties:
Code:
ZipFile: |
"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};
mockRulePriorityZipFile
Handler: "index.nextAvailableRulePriorityHandler"
Timeout: 600
MemorySize: 512
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ Resources:
Properties:
Code:
ZipFile: |
Abracadabra
mockEnvControllerZipFile
Handler: "index.handler"
Timeout: 900
MemorySize: 512
Expand Down Expand Up @@ -330,7 +330,7 @@ Resources:
Properties:
Code:
ZipFile: |
"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};
mockRulePriorityZipFile
Handler: "index.nextAvailableRulePriorityHandler"
Timeout: 600
MemorySize: 512
Expand Down

0 comments on commit c664b4e

Please sign in to comment.