...
1
16
17 package testing
18
19 import (
20 "bytes"
21 "fmt"
22 "os"
23 "path/filepath"
24 "testing"
25
26 "github.com/google/go-cmp/cmp"
27 "k8s.io/apimachinery/pkg/runtime"
28 "k8s.io/apimachinery/pkg/runtime/schema"
29 "k8s.io/apimachinery/pkg/runtime/serializer"
30 )
31
32
33 type TestCase struct {
34 name, in, out string
35 codec runtime.Codec
36 }
37
38
39
40 func RunTestsOnYAMLData(t *testing.T, tests []TestCase) {
41 for _, tc := range tests {
42 t.Run(tc.name, func(t *testing.T) {
43 roundTrip(t, tc)
44 })
45 }
46 }
47
48 func decodeYAML(t *testing.T, path string, codec runtime.Codec) runtime.Object {
49 content, err := os.ReadFile(path)
50 if err != nil {
51 t.Fatal(err)
52 }
53
54
55 object, err := runtime.Decode(codec, content)
56 if err != nil {
57 t.Fatal(err)
58 }
59
60 return object
61 }
62
63 func getCodecForGV(codecs serializer.CodecFactory, gv schema.GroupVersion) (runtime.Codec, error) {
64 mediaType := runtime.ContentTypeYAML
65 serializerInfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)
66 if !ok {
67 return nil, fmt.Errorf("unable to locate encoder -- %q is not a supported media type", mediaType)
68 }
69 codec := codecs.CodecForVersions(serializerInfo.Serializer, codecs.UniversalDeserializer(), gv, nil)
70 return codec, nil
71 }
72
73 func matchOutputFile(t *testing.T, actual []byte, expectedFilePath string) {
74 expected, err := os.ReadFile(expectedFilePath)
75 if err != nil && !os.IsNotExist(err) {
76 t.Fatalf("couldn't read test data: %v", err)
77 }
78
79 needsUpdate := false
80 const updateEnvVar = "UPDATE_COMPONENTCONFIG_FIXTURE_DATA"
81
82 if os.IsNotExist(err) {
83 needsUpdate = true
84 if os.Getenv(updateEnvVar) != "true" {
85 t.Error("couldn't find test data")
86 }
87 } else {
88 if !bytes.Equal(expected, actual) {
89 t.Errorf("Output does not match expected, diff (- want, + got):\n%s\n",
90 cmp.Diff(string(expected), string(actual)))
91 needsUpdate = true
92 }
93 }
94 if needsUpdate {
95 if os.Getenv(updateEnvVar) == "true" {
96 if err := os.MkdirAll(filepath.Dir(expectedFilePath), 0755); err != nil {
97 t.Fatal(err)
98 }
99 if err := os.WriteFile(expectedFilePath, actual, 0644); err != nil {
100 t.Fatal(err)
101 }
102 t.Error("wrote expected test data... verify, commit, and rerun tests")
103 } else {
104 t.Errorf("if the diff is expected because of a new type or a new field, "+
105 "re-run with %s=true to update the compatibility data or generate missing files", updateEnvVar)
106 }
107 }
108 }
109
View as plain text