Debian Codegraph @

pkg/cel/value_test.go

raw
1 /*
2 Copyright 2022 The Kubernetes Authors.
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 */
16
17 package cel
18
19 import (
20 "fmt"
21 "reflect"
22 "testing"
23 "time"
24
25 "github.com/google/cel-go/common/types"
26 "github.com/google/cel-go/common/types/ref"
27 "github.com/google/cel-go/common/types/traits"
28 )
29
30 func TestConvertToType(t *testing.T) {
31 objType := NewObjectType("TestObject", map[string]*DeclField{})
32 tests := []struct {
33 val interface{}
34 typ ref.Type
35 }{
36 {true, types.BoolType},
37 {float64(1.2), types.DoubleType},
38 {int64(-42), types.IntType},
39 {uint64(63), types.UintType},
40 {time.Duration(300), types.DurationType},
41 {time.Now().UTC(), types.TimestampType},
42 {types.NullValue, types.NullType},
43 {NewListValue(), types.ListType},
44 {NewMapValue(), types.MapType},
45 {[]byte("bytes"), types.BytesType},
46 {NewObjectValue(objType), objType},
47 }
48 for i, tc := range tests {
49 idx := i
50 tst := tc
51 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
52 dv := testValue(t, int64(idx), tst.val)
53 ev := dv.ExprValue()
54 if ev.ConvertToType(types.TypeType).(ref.Type).TypeName() != tst.typ.TypeName() {
55 t.Errorf("got %v, wanted %v type", ev.ConvertToType(types.TypeType), tst.typ)
56 }
57 if ev.ConvertToType(tst.typ).Equal(ev) != types.True {
58 t.Errorf("got %v, wanted input value %v", ev.ConvertToType(tst.typ), ev)
59 }
60 })
61 }
62 }
63
64 func TestEqual(t *testing.T) {
65 vals := []interface{}{
66 true, []byte("bytes"), float64(1.2), int64(-42), uint64(63), time.Duration(300),
67 time.Now().UTC(), types.NullValue, NewListValue(), NewMapValue(),
68 NewObjectValue(NewObjectType("TestObject", map[string]*DeclField{})),
69 }
70 for i, v := range vals {
71 dv := testValue(t, int64(i), v)
72 if dv.Equal(dv.ExprValue()) != types.True {
73 t.Errorf("got %v, wanted dyn value %v equal to itself", dv.Equal(dv.ExprValue()), dv.ExprValue())
74 }
75 }
76 }
77
78 func TestListValueAdd(t *testing.T) {
79 lv := NewListValue()
80 lv.Append(testValue(t, 1, "first"))
81 ov := NewListValue()
82 ov.Append(testValue(t, 2, "second"))
83 ov.Append(testValue(t, 3, "third"))
84 llv := NewListValue()
85 llv.Append(testValue(t, 4, lv))
86 lov := NewListValue()
87 lov.Append(testValue(t, 5, ov))
88 var v traits.Lister = llv.Add(lov).(traits.Lister)
89 if v.Size() != types.Int(2) {
90 t.Errorf("got list size %d, wanted 2", v.Size())
91 }
92 complex, err := v.ConvertToNative(reflect.TypeOf([][]string{}))
93 complexList := complex.([][]string)
94 if err != nil {
95 t.Fatal(err)
96 }
97 if !reflect.DeepEqual(complexList, [][]string{{"first"}, {"second", "third"}}) {
98 t.Errorf("got %v, wanted [['first'], ['second', 'third']]", complexList)
99 }
100 }
101
102 func TestListValueContains(t *testing.T) {
103 lv := NewListValue()
104 lv.Append(testValue(t, 1, "first"))
105 lv.Append(testValue(t, 2, "second"))
106 lv.Append(testValue(t, 3, "third"))
107 for i := types.Int(0); i < lv.Size().(types.Int); i++ {
108 e := lv.Get(i)
109 contained := lv.Contains(e)
110 if contained != types.True {
111 t.Errorf("got %v, wanted list contains elem[%v] %v == true", contained, i, e)
112 }
113 }
114 if lv.Contains(types.String("fourth")) != types.False {
115 t.Errorf("got %v, wanted false 'fourth'", lv.Contains(types.String("fourth")))
116 }
117 if !types.IsError(lv.Contains(types.Int(-1))) {
118 t.Errorf("got %v, wanted error for invalid type", lv.Contains(types.Int(-1)))
119 }
120 }
121
122 func TestListValueContainsNestedList(t *testing.T) {
123 lvA := NewListValue()
124 lvA.Append(testValue(t, 1, int64(1)))
125 lvA.Append(testValue(t, 2, int64(2)))
126
127 lvB := NewListValue()
128 lvB.Append(testValue(t, 3, int64(3)))
129
130 elemA, elemB := testValue(t, 4, lvA), testValue(t, 5, lvB)
131 lv := NewListValue()
132 lv.Append(elemA)
133 lv.Append(elemB)
134
135 contained := lv.Contains(elemA.ExprValue())
136 if contained != types.True {
137 t.Errorf("got %v, wanted elemA contained in list value", contained)
138 }
139 contained = lv.Contains(elemB.ExprValue())
140 if contained != types.True {
141 t.Errorf("got %v, wanted elemB contained in list value", contained)
142 }
143 contained = lv.Contains(types.DefaultTypeAdapter.NativeToValue([]int32{4}))
144 if contained != types.False {
145 t.Errorf("got %v, wanted empty list not contained", contained)
146 }
147 }
148
149 func TestListValueConvertToNative(t *testing.T) {
150 lv := NewListValue()
151 none, err := lv.ConvertToNative(reflect.TypeOf([]interface{}{}))
152 if err != nil {
153 t.Fatal(err)
154 }
155 if !reflect.DeepEqual(none, []interface{}{}) {
156 t.Errorf("got %v, wanted empty list", none)
157 }
158 lv.Append(testValue(t, 1, "first"))
159 one, err := lv.ConvertToNative(reflect.TypeOf([]string{}))
160 oneList := one.([]string)
161 if err != nil {
162 t.Fatal(err)
163 }
164 if len(oneList) != 1 {
165 t.Errorf("got len(one) == %d, wanted 1", len(oneList))
166 }
167 if !reflect.DeepEqual(oneList, []string{"first"}) {
168 t.Errorf("got %v, wanted string list", oneList)
169 }
170 ov := NewListValue()
171 ov.Append(testValue(t, 2, "second"))
172 ov.Append(testValue(t, 3, "third"))
173 if ov.Size() != types.Int(2) {
174 t.Errorf("got list size %d, wanted 2", ov.Size())
175 }
176 llv := NewListValue()
177 llv.Append(testValue(t, 4, lv))
178 llv.Append(testValue(t, 5, ov))
179 if llv.Size() != types.Int(2) {
180 t.Errorf("got list size %d, wanted 2", llv.Size())
181 }
182 complex, err := llv.ConvertToNative(reflect.TypeOf([][]string{}))
183 complexList := complex.([][]string)
184 if err != nil {
185 t.Fatal(err)
186 }
187 if !reflect.DeepEqual(complexList, [][]string{{"first"}, {"second", "third"}}) {
188 t.Errorf("got %v, wanted [['first'], ['second', 'third']]", complexList)
189 }
190 }
191
192 func TestListValueIterator(t *testing.T) {
193 lv := NewListValue()
194 lv.Append(testValue(t, 1, "first"))
195 lv.Append(testValue(t, 2, "second"))
196 lv.Append(testValue(t, 3, "third"))
197 it := lv.Iterator()
198 if it.Type() != types.IteratorType {
199 t.Errorf("got type %v for iterator, wanted IteratorType", it.Type())
200 }
201 i := types.Int(0)
202 for it.HasNext() == types.True {
203 v := it.Next()
204 if v.Equal(lv.Get(i)) != types.True {
205 t.Errorf("iterator value %v and value %v at index %d not equal", v, lv.Get(i), i)
206 }
207 i++
208 }
209 }
210
211 func TestMapValueConvertToNative(t *testing.T) {
212 mv := NewMapValue()
213 none, err := mv.ConvertToNative(reflect.TypeOf(map[string]interface{}{}))
214 if err != nil {
215 t.Fatal(err)
216 }
217 if !reflect.DeepEqual(none, map[string]interface{}{}) {
218 t.Errorf("got %v, wanted empty map", none)
219 }
220 none, err = mv.ConvertToNative(reflect.TypeOf(map[interface{}]interface{}{}))
221 if err != nil {
222 t.Fatal(err)
223 }
224 if !reflect.DeepEqual(none, map[interface{}]interface{}{}) {
225 t.Errorf("got %v, wanted empty map", none)
226 }
227 mv.AddField(NewField(1, "Test"))
228 tst, _ := mv.GetField("Test")
229 tst.Ref = testValue(t, 2, uint64(12))
230 mv.AddField(NewField(3, "Check"))
231 chk, _ := mv.GetField("Check")
232 chk.Ref = testValue(t, 4, uint64(34))
233 if mv.Size() != types.Int(2) {
234 t.Errorf("got size %d, wanted 2", mv.Size())
235 }
236 if mv.Contains(types.String("Test")) != types.True {
237 t.Error("key 'Test' not found")
238 }
239 if mv.Contains(types.String("Check")) != types.True {
240 t.Error("key 'Check' not found")
241 }
242 if mv.Contains(types.String("Checked")) != types.False {
243 t.Error("key 'Checked' found, wanted not found")
244 }
245 it := mv.Iterator()
246 for it.HasNext() == types.True {
247 k := it.Next()
248 v := mv.Get(k)
249 if k == types.String("Test") && v != types.Uint(12) {
250 t.Errorf("key 'Test' not equal to 12u")
251 }
252 if k == types.String("Check") && v != types.Uint(34) {
253 t.Errorf("key 'Check' not equal to 34u")
254 }
255 }
256 mpStrUint, err := mv.ConvertToNative(reflect.TypeOf(map[string]uint64{}))
257 if err != nil {
258 t.Fatal(err)
259 }
260 if !reflect.DeepEqual(mpStrUint, map[string]uint64{
261 "Test": uint64(12),
262 "Check": uint64(34),
263 }) {
264 t.Errorf("got %v, wanted {'Test': 12u, 'Check': 34u}", mpStrUint)
265 }
266 tstStr, err := mv.ConvertToNative(reflect.TypeOf(&tstStruct{}))
267 if err != nil {
268 t.Fatal(err)
269 }
270 if !reflect.DeepEqual(tstStr, &tstStruct{
271 Test: uint64(12),
272 Check: uint64(34),
273 }) {
274 t.Errorf("got %v, wanted tstStruct{Test: 12u, Check: 34u}", tstStr)
275 }
276 }
277
278 func TestMapValueEqual(t *testing.T) {
279 mv := NewMapValue()
280 name := NewField(1, "name")
281 name.Ref = testValue(t, 2, "alert")
282 priority := NewField(3, "priority")
283 priority.Ref = testValue(t, 4, int64(4))
284 mv.AddField(name)
285 mv.AddField(priority)
286 if mv.Equal(mv) != types.True {
287 t.Fatalf("map.Equal(map) failed: %v", mv.Equal(mv))
288 }
289 }
290
291 func TestMapValueNotEqual(t *testing.T) {
292 mv := NewMapValue()
293 name := NewField(1, "name")
294 name.Ref = testValue(t, 2, "alert")
295 priority := NewField(3, "priority")
296 priority.Ref = testValue(t, 4, int64(4))
297 mv.AddField(name)
298 mv.AddField(priority)
299
300 mv2 := NewMapValue()
301 mv2.AddField(name)
302 if mv.Equal(mv2) != types.False {
303 t.Fatalf("mv.Equal(mv2) failed: %v", mv.Equal(mv2))
304 }
305
306 priority2 := NewField(5, "priority")
307 priority2.Ref = testValue(t, 6, int64(3))
308 mv2.AddField(priority2)
309 if mv.Equal(mv2) != types.False {
310 t.Fatalf("mv.Equal(mv2) failed: %v", mv.Equal(mv2))
311 }
312 }
313
314 func TestMapValueIsSet(t *testing.T) {
315 mv := NewMapValue()
316 if mv.IsSet(types.String("name")) != types.False {
317 t.Error("map.IsSet('name') returned true for unset key")
318 }
319 mv.AddField(NewField(1, "name"))
320 if mv.IsSet(types.String("name")) != types.True {
321 t.Error("map.IsSet('name') returned false for a set key")
322 }
323 }
324
325 func TestObjectValueEqual(t *testing.T) {
326 objType := NewObjectType("Notice", map[string]*DeclField{
327 "name": {Name: "name", Type: StringType},
328 "priority": {Name: "priority", Type: IntType},
329 "message": {Name: "message", Type: StringType, defaultValue: "<eom>"},
330 })
331 name := NewField(1, "name")
332 name.Ref = testValue(t, 2, "alert")
333 priority := NewField(3, "priority")
334 priority.Ref = testValue(t, 4, int64(4))
335 message := NewField(5, "message")
336 message.Ref = testValue(t, 6, "call immediately")
337
338 mv1 := NewMapValue()
339 mv1.AddField(name)
340 mv1.AddField(priority)
341 obj1 := mv1.ConvertToObject(objType)
342 if obj1.Equal(obj1) != types.True {
343 t.Errorf("obj1.Equal(obj1) failed, got: %v", obj1.Equal(obj1))
344 }
345
346 mv2 := NewMapValue()
347 mv2.AddField(name)
348 mv2.AddField(priority)
349 mv2.AddField(message)
350 obj2 := mv2.ConvertToObject(objType)
351 if obj1.Equal(obj2) == types.True {
352 t.Error("obj1.Equal(obj2) returned true, wanted false")
353 }
354 if obj2.Equal(obj1) == types.True {
355 t.Error("obj2.Equal(obj1) returned true, wanted false")
356 }
357 }
358
359 type tstStruct struct {
360 Test uint64
361 Check uint64
362 }