blob: 41fe8dcc52b760847f755181ba0fe681db542c27 [file] [log] [blame]
Serge Bazanskibe538db2020-11-12 00:22:42 +01001// Copyright 2017 The kubecfg authors
2//
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16package utils
17
18import (
19 "encoding/json"
20 "reflect"
21 "sort"
22 "testing"
23)
24
25func TestJsonWalk(t *testing.T) {
26 fooObj := map[string]interface{}{
27 "apiVersion": "test",
28 "kind": "Foo",
29 }
30 barObj := map[string]interface{}{
31 "apiVersion": "test",
32 "kind": "Bar",
33 }
34
35 tests := []struct {
36 input string
37 result []interface{}
38 error string
39 }{
40 {
41 // nil input
42 input: `null`,
43 result: []interface{}{},
44 },
45 {
46 // single basic object
47 input: `{"apiVersion": "test", "kind": "Foo"}`,
48 result: []interface{}{fooObj},
49 },
50 {
51 // array of objects
52 input: `[{"apiVersion": "test", "kind": "Foo"}, {"apiVersion": "test", "kind": "Bar"}]`,
53 result: []interface{}{barObj, fooObj},
54 },
55 {
56 // object of objects
57 input: `{"foo": {"apiVersion": "test", "kind": "Foo"}, "bar": {"apiVersion": "test", "kind": "Bar"}}`,
58 result: []interface{}{barObj, fooObj},
59 },
60 {
61 // Deeply nested
62 input: `{"foo": [[{"apiVersion": "test", "kind": "Foo"}], {"apiVersion": "test", "kind": "Bar"}]}`,
63 result: []interface{}{barObj, fooObj},
64 },
65 {
66 // Error: nested misplaced value
67 input: `{"foo": {"bar": [null, 42]}}`,
68 error: "Looking for kubernetes object at <top>.foo.bar[1], but instead found float64",
69 },
70 }
71
72 for i, test := range tests {
73 t.Logf("%d: %s", i, test.input)
74 var top interface{}
75 if err := json.Unmarshal([]byte(test.input), &top); err != nil {
76 t.Errorf("Failed to unmarshal %q: %v", test.input, err)
77 continue
78 }
79 objs, err := jsonWalk(&walkContext{label: "<top>"}, top)
80 if test.error != "" {
81 // expect error
82 if err == nil {
83 t.Errorf("Test %d failed to fail", i)
84 } else if err.Error() != test.error {
85 t.Errorf("Test %d failed with %q but expected %q", i, err, test.error)
86 }
87
88 continue
89 }
90
91 // expect success
92 if err != nil {
93 t.Errorf("Test %d failed: %v", i, err)
94 continue
95 }
96 keyFunc := func(i int) string {
97 v := objs[i].(map[string]interface{})
98 return v["kind"].(string)
99 }
100 sort.Slice(objs, func(i, j int) bool {
101 return keyFunc(i) < keyFunc(j)
102 })
103 if !reflect.DeepEqual(objs, test.result) {
104 t.Errorf("Expected %v, got %v", test.result, objs)
105 }
106 }
107}