Debian Codegraph @

ext/lists_test.go

raw symbols SCIP
1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package ext
16
17 import (
18 "fmt"
19 "strings"
20 "testing"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/checker"
24 "github.com/google/cel-go/common/types"
25
26 proto2pb "github.com/google/cel-go/test/proto2pb"
27 )
28
29 func TestLists(t *testing.T) {
30 listsTests := []struct {
31 expr string
32 err string
33 }{
34 {expr: `lists.range(4) == [0,1,2,3]`},
35 {expr: `lists.range(0) == []`},
36 {expr: `[5,1,2,3].reverse() == [3,2,1,5]`},
37 {expr: `[].reverse() == []`},
38 {expr: `[1].reverse() == [1]`},
39 {expr: `['are', 'you', 'as', 'bored', 'as', 'I', 'am'].reverse() == ['am', 'I', 'as', 'bored', 'as', 'you', 'are']`},
40 {expr: `[false, true, true].reverse().reverse() == [false, true, true]`},
41 {expr: `[1,2,3,4].slice(0, 4) == [1,2,3,4]`},
42 {expr: `[1,2,3,4].slice(0, 0) == []`},
43 {expr: `[1,2,3,4].slice(1, 1) == []`},
44 {expr: `[1,2,3,4].slice(4, 4) == []`},
45 {expr: `[1,2,3,4].slice(1, 3) == [2, 3]`},
46 {expr: `[1,2,3,4].slice(3, 0)`, err: "cannot slice(3, 0), start index must be less than or equal to end index"},
47 {expr: `[1,2,3,4].slice(0, 10)`, err: "cannot slice(0, 10), list is length 4"},
48 {expr: `[1,2,3,4].slice(-5, 10)`, err: "cannot slice(-5, 10), negative indexes not supported"},
49 {expr: `[1,2,3,4].slice(-5, -3)`, err: "cannot slice(-5, -3), negative indexes not supported"},
50
51 {expr: `dyn([]).flatten() == []`},
52 {expr: `dyn([1,2,3,4]).flatten() == [1,2,3,4]`},
53 {expr: `[1,[2,[3,4]]].flatten() == [1,2,[3,4]]`},
54 {expr: `[1,2,[],[],[3,4]].flatten() == [1,2,3,4]`},
55 {expr: `[1,[2,[3,4]]].flatten(2) == [1,2,3,4]`},
56 {expr: `[1,[2,[3,[4]]]].flatten(-1) == [1,2,3,4]`, err: "level must be non-negative"},
57 {expr: `[].sort() == []`},
58 {expr: `[1].sort() == [1]`},
59 {expr: `[4, 3, 2, 1].sort() == [1, 2, 3, 4]`},
60 {expr: `["d", "a", "b", "c"].sort() == ["a", "b", "c", "d"]`},
61 {expr: `["d", 3, 2, "c"].sort() == ["a", "b", "c", "d"]`, err: "list elements must have the same type"},
62 {expr: `[].sortBy(e, e) == []`},
63 {expr: `["a"].sortBy(e, e) == ["a"]`},
64 {expr: `[-3, 1, -5, -2, 4].sortBy(e, -(e * e)) == [-5, 4, -3, -2, 1]`},
65 {expr: `[-3, 1, -5, -2, 4].map(e, e * 2).sortBy(e, -(e * e)) == [-10, 8, -6, -4, 2]`},
66 {expr: `lists.range(3).sortBy(e, -e) == [2, 1, 0]`},
67 {expr: `["a", "c", "b", "first"].sortBy(e, e == "first" ? "" : e) == ["first", "a", "b", "c"]`},
68 {expr: `[ExampleType{name: 'foo'}, ExampleType{name: 'bar'}, ExampleType{name: 'baz'}].sortBy(e, e.name) == [ExampleType{name: 'bar'}, ExampleType{name: 'baz'}, ExampleType{name: 'foo'}]`},
69 {expr: `[].distinct() == []`},
70 {expr: `[1].distinct() == [1]`},
71 {expr: `[-2, 5, -2, 1, 1, 5, -2, 1].distinct() == [-2, 5, 1]`},
72 {expr: `['c', 'a', 'a', 'b', 'a', 'b', 'c', 'c'].distinct() == ['c', 'a', 'b']`},
73 {expr: `[1, 2.0, "c", 3, "c", 1].distinct() == [1, 2.0, "c", 3]`},
74 {expr: `[1, 1.0, 2].distinct() == [1, 2]`},
75 {expr: `[[1], [1], [2]].distinct() == [[1], [2]]`},
76 {expr: `[ExampleType{name: 'a'}, ExampleType{name: 'b'}, ExampleType{name: 'a'}].distinct() == [ExampleType{name: 'a'}, ExampleType{name: 'b'}]`},
77 }
78
79 env := testListsEnv(t)
80 for i, tst := range listsTests {
81 tc := tst
82 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
83 var asts []*cel.Ast
84 pAst, iss := env.Parse(tc.expr)
85 if iss.Err() != nil {
86 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
87 }
88 asts = append(asts, pAst)
89 cAst, iss := env.Check(pAst)
90 if iss.Err() != nil {
91 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
92 }
93 asts = append(asts, cAst)
94
95 for _, ast := range asts {
96 prg, err := env.Program(ast)
97 if err != nil {
98 t.Fatalf("env.Program() failed: %v", err)
99 }
100 out, _, err := prg.Eval(cel.NoVars())
101 if tc.err != "" {
102 if err == nil {
103 t.Fatalf("got value %v, wanted error %s for expr: %s",
104 out.Value(), tc.err, tc.expr)
105 }
106 if !strings.Contains(err.Error(), tc.err) {
107 t.Errorf("got error %v, wanted error %s for expr: %s", err, tc.err, tc.expr)
108 }
109 } else if err != nil {
110 t.Fatal(err)
111 } else if out.Value() != true {
112 t.Errorf("got %v, wanted true for expr: %s", out.Value(), tc.expr)
113 }
114 }
115 })
116 }
117 }
118
119 func TestListsRuntimeErrors(t *testing.T) {
120 env, err := cel.NewEnv(Lists(ListsVersion(1)))
121 if err != nil {
122 t.Fatalf("cel.NewEnv() failed: %v", err)
123 }
124 listsTests := []struct {
125 expr string
126 err string
127 }{
128 {
129 expr: "dyn({}).flatten()",
130 err: "no such overload",
131 },
132 {
133 expr: "dyn({}).flatten(0)",
134 err: "no such overload",
135 },
136 {
137 expr: "[].flatten(-1)",
138 err: "level must be non-negative",
139 },
140 {
141 expr: "[].flatten(dyn('1'))",
142 err: "no such overload",
143 },
144 }
145 for i, tst := range listsTests {
146 tc := tst
147 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
148 ast, iss := env.Compile(tc.expr)
149 if iss.Err() != nil {
150 t.Fatalf("env.Compile(%q) failed: %v", tc.expr, iss.Err())
151 }
152 prg, err := env.Program(ast)
153 if err != nil {
154 t.Fatalf("env.Program() failed: %v", err)
155 }
156 _, _, err = prg.Eval(cel.NoVars())
157 if err == nil || !strings.Contains(err.Error(), tc.err) {
158 t.Errorf("prg.Eval() got %v, wanted %v", err, tc.err)
159 }
160 })
161 }
162 }
163
164 func TestListsVersion(t *testing.T) {
165 versionCases := []struct {
166 version uint32
167 supportedFunctions map[string]string
168 }{
169 {
170 version: 0,
171 supportedFunctions: map[string]string{
172 "slice": "[1, 2, 3, 4, 5].slice(2, 4) == [3, 4]",
173 },
174 },
175 {
176 version: 1,
177 supportedFunctions: map[string]string{
178 "flatten": "[[1, 2], [3, 4]].flatten() == [1, 2, 3, 4]",
179 },
180 },
181 {
182 version: 2,
183 supportedFunctions: map[string]string{
184 "distinct": "[1, 2, 2, 1].distinct() == [1, 2]",
185 "range": "lists.range(5) == [0, 1, 2, 3, 4]",
186 "reverse": "[1, 2, 3].reverse() == [3, 2, 1]",
187 "sort": "[2, 1, 3].sort() == [1, 2, 3]",
188 "sortBy": "[{'field': 'lo'}, {'field': 'hi'}].sortBy(m, m.field) == [{'field': 'hi'}, {'field': 'lo'}]",
189 },
190 },
191 }
192 for _, lib := range versionCases {
193 env, err := cel.NewEnv(Lists(ListsVersion(lib.version)))
194 if err != nil {
195 t.Fatalf("cel.NewEnv(Lists(ListsVersion(%d))) failed: %v", lib.version, err)
196 }
197 t.Run(fmt.Sprintf("version=%d", lib.version), func(t *testing.T) {
198 for _, tc := range versionCases {
199 for name, expr := range tc.supportedFunctions {
200 supported := lib.version >= tc.version
201 t.Run(fmt.Sprintf("%s-supported=%t", name, supported), func(t *testing.T) {
202 ast, iss := env.Compile(expr)
203 if supported {
204 if iss.Err() != nil {
205 t.Errorf("unexpected error: %v", iss.Err())
206 }
207 } else {
208 if iss.Err() == nil || !strings.Contains(iss.Err().Error(), "undeclared reference") {
209 t.Errorf("got error %v, wanted error %s for expr: %s, version: %d", iss.Err(), "undeclared reference", expr, tc.version)
210 }
211 return
212 }
213 prg, err := env.Program(ast)
214 if err != nil {
215 t.Fatalf("env.Program() failed: %v", err)
216 }
217 out, _, err := prg.Eval(cel.NoVars())
218 if err != nil {
219 t.Fatalf("prg.Eval() failed: %v", err)
220 }
221 if out != types.True {
222 t.Errorf("prg.Eval() got %v, wanted true", out)
223 }
224 })
225 }
226 }
227 })
228 }
229 }
230
231 func TestListsCosts(t *testing.T) {
232 tests := []struct {
233 name string
234 expr string
235 vars []cel.EnvOption
236 in map[string]any
237 hints map[string]uint64
238 estimatedCost checker.CostEstimate
239 actualCost uint64
240 }{
241 {
242 // (1 array alloc + internal alloc) * 10
243 // + size(list)
244 // + 2 calls
245 name: "list_range",
246 expr: `lists.range(4) == [0, 1, 2, 3]`,
247 estimatedCost: checker.FixedCostEstimate(26),
248 actualCost: 26,
249 },
250 {
251 name: "list_range_computed",
252 expr: `lists.range(4 / 2) == [0, 1]`,
253 estimatedCost: checker.FixedCostEstimate(18446744073709551615),
254 actualCost: 25,
255 },
256 {
257 name: "list_range_var",
258 expr: `lists.range(x) == [0, 1, 2, 3, 4]`,
259 vars: []cel.EnvOption{cel.Variable("x", cel.IntType)},
260 in: map[string]any{"x": 5},
261 hints: map[string]uint64{"x": 10},
262 estimatedCost: checker.FixedCostEstimate(18446744073709551615),
263 actualCost: 28,
264 },
265 {
266 // (3 array allocs + internal alloc) * 10 + size(list) + 2 calls
267 name: "list_flatten_depth_one",
268 expr: `[[1, 2], 3].flatten(1) == [1, 2, 3]`,
269 estimatedCost: checker.FixedCostEstimate(44),
270 actualCost: 44,
271 },
272 {
273 // (3 array allocs + internal alloc) * 10 + size(list) * 2 + 2 calls
274 name: "list_flatten_depth_two",
275 expr: `[[1, 2], 3].flatten(2) == [1, 2, 3]`,
276 estimatedCost: checker.FixedCostEstimate(46),
277 actualCost: 46,
278 },
279 {
280 // (3 array allocs + internal alloc) * 10 + size(list) * 3 + 2 calls
281 name: "list_flatten_depth_three",
282 expr: `[[1, 2], 3].flatten(3) == [1, 2, 3]`,
283 estimatedCost: checker.FixedCostEstimate(48),
284 actualCost: 48,
285 },
286 {
287 name: "list_flatten",
288 expr: `[[1], 2, 3].flatten() == [1, 2, 3]`,
289 estimatedCost: checker.FixedCostEstimate(45),
290 actualCost: 45,
291 },
292 {
293 name: "list_flatten_var",
294 expr: `x.flatten() == [1, 2, 3]`,
295 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.DynType))},
296 in: map[string]any{"x": []any{[]any{1}, 2, 3}},
297 hints: map[string]uint64{"x": 3},
298 estimatedCost: checker.CostEstimate{Min: 23, Max: 26},
299 actualCost: 26,
300 },
301 {
302 name: "list_flatten_depth_var",
303 expr: `[[1, 2], 3].flatten(x) == [1, 2, 3]`,
304 vars: []cel.EnvOption{cel.Variable("x", cel.IntType)},
305 in: map[string]any{"x": 5},
306 hints: map[string]uint64{"x": 10},
307 estimatedCost: checker.FixedCostEstimate(18446744073709551615),
308 actualCost: 53,
309 },
310 {
311 // (2 array allocs + 1 internal) * 10
312 // + size(list) * size(list) * 2
313 // + 2 calls
314 name: "list_distinct_worst_case",
315 expr: `[1, 2, 3].distinct() == [1, 2, 3]`,
316 estimatedCost: checker.FixedCostEstimate(50),
317 actualCost: 50,
318 },
319 {
320 // (2 array allocs + 1 internal) * 10
321 // + size(list) * size(list) * 2
322 // + 2 calls
323 name: "list_distinct_best_case",
324 expr: `[1, 1, 1].distinct() == [1]`,
325 estimatedCost: checker.FixedCostEstimate(50),
326 actualCost: 50,
327 },
328 {
329 // (1 array alloc + 1 internal) * 20
330 // + [0, size(x) * size(x)] * 2 --> [0, 18]
331 // + 2 calls
332 // + 1 ident lookup
333 name: "list_distinct_var",
334 expr: `x.distinct() == ['hello']`,
335 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.StringType))},
336 in: map[string]any{"x": []string{"hello", "hello"}},
337 hints: map[string]uint64{"x": 3},
338 estimatedCost: checker.CostEstimate{Min: 23, Max: 41},
339 actualCost: 31,
340 },
341 {
342 // allocs: (2 + one internal) * 10
343 // max_slice cost: 5
344 // lookups: 2
345 // calls: 2
346 name: "list_slice_var_range",
347 expr: `[1, 2, 3, 4, 5].slice(x, y) == [2, 3]`,
348 vars: []cel.EnvOption{
349 cel.Variable("x", cel.IntType),
350 cel.Variable("y", cel.IntType),
351 },
352 in: map[string]any{"x": 1, "y": 3},
353 estimatedCost: checker.FixedCostEstimate(39),
354 actualCost: 36,
355 },
356 {
357 // allocs: (1 + one internal) * 10
358 // max_slice cost: 2
359 // lookups: 1
360 // calls: 2
361 name: "list_slice_var_list",
362 expr: `z.slice(1, 3) == [2, 3]`,
363 vars: []cel.EnvOption{
364 cel.Variable("x", cel.IntType),
365 cel.Variable("y", cel.IntType),
366 cel.Variable("z", cel.ListType(cel.IntType)),
367 },
368 in: map[string]any{"x": 1, "y": 3, "z": []int{1, 2, 3, 4, 5, 6, 7}},
369 hints: map[string]uint64{"z": 10},
370 estimatedCost: checker.FixedCostEstimate(25),
371 actualCost: 25,
372 },
373 {
374 // allocs: (1 + one internal) * 10
375 // max_slice cost: 10
376 // lookups: 3
377 // calls: 2
378 name: "list_slice_var_list_var_range",
379 expr: `z.slice(x, y) == [2, 3]`,
380 vars: []cel.EnvOption{
381 cel.Variable("x", cel.IntType),
382 cel.Variable("y", cel.IntType),
383 cel.Variable("z", cel.ListType(cel.IntType)),
384 },
385 in: map[string]any{"x": 1, "y": 3, "z": []int{1, 2, 3, 4, 5, 6, 7}},
386 hints: map[string]uint64{"z": 10},
387 estimatedCost: checker.FixedCostEstimate(35),
388 actualCost: 27,
389 },
390 {
391 name: "list_slice",
392 expr: `[1, 2, 3].slice(1, 3) == [2, 3]`,
393 estimatedCost: checker.FixedCostEstimate(34),
394 actualCost: 34,
395 },
396 {
397 // allocs: (2 + one internal) * 10
398 // reverse cost: 3
399 // calls: 2
400 name: "list_reverse",
401 expr: `[3, 2, 1].reverse() == [1, 2, 3]`,
402 estimatedCost: checker.FixedCostEstimate(35),
403 actualCost: 35,
404 },
405 {
406 // allocs: (1 + one internal) * 10
407 // reverse cost: 5
408 // lookups: 1
409 // calls: 2
410 name: "list_var_reverse",
411 expr: `x.reverse() == [1, 2, 3]`,
412 vars: []cel.EnvOption{
413 cel.Variable("x", cel.ListType(cel.IntType)),
414 },
415 in: map[string]any{"x": []int{3, 2, 1}},
416 hints: map[string]uint64{"x": 5},
417 estimatedCost: checker.CostEstimate{Min: 23, Max: 28},
418 actualCost: 26,
419 },
420 {
421 // (2 allocs + 1 internal) * 10
422 // + size(list) * size(list) * 2
423 // + 2 calls
424 name: "list_sort",
425 expr: `[2, 3, 1].sort() == [1, 2, 3]`,
426 estimatedCost: checker.FixedCostEstimate(50),
427 actualCost: 50,
428 },
429 {
430 // (1 allocs + 1 internal) * 10
431 // + [0, size(x) * size(x)] * 2 --> [0, 50]
432 // + 2 calls
433 // + 1 ident lookup
434 name: "list_sort_var",
435 expr: `x.sort() == [1, 2, 3]`,
436 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.IntType))},
437 in: map[string]any{"x": []int{3, 2, 1}},
438 hints: map[string]uint64{"x": 5},
439 estimatedCost: checker.CostEstimate{Min: 23, Max: 73},
440 actualCost: 41,
441 },
442 {
443 name: "list_sort_var_string",
444 expr: `x.sort() == ["a", "a", "b", "b", "c", "c"]`,
445 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.StringType))},
446 in: map[string]any{"x": []string{"b", "a", "b", "a", "c", "c"}},
447 hints: map[string]uint64{"x": 10},
448 estimatedCost: checker.CostEstimate{Min: 23, Max: 233},
449 actualCost: 98,
450 },
451 {
452 name: "list_sort_var_int_empty",
453 expr: `x.sort() == []`,
454 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.IntType))},
455 in: map[string]any{"x": []int{}},
456 hints: map[string]uint64{"x": 10},
457 estimatedCost: checker.CostEstimate{Min: 22, Max: 222},
458 actualCost: 22,
459 },
460 {
461 name: "list_sortBy",
462 expr: `[{'x':4}, {'x':3}].sortBy(m, m['x']) == [{'x':3}, {'x':4}]`,
463 estimatedCost: checker.FixedCostEstimate(211),
464 actualCost: 211,
465 },
466 {
467 name: "list_sortBy_var",
468 expr: `x.sortBy(m, m['x']) == [{'x':3}, {'x':4}]`,
469 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.DynType))},
470 in: map[string]any{"x": []any{map[string]any{"x": 4}, map[string]any{"x": 3}}},
471 hints: map[string]uint64{"x": 5},
472 estimatedCost: checker.CostEstimate{Min: 106, Max: 226},
473 actualCost: 142,
474 },
475 {
476 name: "list_sortBy_var_string",
477 expr: `x.sortBy(m, m['x']) == [{'x': 'a'}, {'x': 'b'}, {'x': 'c'}]`,
478 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.MapType(cel.StringType, cel.StringType)))},
479 in: map[string]any{"x": []any{map[string]any{"x": "b"}, map[string]any{"x": "c"}, map[string]any{"x": "a"}}},
480 hints: map[string]uint64{"x": 3},
481 estimatedCost: checker.CostEstimate{Min: 136, Max: 197},
482 actualCost: 196,
483 },
484 }
485
486 for _, tst := range tests {
487 tc := tst
488 t.Run(tc.name, func(t *testing.T) {
489 env := testListsEnv(t, tc.vars...)
490 var asts []*cel.Ast
491 pAst, iss := env.Parse(tc.expr)
492 if iss.Err() != nil {
493 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
494 }
495 asts = append(asts, pAst)
496 cAst, iss := env.Check(pAst)
497 if iss.Err() != nil {
498 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
499 }
500
501 testCheckCost(t, env, cAst, tc.hints, tc.estimatedCost)
502 asts = append(asts, cAst)
503 for _, ast := range asts {
504 testEvalWithCost(t, env, ast, tc.in, tc.actualCost)
505 }
506 })
507 }
508 }
509
510 func testListsEnv(t *testing.T, opts ...cel.EnvOption) *cel.Env {
511 t.Helper()
512 baseOpts := []cel.EnvOption{
513 Lists(),
514 cel.Container("google.expr.proto2.test"),
515 cel.Types(&proto2pb.ExampleType{},
516 &proto2pb.ExternalMessageType{},
517 )}
518 env, err := cel.NewEnv(append(baseOpts, opts...)...)
519 if err != nil {
520 t.Fatalf("cel.NewEnv(Lists()) failed: %v", err)
521 }
522 return env
523 }