...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package serialization
16
17 import (
18 "fmt"
19 "io/ioutil"
20 "regexp"
21 "strings"
22 "testing"
23
24 tfprovider "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/tf/provider"
25 "github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
26 "gopkg.in/yaml.v2"
27 )
28
29 func TestSerializeInstance(t *testing.T) {
30 testSerialize(t, "testdata/instance.terraform.instancestate", "google_compute_instance", "testdata/instance.golden.tf")
31 }
32
33 func TestSerializeCluster(t *testing.T) {
34 testSerialize(t, "testdata/cluster.terraform.instancestate", "google_container_cluster", "testdata/cluster.golden.tf")
35 }
36
37 func testSerialize(t *testing.T, instanceStateFile, tfType, goldenFile string) string {
38 provider := tfprovider.NewOrLogFatal(tfprovider.DefaultConfig)
39 b, err := ioutil.ReadFile(instanceStateFile)
40 if err != nil {
41 t.Fatalf("failed to load instance state for instance, %s", err.Error())
42 }
43 is := &terraform.InstanceState{}
44 yaml.Unmarshal(b, &is)
45 info := &terraform.InstanceInfo{
46 Id: "foo",
47 Type: tfType,
48 }
49 out, err := InstanceStateToHCL(is, info, provider)
50 if err != nil {
51 t.Fatalf("failed to create HCL: %s", err.Error())
52 }
53
54 fmt.Println(out)
55 if err != nil {
56 t.Fatal(err)
57 }
58 golden, err := ioutil.ReadFile(goldenFile)
59 if err != nil {
60 t.Fatal(err)
61 }
62 goldenLines := strings.Split(string(golden), "\n")
63 for linenum, line := range strings.Split(out, "\n") {
64 if !stringContains(goldenLines, line) {
65 t.Fatalf("golden value didn't match provided value: line %d, %q, not in golden.", linenum, line)
66 }
67 }
68 return out
69 }
70
71 func stringContains(ss []string, s string) bool {
72 re := regexp.MustCompile(`\s*=\s*`)
73 for _, sss := range ss {
74 if re.ReplaceAllString(sss, " = ") == re.ReplaceAllString(s, " = ") {
75 return true
76 }
77 }
78 return false
79 }
80
View as plain text