providers/aws: no empty security groups when flattening ip perms

/cc @pearkes - A few things here:

First, this fixes the issue you mentioned to be in chat. Basically: if
there are no security groups, don't put it into flatten, because flatten
will include a "key.#" = "0".

Next, I transformed your test into a "table-driven" test which are really
nice to write and maintain. Basically, as you find bugs or edge cases, you can
just add to the table and you get the test for free. I recommend these
whereever you have a pure input to output sort of data transformation
function.
This commit is contained in:
Mitchell Hashimoto 2014-07-16 18:32:36 -07:00
parent bcc6f884b1
commit 79dbd07679
2 changed files with 57 additions and 21 deletions

View File

@ -80,7 +80,11 @@ func flattenIPPerms(list []ec2.IPPerm) []map[string]interface{} {
n["protocol"] = perm.Protocol n["protocol"] = perm.Protocol
n["to_port"] = perm.ToPort n["to_port"] = perm.ToPort
n["cidr_blocks"] = perm.SourceIPs n["cidr_blocks"] = perm.SourceIPs
n["security_groups"] = flattenSecurityGroups(perm.SourceGroups)
if v := flattenSecurityGroups(perm.SourceGroups); len(v) > 0 {
n["security_groups"] = v
}
result = append(result, n) result = append(result, n)
} }

View File

@ -56,31 +56,63 @@ func Test_expandIPPerms(t *testing.T) {
} }
func Test_flattenIPPerms(t *testing.T) { func Test_flattenIPPerms(t *testing.T) {
rawIp := []ec2.IPPerm{ cases := []struct {
ec2.IPPerm{ Input []ec2.IPPerm
Protocol: "icmp", Output []map[string]interface{}
FromPort: 1, }{
ToPort: -1, {
SourceIPs: []string{"0.0.0.0/0"}, Input: []ec2.IPPerm{
SourceGroups: []ec2.UserSecurityGroup{ ec2.IPPerm{
ec2.UserSecurityGroup{ Protocol: "icmp",
Id: "sg-11111", FromPort: 1,
ToPort: -1,
SourceIPs: []string{"0.0.0.0/0"},
SourceGroups: []ec2.UserSecurityGroup{
ec2.UserSecurityGroup{
Id: "sg-11111",
},
},
},
},
Output: []map[string]interface{}{
map[string]interface{}{
"protocol": "icmp",
"from_port": 1,
"to_port": -1,
"cidr_blocks": []string{"0.0.0.0/0"},
"security_groups": []string{"sg-11111"},
},
},
},
{
Input: []ec2.IPPerm{
ec2.IPPerm{
Protocol: "icmp",
FromPort: 1,
ToPort: -1,
SourceIPs: []string{"0.0.0.0/0"},
SourceGroups: nil,
},
},
Output: []map[string]interface{}{
map[string]interface{}{
"protocol": "icmp",
"from_port": 1,
"to_port": -1,
"cidr_blocks": []string{"0.0.0.0/0"},
}, },
}, },
}, },
} }
toFlatten := make(map[string]interface{}) for _, tc := range cases {
toFlatten["ingress"] = flattenIPPerms(rawIp) output := flattenIPPerms(tc.Input)
if !reflect.DeepEqual(output, tc.Output) {
perms := flatmap.Flatten(toFlatten) t.Fatalf("Input:\n\n%#v\n\nOutput:\n\n%#v", tc.Input, output)
}
if perms["ingress.0.protocol"] != "icmp" {
t.Fatalf("bad protocol")
}
if perms["ingress.0.security_groups.0"] != "sg-11111" {
t.Fatalf("bad security group")
} }
} }