-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathcty_test_diff.go
88 lines (73 loc) · 2.39 KB
/
cty_test_diff.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
package test
import (
"fmt"
"strings"
"testing"
"github.com/snyk/driftctl/enumeration/terraform"
"github.com/snyk/driftctl/test/goldenfile"
"github.com/zclconf/go-cty/cty/json"
"github.com/snyk/driftctl/enumeration/resource"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/r3labs/diff/v2"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/gocty"
)
func doTestDiff(got []*resource.Resource, dirName string, provider terraform.TerraformProvider, deserializer *resource.Deserializer, shouldUpdate bool) (diff.Changelog, error) {
resources := make(map[string][]resource.Attributes)
for _, r := range got {
res, exist := resources[r.ResourceType()]
if !exist {
resources[r.ResourceType()] = []resource.Attributes{*r.Attributes()}
continue
}
resources[r.ResourceType()] = append(res, *r.Attributes())
}
expectedResources := []*resource.Resource{}
for ty, resList := range resources {
resGoldenName := goldenfile.ResultsFilename
if len(resources) > 1 {
resGoldenName = fmt.Sprintf("results.%s.golden.json", ty)
}
ctyType := cty.List(provider.Schema()[ty].Block.ImpliedType())
if shouldUpdate {
ctVal, err := gocty.ToCtyValue(resList, ctyType)
if err != nil {
panic(err)
}
unm, err := json.Marshal(ctVal, ctyType)
if err != nil {
panic(err)
}
goldenfile.WriteFile(dirName, unm, resGoldenName)
}
file := goldenfile.ReadFile(dirName, resGoldenName)
decodedJson, err := json.Unmarshal(file, ctyType)
if err != nil {
panic(err)
}
decodedResources, err := deserializer.Deserialize(ty, decodedJson.AsValueSlice())
if err != nil {
panic(err)
}
expectedResources = append(expectedResources, decodedResources...)
}
differ, err := diff.NewDiffer(diff.SliceOrdering(true))
if err != nil {
panic(err)
}
got = resource.Sort(got)
expectedResources = resource.Sort(expectedResources)
return differ.Diff(got, expectedResources)
}
// CtyTestDiff Deprecated
func CtyTestDiff(got []*resource.Resource, dirName string, provider terraform.TerraformProvider, deserializer *resource.Deserializer, shouldUpdate bool, t *testing.T) {
changelog, err := doTestDiff(got, dirName, provider, deserializer, shouldUpdate)
if err != nil {
panic(err)
}
if len(changelog) > 0 {
for _, change := range changelog {
t.Errorf("%s got = %v, want %v", strings.Join(change.Path, "."), awsutil.Prettify(change.From), awsutil.Prettify(change.To))
}
}
}