...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package testcontroller
16
17 import (
18 "strings"
19 "testing"
20
21 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/core/v1alpha1"
22 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
23
24 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
25 )
26
27 func AssertServerGeneratedResourceIDMatch(t *testing.T, reconciledResourceID string, appliedUnstruct *unstructured.Unstructured) {
28 t.Helper()
29
30 appliedResourceID, foundInAppliedSpec := GetResourceID(t, appliedUnstruct)
31 if foundInAppliedSpec && reconciledResourceID != appliedResourceID {
32 t.Fatalf("resourceID should never be changed if specified; "+
33 "resourceID before reconciliation: '%s', resourceID after "+
34 "reconciliation: '%s'", appliedResourceID, reconciledResourceID)
35 }
36 }
37
38 func AssertUserSpecifiedResourceIDMatch(t *testing.T, reconciledResourceID string, appliedUnstruct *unstructured.Unstructured) {
39 t.Helper()
40
41 appliedResourceID, foundInAppliedSpec := GetResourceID(t, appliedUnstruct)
42
43 if !foundInAppliedSpec && reconciledResourceID != appliedUnstruct.GetName() {
44 t.Fatalf("resourceID must be the same as the value of "+
45 "'metadata.name' if '%s' is not specified; 'metadata.name': "+
46 "'%s', resourceID after reconciliation: '%s'",
47 k8s.ResourceIDFieldPath, appliedUnstruct.GetName(),
48 reconciledResourceID)
49 }
50
51 if foundInAppliedSpec && reconciledResourceID != appliedResourceID {
52 t.Fatalf("resourceID should never be changed if specified; "+
53 "resourceID before reconciliation: '%s', resourceID after "+
54 "reconciliation: '%s'", appliedResourceID, reconciledResourceID)
55 }
56 }
57
58
59 func SupportsResourceIDField(rc *v1alpha1.ResourceConfig) bool {
60 return rc.ResourceID.TargetField != ""
61 }
62
63
64 func IsResourceIDFieldServerGenerated(rc *v1alpha1.ResourceConfig) bool {
65 return rc.ResourceID.TargetField == rc.ServerGeneratedIDField &&
66 rc.ServerGeneratedIDField != ""
67 }
68
69 func GetResourceID(t *testing.T, resourceUnstruct *unstructured.Unstructured) (string, bool) {
70 resourceID, found, err := unstructured.NestedString(resourceUnstruct.Object, "spec", k8s.ResourceIDFieldName)
71 if err != nil {
72 t.Fatalf("error getting '%s': %v", k8s.ResourceIDFieldPath, err)
73 }
74
75 return resourceID, found
76 }
77
78 func SetResourceID(t *testing.T, u *unstructured.Unstructured, val string) {
79 if err := unstructured.SetNestedField(u.Object, val, strings.Split(k8s.ResourceIDFieldPath, ".")...); err != nil {
80 t.Fatalf("error setting '%s' on unstruct: %v", k8s.ResourceIDFieldPath, err)
81 }
82 }
83
84 func RemoveResourceID(u *unstructured.Unstructured) {
85 unstructured.RemoveNestedField(u.Object, strings.Split(k8s.ResourceIDFieldPath, ".")...)
86 }
87
View as plain text