...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package krmtotf_test
16
17 import (
18 "testing"
19
20 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
21 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/krmtotf"
22
23 tfprovider "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/tf/provider"
24 tfschema "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
25 "github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
26 )
27
28 func TestSetBlueprintAttribution(t *testing.T) {
29 tests := []struct {
30 name string
31 withAttribution bool
32 input *terraform.InstanceState
33 }{
34 {
35 name: "existing input, with attribution",
36 withAttribution: true,
37 input: &terraform.InstanceState{ID: "test"},
38 },
39 {
40 name: "nil input, with attribution",
41 withAttribution: true,
42 input: nil,
43 },
44 {
45 name: "existing input, no attribution",
46 withAttribution: false,
47 input: &terraform.InstanceState{ID: "test"},
48 },
49 {
50 name: "nil input, no attribution",
51 withAttribution: false,
52 input: nil,
53 },
54 }
55 expectedAttribution := "blueprints/test"
56 provider := tfprovider.NewOrLogFatal(tfprovider.DefaultConfig)
57 for _, tc := range tests {
58 t.Run(tc.name, func(t *testing.T) {
59 resource := &krmtotf.Resource{}
60 if tc.withAttribution {
61 k8s.SetAnnotation(k8s.BlueprintAttributionAnnotation, "test", resource)
62 }
63 output := krmtotf.SetBlueprintAttribution(tc.input, resource, provider)
64 blueprint, found := getModuleName(output, provider)
65 if tc.withAttribution {
66 if !found {
67 t.Fatalf("blueprint attribution not set")
68 }
69 if blueprint != expectedAttribution {
70 t.Fatalf("actual: %v, expected: %v", blueprint, expectedAttribution)
71 }
72 } else {
73 if found {
74 t.Fatalf("module name set to %v despite no attribution expected", blueprint)
75 }
76 }
77 })
78 }
79 }
80
81 func getModuleName(state *terraform.InstanceState, provider *tfschema.Provider) (string, bool) {
82 if state == nil || state.ProviderMeta.IsNull() {
83 return "", false
84 }
85 meta := krmtotf.CtyValToMap(state.ProviderMeta, tfschema.InternalMap(provider.ProviderMetaSchema).CoreConfigSchema().ImpliedType())
86 val, ok := meta["module_name"]
87 if !ok {
88 return "", false
89 }
90 return val.(string), true
91 }
92
View as plain text