...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package testyaml
16
17 import (
18 "io/ioutil"
19 "reflect"
20 "testing"
21
22 cnrmyaml "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/yaml"
23
24 "github.com/ghodss/yaml"
25 "github.com/google/go-cmp/cmp"
26 )
27
28 func SplitYAML(t *testing.T, yamlBytes []byte) [][]byte {
29 t.Helper()
30 result, err := cnrmyaml.SplitYAML(yamlBytes)
31 if err != nil {
32 t.Fatalf("error splitting YAML: %v", err)
33 }
34 return result
35 }
36
37 func WriteValueToFile(t *testing.T, value interface{}, filePath string) {
38 t.Helper()
39 bytes, err := yaml.Marshal(value)
40 if err != nil {
41 t.Fatalf("error marshalling value '%v' with kind '%v': %v", value, reflect.TypeOf(value).Name(), err)
42 }
43 WriteFile(t, bytes, filePath)
44 }
45
46 func WriteFile(t *testing.T, yamlBytes []byte, filePath string) {
47 t.Helper()
48 if err := ioutil.WriteFile(filePath, yamlBytes, 0644); err != nil {
49 t.Fatalf("error writing file '%v': %v", filePath, err)
50 }
51 }
52
53 func UnmarshalFile(t *testing.T, filePath string, value interface{}) {
54 t.Helper()
55 bytes, err := ioutil.ReadFile(filePath)
56 if err != nil {
57 t.Fatalf("error reading file '%v': %v", filePath, err)
58 }
59 if err := yaml.Unmarshal(bytes, &value); err != nil {
60 t.Fatalf("error unmarshalling bytes to '%v': %v\n\nstring value:\n\n%v", reflect.TypeOf(value).Name(), err, string(bytes))
61 }
62 }
63
64 func AssertFileContentsMatchValue(t *testing.T, expectedFilePath string, actualValue interface{}) {
65 t.Helper()
66 newValue := reflect.New(reflect.TypeOf(actualValue)).Interface()
67 UnmarshalFile(t, expectedFilePath, newValue)
68 expectedValue := reflect.ValueOf(newValue).Elem().Interface()
69 if !reflect.DeepEqual(expectedValue, actualValue) {
70 diff := cmp.Diff(expectedValue, actualValue)
71 t.Fatalf("mismatch between actual type and expected for type '%v', diff:\n%v", reflect.TypeOf(actualValue).Name(), diff)
72 }
73 }
74
View as plain text