Debian Codegraph @

ext/bindings_test.go

raw
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/ast"
25 "github.com/google/cel-go/common/operators"
26 "github.com/google/cel-go/common/types"
27 "github.com/google/cel-go/common/types/ref"
28 )
29
30 var bindingTests = []struct {
31 name string
32 expr string
33 vars []cel.EnvOption
34 in map[string]any
35 hints map[string]uint64
36 estimatedCost checker.CostEstimate
37 actualCost uint64
38 }{
39 {
40 name: "single bind",
41 expr: `cel.bind(a, 'hell' + 'o' + '!', "%s, %s, %s".format([a, a, a])) ==
42 'hello!, hello!, hello' + '!'`,
43 estimatedCost: checker.CostEstimate{Min: 30, Max: 32},
44 actualCost: 32,
45 },
46 {
47 name: "multiple binds",
48 expr: `cel.bind(a, 'hello!',
49 cel.bind(b, 'goodbye',
50 a + ' and, ' + b)) == 'hello! and, goodbye'`,
51 estimatedCost: checker.CostEstimate{Min: 27, Max: 28},
52 actualCost: 28,
53 },
54 {
55 name: "shadow binds",
56 expr: `cel.bind(a,
57 cel.bind(a, 'world', a + '!'),
58 'hello ' + a) == 'hello ' + 'world' + '!'`,
59 estimatedCost: checker.CostEstimate{Min: 30, Max: 31},
60 actualCost: 31,
61 },
62 {
63 name: "nested bind with int list",
64 expr: `cel.bind(a, x,
65 cel.bind(b, a[0],
66 cel.bind(c, a[1], b + c))) == 10`,
67 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.IntType))},
68 in: map[string]any{
69 "x": []int64{3, 7},
70 },
71 hints: map[string]uint64{
72 "x": 3,
73 },
74 estimatedCost: checker.CostEstimate{Min: 39, Max: 39},
75 actualCost: 39,
76 },
77 {
78 name: "nested bind with string list",
79 expr: `cel.bind(a, x,
80 cel.bind(b, a[0],
81 cel.bind(c, a[1], b + c))) == "threeseven"`,
82 vars: []cel.EnvOption{cel.Variable("x", cel.ListType(cel.StringType))},
83 in: map[string]any{
84 "x": []string{"three", "seven"},
85 },
86 hints: map[string]uint64{
87 "x": 3,
88 "x.@items": 10,
89 },
90 estimatedCost: checker.CostEstimate{Min: 38, Max: 40},
91 actualCost: 39,
92 },
93 {
94 name: "shadowed binding",
95 expr: `cel.bind(x, 0, x == 0)`,
96 vars: []cel.EnvOption{cel.Variable("x", cel.StringType)},
97 in: map[string]any{
98 "cel.example.x": "1",
99 },
100 estimatedCost: checker.FixedCostEstimate(12),
101 actualCost: 12,
102 },
103 {
104 name: "container shadowed binding",
105 expr: `cel.bind(x, 0, x == 0)`,
106 vars: []cel.EnvOption{
107 cel.Container("cel.example"),
108 cel.Variable("cel.example.x", cel.StringType),
109 },
110 in: map[string]any{
111 "cel.example.x": "1",
112 },
113 estimatedCost: checker.FixedCostEstimate(12),
114 actualCost: 12,
115 },
116 {
117 name: "shadowing namespace resolution selector",
118 expr: `cel.bind(x, {'y': 0}, x.y == 0)`,
119 vars: []cel.EnvOption{
120 cel.Container("cel.example"),
121 cel.Variable("cel.example.x.y", cel.IntType),
122 },
123 in: map[string]any{
124 "cel.example.x.y": 1,
125 },
126 estimatedCost: checker.FixedCostEstimate(43),
127 actualCost: 43,
128 },
129 {
130 name: "shadowing namespace resolution selector with local",
131 expr: `cel.bind(x, {'y': 0}, .x.y == x.y)`,
132 vars: []cel.EnvOption{
133 cel.Variable("x.y", cel.IntType),
134 },
135 in: map[string]any{
136 "x.y": 0,
137 },
138 estimatedCost: checker.FixedCostEstimate(44),
139 actualCost: 44,
140 },
141 {
142 name: "namespace disambiguation",
143 expr: `cel.bind(y, 0, .y != y)`,
144 vars: []cel.EnvOption{
145 cel.Variable("y", cel.IntType),
146 },
147 in: map[string]any{
148 "y": 1,
149 },
150 estimatedCost: checker.FixedCostEstimate(13),
151 actualCost: 13,
152 },
153 {
154 name: "nesting shadowing",
155 expr: `cel.bind(y, 0, cel.bind(y, 1, y != 0))`,
156 estimatedCost: checker.FixedCostEstimate(22),
157 actualCost: 22,
158 },
159 }
160
161 func TestBindings(t *testing.T) {
162 for _, tst := range bindingTests {
163 tc := tst
164 t.Run(tc.name, func(t *testing.T) {
165 var asts []*cel.Ast
166 opts := append([]cel.EnvOption{Bindings(BindingsVersion(0)), Strings()}, tc.vars...)
167 env, err := cel.NewEnv(opts...)
168 if err != nil {
169 t.Fatalf("cel.NewEnv(Bindings(), Strings()) failed: %v", err)
170 }
171 pAst, iss := env.Parse(tc.expr)
172 if iss.Err() != nil {
173 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
174 }
175 asts = append(asts, pAst)
176 cAst, iss := env.Check(pAst)
177 if iss.Err() != nil {
178 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
179 }
180 testCheckCost(t, env, cAst, tc.hints, tc.estimatedCost)
181 asts = append(asts, cAst)
182 for _, ast := range asts {
183 testEvalWithCost(t, env, ast, tc.in, tc.actualCost)
184 }
185 })
186 }
187 }
188
189 func TestBindingsNonMatch(t *testing.T) {
190 env, err := cel.NewEnv(Bindings(), Strings())
191 if err != nil {
192 t.Fatalf("cel.NewEnv(Bindings(), Strings()) failed: %v", err)
193 }
194 nonMatchExpr := `ceel.bind(a, 1, a)`
195 ast, iss := env.Parse(nonMatchExpr)
196 if iss.Err() != nil {
197 t.Fatalf("env.Parse(%v) failed: %v", nonMatchExpr, iss.Err())
198 }
199 if len(ast.SourceInfo().GetMacroCalls()) != 0 {
200 t.Fatalf("env.Parse(%v) performed a macro replacement when none was expected: %v",
201 nonMatchExpr, ast.SourceInfo().GetMacroCalls())
202 }
203 }
204
205 func TestBindingsInvalidIdent(t *testing.T) {
206 env, err := cel.NewEnv(Bindings(), Strings())
207 if err != nil {
208 t.Fatalf("cel.NewEnv(Bindings(), Strings()) failed: %v", err)
209 }
210 invalidIdentExpr := `cel.bind(a.b, 1, a.b)`
211 wantErr := "ERROR: <input>:1:11: cel.bind() variable names must be simple identifiers"
212 _, iss := env.Parse(invalidIdentExpr)
213 if !strings.Contains(iss.Err().Error(), wantErr) {
214 t.Fatalf("env.Parse(%v) failed: %v", invalidIdentExpr, iss.Err())
215 }
216 }
217
218 func BenchmarkBindings(b *testing.B) {
219 env, err := cel.NewEnv(Bindings(), Strings())
220 if err != nil {
221 b.Fatalf("cel.NewEnv(Bindings(), Strings()) failed: %v", err)
222 }
223 for i, tst := range bindingTests {
224 tc := tst
225 ast, iss := env.Compile(tc.expr)
226 if iss.Err() != nil {
227 b.Fatalf("env.Compile(%q) failed: %v", tc.expr, iss.Err())
228 }
229 prg, err := env.Program(ast, cel.EvalOptions(cel.OptOptimize))
230 if err != nil {
231 b.Fatalf("env.Program(ast, Optimize) failed: %v", err)
232 }
233 // Benchmark the eval.
234 b.Run(fmt.Sprintf("[%d]", i), func(b *testing.B) {
235 b.ResetTimer()
236 b.ReportAllocs()
237 for i := 0; i < b.N; i++ {
238 prg.Eval(cel.NoVars())
239 }
240 })
241 }
242 }
243
244 func TestBlockEval(t *testing.T) {
245 fac := ast.NewExprFactory()
246 tests := []struct {
247 name string
248 expr ast.Expr
249 opts []cel.EnvOption
250 in map[string]any
251 out ref.Val
252 }{
253 {
254 name: "chained block",
255 expr: fac.NewCall(
256 1, "cel.@block",
257 fac.NewList(2, []ast.Expr{
258 fac.NewIdent(3, "x"),
259 fac.NewIdent(4, "@index0"),
260 fac.NewIdent(5, "@index1"),
261 }, []int32{}),
262 fac.NewCall(9, operators.Add,
263 fac.NewCall(6, operators.Add,
264 fac.NewIdent(7, "@index2"),
265 fac.NewIdent(8, "@index1")),
266 fac.NewIdent(10, "@index0"),
267 ),
268 ),
269 opts: []cel.EnvOption{
270 cel.Variable("x", cel.StringType),
271 },
272 in: map[string]any{"x": "hello"},
273 out: types.String("hellohellohello"),
274 },
275 {
276 name: "empty block",
277 expr: fac.NewCall(
278 1, "cel.@block",
279 fac.NewList(2, []ast.Expr{}, []int32{}),
280 fac.NewCall(3, operators.LogicalNot, fac.NewLiteral(4, types.False)),
281 ),
282 in: map[string]any{},
283 out: types.True,
284 },
285 {
286 name: "mixed block constant values",
287 expr: fac.NewCall(
288 1, "cel.@block",
289 fac.NewList(2, []ast.Expr{
290 fac.NewLiteral(3, types.String("hello")),
291 fac.NewLiteral(4, types.Int(5)),
292 }, []int32{}),
293 fac.NewCall(5, operators.Equals,
294 fac.NewCall(6, "size",
295 fac.NewIdent(7, "@index0")),
296 fac.NewIdent(8, "@index1"),
297 ),
298 ),
299 opts: []cel.EnvOption{
300 cel.ExtendedValidations(),
301 },
302 in: map[string]any{},
303 out: types.True,
304 },
305 {
306 name: "mixed block dynamic values",
307 expr: fac.NewCall(
308 1, "cel.@block",
309 fac.NewList(2, []ast.Expr{
310 fac.NewIdent(3, "x"),
311 fac.NewLiteral(4, types.Int(5)),
312 }, []int32{}),
313 fac.NewCall(5, operators.Equals,
314 fac.NewCall(6, "size",
315 fac.NewIdent(7, "@index0")),
316 fac.NewIdent(8, "@index1"),
317 ),
318 ),
319 opts: []cel.EnvOption{
320 cel.Variable("x", cel.StringType),
321 cel.ExtendedValidations(),
322 },
323 in: map[string]any{"x": "goodbye"},
324 out: types.False,
325 },
326 {
327 name: "mixed block constant values dyn var",
328 expr: fac.NewCall(
329 1, "cel.@block",
330 fac.NewList(2, []ast.Expr{
331 fac.NewLiteral(3, types.String("hello")),
332 }, []int32{}),
333 fac.NewCall(4, operators.Equals,
334 fac.NewCall(5, "size",
335 fac.NewIdent(6, "@index0")),
336 fac.NewIdent(7, "y"),
337 ),
338 ),
339 opts: []cel.EnvOption{
340 cel.Variable("y", cel.IntType),
341 cel.ExtendedValidations(),
342 },
343 in: map[string]any{
344 "y": 5,
345 },
346 out: types.True,
347 },
348 }
349 for _, tst := range tests {
350 tc := tst
351 t.Run(tc.name, func(t *testing.T) {
352 blockAST := ast.NewAST(tc.expr, nil)
353 opts := append([]cel.EnvOption{Bindings()}, tc.opts...)
354 env, err := cel.NewEnv(opts...)
355 if err != nil {
356 t.Fatalf("cel.NewEnv(Bindings()) failed: %v", err)
357 }
358 prg, err := env.PlanProgram(blockAST, cel.EvalOptions(cel.OptOptimize))
359 if err != nil {
360 t.Fatalf("PlanProgram() failed: %v", err)
361 }
362 out, _, err := prg.Eval(tc.in)
363 if err != nil {
364 t.Fatalf("prg.Eval() failed: %v", err)
365 }
366 if out.Equal(tc.out) != types.True {
367 t.Errorf("got %v, wanted %v", out, tc.out)
368 }
369 })
370 }
371 }
372
373 func TestBlockEval_BadPlan(t *testing.T) {
374 fac := ast.NewExprFactory()
375 blockExpr := fac.NewCall(
376 1, "cel.@block",
377 fac.NewList(2, []ast.Expr{
378 fac.NewIdent(3, "x"),
379 fac.NewIdent(4, "@index0"),
380 }, []int32{}),
381 fac.NewCall(6, operators.Add,
382 fac.NewIdent(7, "@index1"),
383 fac.NewIdent(8, "@index0")),
384 fac.NewIdent(9, "x"),
385 )
386 blockAST := ast.NewAST(blockExpr, nil)
387 env, err := cel.NewEnv(
388 Bindings(BindingsVersion(1)),
389 cel.Variable("x", cel.StringType),
390 )
391 if err != nil {
392 t.Fatalf("cel.NewEnv(Bindings()) failed: %v", err)
393 }
394 _, err = env.PlanProgram(blockAST)
395 if err == nil {
396 t.Fatal("PlanProgram() succeeded, expected error")
397 }
398 }
399
400 func TestBlockEval_BadBlock(t *testing.T) {
401 fac := ast.NewExprFactory()
402 blockExpr := fac.NewCall(
403 1, "cel.@block",
404 fac.NewCall(2, operators.Add,
405 fac.NewIdent(3, "@index1"),
406 fac.NewIdent(4, "@index0")),
407 fac.NewIdent(5, "x"),
408 )
409 blockAST := ast.NewAST(blockExpr, nil)
410 env, err := cel.NewEnv(
411 Bindings(BindingsVersion(1)),
412 cel.Variable("x", cel.StringType),
413 )
414 if err != nil {
415 t.Fatalf("cel.NewEnv(Bindings()) failed: %v", err)
416 }
417 _, err = env.PlanProgram(blockAST)
418 if err == nil {
419 t.Fatal("PlanProgram() succeeded, expected error")
420 }
421 }
422
423 func TestBlockEval_RuntimeErrors(t *testing.T) {
424 fac := ast.NewExprFactory()
425 tests := []struct {
426 name string
427 expr ast.Expr
428 }{
429 {
430 name: "bad index",
431 expr: fac.NewCall(
432 1, "cel.@block",
433 fac.NewList(2, []ast.Expr{
434 fac.NewIdent(3, "x"),
435 fac.NewIdent(4, "@indexNext"),
436 }, []int32{}),
437 fac.NewCall(6, operators.Add,
438 fac.NewIdent(7, "@indexNext"),
439 fac.NewIdent(8, "@index0")),
440 ),
441 },
442 {
443 name: "infinite recursion",
444 expr: fac.NewCall(
445 1, "cel.@block",
446 fac.NewList(2, []ast.Expr{
447 fac.NewIdent(3, "@index0"),
448 fac.NewIdent(4, "@index0"),
449 }, []int32{}),
450 fac.NewIdent(10, "@index0"),
451 ),
452 },
453 {
454 name: "negative index",
455 expr: fac.NewCall(
456 1, "cel.@block",
457 fac.NewList(2, []ast.Expr{
458 fac.NewIdent(3, "@index-1"),
459 fac.NewIdent(4, "@index0"),
460 }, []int32{}),
461 fac.NewIdent(10, "@index0"),
462 ),
463 },
464 {
465 name: "out of range index",
466 expr: fac.NewCall(
467 1, "cel.@block",
468 fac.NewList(2, []ast.Expr{
469 fac.NewIdent(3, "@index100"),
470 fac.NewIdent(4, "@index0"),
471 }, []int32{}),
472 fac.NewIdent(10, "@index0"),
473 ),
474 },
475 }
476 for _, tst := range tests {
477 tc := tst
478 t.Run(tc.name, func(t *testing.T) {
479 blockAST := ast.NewAST(tc.expr, nil)
480 env, err := cel.NewEnv(
481 Bindings(BindingsVersion(1)),
482 cel.Variable("x", cel.StringType),
483 )
484 if err != nil {
485 t.Fatalf("cel.NewEnv(Bindings()) failed: %v", err)
486 }
487 prg, err := env.PlanProgram(blockAST)
488 if err != nil {
489 t.Fatalf("PlanProgram() failed: %v", err)
490 }
491 _, _, err = prg.Eval(map[string]any{"x": "hello"})
492 if !strings.Contains(err.Error(), "no such attribute") {
493 t.Fatalf("prg.Eval() got %v, expected no such attribute error", err)
494 }
495 })
496 }
497 }