Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/ext/native_test.go

raw symbols SCIP
1 // Copyright 2022 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 "errors"
19 "fmt"
20 "reflect"
21 "sort"
22 "strings"
23 "testing"
24 "time"
25
26 "google.golang.org/protobuf/encoding/protojson"
27 "google.golang.org/protobuf/proto"
28
29 "github.com/google/cel-go/cel"
30 "github.com/google/cel-go/common/types"
31 "github.com/google/cel-go/common/types/pb"
32 "github.com/google/cel-go/common/types/ref"
33 "github.com/google/cel-go/common/types/traits"
34 "github.com/google/cel-go/test"
35
36 structpb "google.golang.org/protobuf/types/known/structpb"
37
38 proto3pb "github.com/google/cel-go/test/proto3pb"
39 )
40
41 func TestNativeTypes(t *testing.T) {
42 var nativeTests = []struct {
43 expr string
44 out any
45 in any
46 envOpts []any
47 }{
48 {
49 expr: `ext.TestAllTypes{
50 NestedVal: ext.TestNestedType{NestedMapVal: {1: false}},
51 BoolVal: true,
52 BytesVal: b'hello',
53 DurationVal: duration('5s'),
54 DoubleVal: 1.5,
55 FloatVal: 2.5,
56 Int32Val: 10,
57 Int64Val: 20,
58 StringVal: 'hello world',
59 TimestampVal: timestamp('2011-08-06T01:23:45Z'),
60 Uint32Val: 100u,
61 Uint64Val: 200u,
62 ListVal: [
63 ext.TestNestedType{
64 NestedListVal:['goodbye', 'cruel', 'world'],
65 NestedMapVal: {42: true},
66 custom_name: 'name',
67 },
68 ],
69 ArrayVal: [
70 ext.TestNestedType{
71 NestedListVal:['goodbye', 'cruel', 'world'],
72 NestedMapVal: {42: true},
73 custom_name: 'name',
74 },
75 ],
76 MapVal: {'map-key': ext.TestAllTypes{BoolVal: true}},
77 CustomSliceVal: [ext.TestNestedSliceType{Value: 'none'}],
78 CustomMapVal: {'even': ext.TestMapVal{Value: 'more'}},
79 custom_name: 'name',
80 }`,
81 out: &TestAllTypes{
82 NestedVal: &TestNestedType{NestedMapVal: map[int64]bool{1: false}},
83 BoolVal: true,
84 BytesVal: []byte("hello"),
85 DurationVal: time.Second * 5,
86 DoubleVal: 1.5,
87 FloatVal: 2.5,
88 Int32Val: 10,
89 Int64Val: 20,
90 StringVal: "hello world",
91 TimestampVal: mustParseTime(t, "2011-08-06T01:23:45Z"),
92 Uint32Val: uint32(100),
93 Uint64Val: uint64(200),
94 ListVal: []*TestNestedType{
95 {
96 NestedListVal: []string{"goodbye", "cruel", "world"},
97 NestedMapVal: map[int64]bool{42: true},
98 NestedCustomName: "name",
99 },
100 },
101 ArrayVal: [1]*TestNestedType{{
102 NestedListVal: []string{"goodbye", "cruel", "world"},
103 NestedMapVal: map[int64]bool{42: true},
104 NestedCustomName: "name",
105 }},
106 MapVal: map[string]TestAllTypes{"map-key": {BoolVal: true}},
107 CustomSliceVal: []TestNestedSliceType{{Value: "none"}},
108 CustomMapVal: map[string]TestMapVal{"even": {Value: "more"}},
109 CustomName: "name",
110 },
111 envOpts: []any{ParseStructTags(true)},
112 },
113
114 {
115 expr: `ext.TestAllTypes{
116 nestedVal: ext.TestNestedType{NestedMapVal: {1: false}},
117 boolVal: true,
118 BytesVal: b'hello',
119 DurationVal: duration('5s'),
120 DoubleVal: 1.5,
121 FloatVal: 2.5,
122 Int32Val: 10,
123 Int64Val: 20,
124 StringVal: 'hello world',
125 TimestampVal: timestamp('2011-08-06T01:23:45Z'),
126 Uint32Val: 100u,
127 Uint64Val: 200u,
128 ListVal: [
129 ext.TestNestedType{
130 NestedListVal:['goodbye', 'cruel', 'world'],
131 NestedMapVal: {42: true},
132 custom_name: 'name',
133 },
134 ],
135 ArrayVal: [
136 ext.TestNestedType{
137 NestedListVal:['goodbye', 'cruel', 'world'],
138 NestedMapVal: {42: true},
139 custom_name: 'name',
140 },
141 ],
142 MapVal: {'map-key': ext.TestAllTypes{boolVal: true}},
143 CustomSliceVal: [ext.TestNestedSliceType{Value: 'none'}],
144 CustomMapVal: {'even': ext.TestMapVal{Value: 'more'}},
145 CustomName: 'name',
146 }`,
147 out: &TestAllTypes{
148 NestedVal: &TestNestedType{NestedMapVal: map[int64]bool{1: false}},
149 BoolVal: true,
150 BytesVal: []byte("hello"),
151 DurationVal: time.Second * 5,
152 DoubleVal: 1.5,
153 FloatVal: 2.5,
154 Int32Val: 10,
155 Int64Val: 20,
156 StringVal: "hello world",
157 TimestampVal: mustParseTime(t, "2011-08-06T01:23:45Z"),
158 Uint32Val: uint32(100),
159 Uint64Val: uint64(200),
160 ListVal: []*TestNestedType{
161 {
162 NestedListVal: []string{"goodbye", "cruel", "world"},
163 NestedMapVal: map[int64]bool{42: true},
164 NestedCustomName: "name",
165 },
166 },
167 ArrayVal: [1]*TestNestedType{{
168 NestedListVal: []string{"goodbye", "cruel", "world"},
169 NestedMapVal: map[int64]bool{42: true},
170 NestedCustomName: "name",
171 }},
172 MapVal: map[string]TestAllTypes{"map-key": {BoolVal: true}},
173 CustomSliceVal: []TestNestedSliceType{{Value: "none"}},
174 CustomMapVal: map[string]TestMapVal{"even": {Value: "more"}},
175 CustomName: "name",
176 },
177 envOpts: []any{ParseStructTag("json")},
178 },
179 {
180 expr: `ext.TestAllTypes{
181 NestedVal: ext.TestNestedType{NestedMapVal: {1: false}},
182 BoolVal: true,
183 BytesVal: b'hello',
184 DurationVal: duration('5s'),
185 DoubleVal: 1.5,
186 FloatVal: 2.5,
187 Int32Val: 10,
188 Int64Val: 20,
189 StringVal: 'hello world',
190 TimestampVal: timestamp('2011-08-06T01:23:45Z'),
191 Uint32Val: 100u,
192 Uint64Val: 200u,
193 ListVal: [
194 ext.TestNestedType{
195 NestedListVal:['goodbye', 'cruel', 'world'],
196 NestedMapVal: {42: true},
197 NestedCustomName: 'name',
198 },
199 ],
200 ArrayVal: [
201 ext.TestNestedType{
202 NestedListVal:['goodbye', 'cruel', 'world'],
203 NestedMapVal: {42: true},
204 NestedCustomName: 'name',
205 },
206 ],
207 MapVal: {'map-key': ext.TestAllTypes{BoolVal: true}},
208 CustomSliceVal: [ext.TestNestedSliceType{Value: 'none'}],
209 CustomMapVal: {'even': ext.TestMapVal{Value: 'more'}},
210 CustomName: 'name',
211 }`,
212 out: &TestAllTypes{
213 NestedVal: &TestNestedType{NestedMapVal: map[int64]bool{1: false}},
214 BoolVal: true,
215 BytesVal: []byte("hello"),
216 DurationVal: time.Second * 5,
217 DoubleVal: 1.5,
218 FloatVal: 2.5,
219 Int32Val: 10,
220 Int64Val: 20,
221 StringVal: "hello world",
222 TimestampVal: mustParseTime(t, "2011-08-06T01:23:45Z"),
223 Uint32Val: uint32(100),
224 Uint64Val: uint64(200),
225 ListVal: []*TestNestedType{
226 {
227 NestedListVal: []string{"goodbye", "cruel", "world"},
228 NestedMapVal: map[int64]bool{42: true},
229 NestedCustomName: "name",
230 },
231 },
232 ArrayVal: [1]*TestNestedType{{
233 NestedListVal: []string{"goodbye", "cruel", "world"},
234 NestedMapVal: map[int64]bool{42: true},
235 NestedCustomName: "name",
236 }},
237 MapVal: map[string]TestAllTypes{"map-key": {BoolVal: true}},
238 CustomSliceVal: []TestNestedSliceType{{Value: "none"}},
239 CustomMapVal: map[string]TestMapVal{"even": {Value: "more"}},
240 CustomName: "name",
241 },
242 },
243 {
244 expr: `ext.TestAllTypes{
245 PbVal: test.TestAllTypes{single_int32: 123}
246 }.PbVal`,
247 out: &proto3pb.TestAllTypes{SingleInt32: 123},
248 },
249 {
250 expr: `ext.TestAllTypes{PbVal: test.TestAllTypes{}} ==
251 ext.TestAllTypes{PbVal: test.TestAllTypes{single_bool: false}}`,
252 },
253 {expr: `ext.TestNestedType{} == TestNestedType{}`},
254 {expr: `ext.TestAllTypes{}.BoolVal != true`},
255 {expr: `!has(ext.TestAllTypes{}.BoolVal) && !has(ext.TestAllTypes{}.NestedVal)`},
256 {expr: `type(ext.TestAllTypes) == type`},
257 {expr: `type(ext.TestAllTypes{}) == ext.TestAllTypes`},
258 {expr: `type(ext.TestAllTypes{}) == ext.TestAllTypes`},
259 {expr: `ext.TestAllTypes != test.TestAllTypes`},
260 {expr: `ext.TestAllTypes{BoolVal: true} != dyn(test.TestAllTypes{single_bool: true})`},
261 {expr: `ext.TestAllTypes{}.NestedVal == ext.TestNestedType{}`},
262 {expr: `ext.TestNestedType{} == ext.TestAllTypes{}.NestedStructVal`},
263 {expr: `ext.TestAllTypes{}.NestedStructVal == ext.TestNestedType{}`},
264 {expr: `ext.TestAllTypes{}.ListVal.size() == 0`},
265 {expr: `ext.TestAllTypes{}.MapVal.size() == 0`},
266 {expr: `ext.TestAllTypes{}.TimestampVal == timestamp(0)`},
267 {expr: `test.TestAllTypes{}.single_timestamp == timestamp(0)`},
268 {expr: `[TestAllTypes{BoolVal: true}, TestAllTypes{BoolVal: false}].exists(t, t.BoolVal == true)`},
269 {expr: `[TestAllTypes{CustomName: 'Alice'}, TestAllTypes{CustomName: 'Bob'}].exists(t, t.CustomName == 'Alice')`},
270 {expr: `[TestAllTypes{custom_name: 'Alice'}, TestAllTypes{custom_name: 'Bob'}].exists(t, t.custom_name == 'Alice')`, envOpts: []any{ParseStructTags(true)}},
271 {expr: `TestAllTypes{BytesArrayVal: b'1234'}.BytesArrayVal != b'123'`},
272 {expr: `TestAllTypes{BytesArrayVal: b'1234'}.BytesArrayVal == b'1234'`},
273 {
274 expr: `tests.all(t, t.Int32Val > 17)`,
275 in: map[string]any{
276 "tests": []*TestAllTypes{{Int32Val: 18}, {Int32Val: 19}, {Int32Val: 20}},
277 },
278 },
279 }
280 for i, tst := range nativeTests {
281 tc := tst
282 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
283 env := testNativeEnv(t, tc.envOpts...)
284 var asts []*cel.Ast
285 pAst, iss := env.Parse(tc.expr)
286 if iss.Err() != nil {
287 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
288 }
289 asts = append(asts, pAst)
290 cAst, iss := env.Check(pAst)
291 if iss.Err() != nil {
292 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
293 }
294 asts = append(asts, cAst)
295 for _, ast := range asts {
296 prg, err := env.Program(ast)
297 if err != nil {
298 t.Fatal(err)
299 }
300 in := tc.in
301 if in == nil {
302 in = cel.NoVars()
303 }
304 out, _, err := prg.Eval(in)
305 if err != nil {
306 t.Fatal(err)
307 }
308 want := tc.out
309 if want == nil {
310 want = true
311 }
312 wantPB, isPB := want.(proto.Message)
313 if isPB && !pb.Equal(wantPB, out.Value().(proto.Message)) {
314 t.Errorf("got %v, wanted %v for expr: %s", out.Value(), want, tc.expr)
315 }
316 if !isPB && !reflect.DeepEqual(out.Value(), want) {
317 t.Errorf("got %v, wanted %v for expr: %s", out.Value(), want, tc.expr)
318 }
319 }
320 })
321 }
322 }
323
324 func TestNativeFindStructFieldNames(t *testing.T) {
325 env := testNativeEnv(t, ParseStructTags(true))
326 provider := env.CELTypeProvider()
327 tests := []struct {
328 typeName string
329 fields []string
330 }{
331 {
332 typeName: "ext.TestNestedType",
333 fields: []string{"NestedListVal", "NestedMapVal", "custom_name"},
334 },
335 {
336 typeName: "google.expr.proto3.test.TestAllTypes.NestedMessage",
337 fields: []string{"bb"},
338 },
339 {
340 typeName: "invalid.TypeName",
341 fields: []string{},
342 },
343 }
344
345 for _, tst := range tests {
346 tc := tst
347 t.Run(fmt.Sprintf("%s", tc.typeName), func(t *testing.T) {
348 fields, _ := provider.FindStructFieldNames(tc.typeName)
349 sort.Strings(fields)
350 sort.Strings(tc.fields)
351 if !reflect.DeepEqual(fields, tc.fields) {
352 t.Errorf("got %v, wanted %v", fields, tc.fields)
353 }
354 })
355 }
356 }
357
358 func TestNativeTypesStaticErrors(t *testing.T) {
359 var nativeTests = []struct {
360 expr string
361 err string
362 }{
363 {
364 expr: `TestAllTypos{}`,
365 err: `ERROR: <input>:1:13: undeclared reference to 'TestAllTypos' (in container 'ext')
366 | TestAllTypos{}
367 | ............^`,
368 },
369 {
370 expr: `ext.TestAllTypes{bool_val: false}`,
371 err: `ERROR: <input>:1:26: undefined field 'bool_val'
372 | ext.TestAllTypes{bool_val: false}
373 | .........................^`,
374 },
375 {
376 expr: `ext.TestAllTypes{UnsupportedVal: null}`,
377 err: `ERROR: <input>:1:32: undefined field 'UnsupportedVal'
378 | ext.TestAllTypes{UnsupportedVal: null}
379 | ...............................^`,
380 },
381 {
382 expr: `ext.TestAllTypes{UnsupportedListVal: null}`,
383 err: `ERROR: <input>:1:36: undefined field 'UnsupportedListVal'
384 | ext.TestAllTypes{UnsupportedListVal: null}
385 | ...................................^`,
386 },
387 {
388 expr: `ext.TestAllTypes{UnsupportedMapVal: null}`,
389 err: `ERROR: <input>:1:35: undefined field 'UnsupportedMapVal'
390 | ext.TestAllTypes{UnsupportedMapVal: null}
391 | ..................................^`,
392 },
393 }
394 env := testNativeEnv(t)
395 for i, tst := range nativeTests {
396 tc := tst
397 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
398 _, iss := env.Compile(tc.expr)
399 if iss.Err() == nil {
400 t.Fatalf("env.Compile(%v) succeeded, wanted error", tc.expr)
401 }
402 if !test.Compare(iss.Err().Error(), tc.err) {
403 t.Errorf("env.Compile(%v) got %v, wanted error %s", tc.expr, iss.Err(), tc.err)
404 }
405 })
406 }
407 }
408
409 func TestNativeTypesJsonSerialization(t *testing.T) {
410 tests := []struct {
411 expr string
412 out string
413 additionalEnvOptions []any
414 }{
415 {
416 expr: `[b'string']`,
417 out: `["c3RyaW5n"]`,
418 },
419 {
420 expr: `TestAllTypes{
421 BoolVal: true,
422 DurationVal: duration('5s'),
423 DoubleVal: 1.5,
424 FloatVal: 2.0,
425 Int32Val: 23,
426 Int64Val: 64,
427 MapVal: {
428 'map-key': ext.TestAllTypes{
429 BoolVal: true
430 }
431 },
432 NestedVal: TestNestedType{
433 NestedListVal: ["first", "second"],
434 },
435 StringVal: "string",
436 CustomName: "name",
437 }`,
438 out: `{
439 "BoolVal": true,
440 "CustomName": "name",
441 "DoubleVal": 1.5,
442 "DurationVal": "5s",
443 "FloatVal": 2,
444 "Int32Val": 23,
445 "Int64Val": 64,
446 "MapVal": {
447 "map-key": {
448 "BoolVal": true
449 }
450 },
451 "NestedVal": {
452 "NestedListVal": [
453 "first",
454 "second"
455 ]
456 },
457 "StringVal": "string"
458 }`,
459 },
460 {
461 expr: `TestAllTypes{
462 BoolVal: true,
463 DurationVal: duration('5s'),
464 DoubleVal: 1.5,
465 FloatVal: 2.0,
466 Int32Val: 23,
467 Int64Val: 64,
468 MapVal: {
469 'map-key': ext.TestAllTypes{
470 BoolVal: true
471 }
472 },
473 NestedVal: TestNestedType{
474 NestedListVal: ["first", "second"],
475 },
476 StringVal: "string",
477 custom_name: "name",
478 }`,
479 out: `{
480 "BoolVal": true,
481 "DoubleVal": 1.5,
482 "DurationVal": "5s",
483 "FloatVal": 2,
484 "Int32Val": 23,
485 "Int64Val": 64,
486 "MapVal": {
487 "map-key": {
488 "BoolVal": true
489 }
490 },
491 "NestedVal": {
492 "NestedListVal": [
493 "first",
494 "second"
495 ]
496 },
497 "StringVal": "string",
498 "custom_name": "name"
499 }`,
500 additionalEnvOptions: []any{ParseStructTags(true)},
501 },
502 }
503 for i, tst := range tests {
504 tc := tst
505 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
506 env := testNativeEnv(t, tst.additionalEnvOptions...)
507 ast, iss := env.Compile(tc.expr)
508 if iss.Err() != nil {
509 t.Fatalf("env.Compile(%v) failed: %v", tc.expr, iss.Err())
510 }
511 prg, err := env.Program(ast)
512 if err != nil {
513 t.Fatalf("env.Program() failed: %v", err)
514 }
515 out, _, err := prg.Eval(cel.NoVars())
516 if err != nil {
517 t.Fatalf("prg.Eval() failed: %v", err)
518 }
519 conv, err := out.ConvertToNative(reflect.TypeOf(&structpb.Value{}))
520 if err != nil {
521 t.Fatalf("out.ConvertToNative(Value) failed: %v", err)
522 }
523 json := protojson.Format(conv.(proto.Message))
524 if !test.Compare(json, tc.out) {
525 t.Errorf("expr %v converted to %v, wanted %v", tc.expr, json, tc.out)
526 }
527 })
528 }
529 }
530
531 func TestNativeTypesRuntimeErrors(t *testing.T) {
532 var nativeTests = []struct {
533 expr string
534 err string
535 }{
536 {
537 expr: `TestAllTypos{}`,
538 err: `unknown type: TestAllTypos`,
539 },
540 {
541 expr: `ext.TestAllTypes{bool_val: false}`,
542 err: `no such field: bool_val`,
543 },
544 {
545 expr: `ext.TestAllTypes{UnsupportedVal: null}`,
546 err: `no such field: UnsupportedVal`,
547 },
548 {
549 expr: `ext.TestAllTypes{UnsupportedListVal: null}`,
550 err: `no such field: UnsupportedListVal`,
551 },
552 {
553 expr: `ext.TestAllTypes{UnsupportedMapVal: null}`,
554 err: `no such field: UnsupportedMapVal`,
555 },
556 {
557 expr: `ext.TestAllTypes{privateVal: null}`,
558 err: `no such field: privateVal`,
559 },
560 {
561 expr: `ext.TestAllTypes{}.UnsupportedMapVal`,
562 err: `no such field: UnsupportedMapVal`,
563 },
564 {
565 expr: `ext.TestAllTypes{}.privateVal`,
566 err: `no such field: privateVal`,
567 },
568 {
569 expr: `ext.TestAllTypes{BoolVal: 'false'}`,
570 err: `unsupported native conversion from string to 'bool'`,
571 },
572 {
573 expr: `has(ext.TestAllTypes{}.BadFieldName)`,
574 err: `no such field: BadFieldName`,
575 },
576 {
577 expr: `ext.TestAllTypes{}[42]`,
578 err: `no such overload`,
579 },
580 {
581 expr: `ext.TestAllTypes{Int32Val: 9223372036854775807}`,
582 err: `integer overflow`,
583 },
584 {
585 expr: `ext.TestAllTypes{Uint32Val: 9223372036854775807u}`,
586 err: `unsigned integer overflow`,
587 },
588 }
589 env := testNativeEnv(t)
590 for i, tst := range nativeTests {
591 tc := tst
592 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
593 ast, iss := env.Parse(tc.expr)
594 if iss.Err() != nil {
595 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
596 }
597 prg, err := env.Program(ast)
598 if err != nil {
599 if !strings.Contains(err.Error(), tc.err) {
600 t.Fatal(err)
601 }
602 return
603 }
604 out, _, err := prg.Eval(cel.NoVars())
605 if err == nil || !strings.Contains(err.Error(), tc.err) {
606 var got any = err
607 if err == nil {
608 got = out
609 }
610 t.Fatalf("prg.Eval() got %v, wanted error %v", got, tc.err)
611 }
612 })
613 }
614 }
615
616 func TestNativeTypesErrors(t *testing.T) {
617 envTests := []struct {
618 nativeType any
619 err string
620 }{
621 {
622 nativeType: reflect.TypeOf(1),
623 err: "unsupported reflect.Type",
624 },
625 {
626 nativeType: reflect.ValueOf(1),
627 err: "unsupported reflect.Type",
628 },
629 {
630 nativeType: 1,
631 err: "must be reflect.Type or reflect.Value",
632 },
633 }
634 for i, tst := range envTests {
635 tc := tst
636 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
637 _, err := cel.NewEnv(NativeTypes(tc.nativeType))
638 if err == nil || !strings.Contains(err.Error(), tc.err) {
639 t.Errorf("cel.NewEnv(NativeTypes(%v)) got error %v, wanted %v", tc.nativeType, err, tc.err)
640 }
641 })
642 }
643 }
644
645 func TestNativeTypesConvertToNative(t *testing.T) {
646 env := testNativeEnv(t, NativeTypes(reflect.TypeOf(TestNestedType{})))
647 adapter := env.CELTypeAdapter()
648 conversions := []struct {
649 in any
650 inType *cel.Type
651 out any
652 err string
653 }{
654 {
655 in: &TestAllTypes{BoolVal: true},
656 inType: cel.ObjectType("ext.TestAllTypes"),
657 out: &TestAllTypes{BoolVal: true},
658 },
659 {
660 in: TestAllTypes{BoolVal: true},
661 inType: cel.ObjectType("ext.TestAllTypes"),
662 out: &TestAllTypes{BoolVal: true},
663 },
664 {
665 in: &TestAllTypes{BoolVal: true},
666 inType: cel.ObjectType("ext.TestAllTypes"),
667 out: TestAllTypes{BoolVal: true},
668 },
669 {
670 in: nil,
671 inType: cel.NullType,
672 out: types.NullValue,
673 },
674 {
675 in: &TestAllTypes{BoolVal: true},
676 inType: cel.ObjectType("ext.TestAllTypes"),
677 out: &proto3pb.TestAllTypes{},
678 err: "type conversion error",
679 },
680 {
681 in: [3]int32{1, 2, 3},
682 inType: cel.ListType(cel.IntType),
683 out: []int32{1, 2, 3},
684 },
685 {
686 in: &[3]byte{1, 2, 3},
687 inType: cel.BytesType,
688 out: []byte{1, 2, 3},
689 },
690 {
691 in: [3]byte{1, 2, 3},
692 inType: cel.BytesType,
693 out: []byte{1, 2, 3},
694 },
695 }
696 for _, c := range conversions {
697 inVal := adapter.NativeToValue(c.in)
698 if types.IsError(inVal) {
699 t.Fatalf("adapter.NativeToValue(%v) failed: %v", c.in, inVal)
700 }
701 if inVal.Type().TypeName() != c.inType.TypeName() {
702 t.Fatalf("adapter.NativeToValue() got type %v, wanted type %v", inVal.Type(), c.inType)
703 }
704 out, err := inVal.ConvertToNative(reflect.TypeOf(c.out))
705 if err != nil {
706 if c.err != "" {
707 if !strings.Contains(err.Error(), c.err) {
708 t.Fatalf("%v.ConvertToNative(%T) got %v, wanted error %v", c.in, c.out, err, c.err)
709 }
710 return
711 }
712 t.Fatalf("%v.ConvertToNative(%T) failed: %v", c.in, c.out, err)
713 }
714 if !reflect.DeepEqual(out, c.out) {
715 t.Errorf("%v.ConvertToNative(%T) got %v, wanted %v", c.in, c.out, out, c.out)
716 }
717 }
718 }
719
720 func TestConvertToTypeErrors(t *testing.T) {
721 env := testNativeEnv(t, NativeTypes(reflect.TypeOf(TestNestedType{})))
722 adapter := env.CELTypeAdapter()
723 conversions := []struct {
724 in any
725 out any
726 err string
727 }{
728 {
729 in: &TestAllTypes{BoolVal: true},
730 out: &TestAllTypes{BoolVal: true},
731 },
732 {
733 in: TestAllTypes{BoolVal: true},
734 out: &TestAllTypes{BoolVal: true},
735 },
736 {
737 in: &TestAllTypes{BoolVal: true},
738 out: TestAllTypes{BoolVal: true},
739 },
740 {
741 in: &TestAllTypes{BoolVal: true},
742 out: &proto3pb.TestAllTypes{},
743 err: "type conversion error",
744 },
745 }
746 for _, c := range conversions {
747 inVal := adapter.NativeToValue(c.in)
748 outVal := adapter.NativeToValue(c.out)
749 if types.IsError(inVal) {
750 t.Fatalf("adapter.NativeToValue(%v) failed: %v", c.in, inVal)
751 }
752 if types.IsError(outVal) {
753 t.Fatalf("adapter.NativeToValue(%v) failed: %v", c.out, outVal)
754 }
755 conv := inVal.ConvertToType(outVal.Type())
756 if c.err != "" {
757 if !types.IsError(conv) {
758 t.Fatalf("%v.ConvertToType(%v) got %v, wanted error %v", c.in, outVal.Type(), conv, c.err)
759 }
760 convErr := conv.(*types.Err)
761 if !strings.Contains(convErr.Error(), c.err) {
762 t.Fatalf("%v.ConvertToType(%v) got %v, wanted error %v", c.in, outVal.Type(), conv, c.err)
763 }
764 return
765 }
766 if conv != inVal {
767 t.Errorf("%v.ConvertToType(%v) got %v, wanted %v", c.in, outVal.Type(), conv, c.err)
768 }
769 conv = inVal.ConvertToType(types.TypeType)
770 if conv.Type() != types.TypeType || conv.(ref.Type) != inVal.Type() {
771 t.Errorf("%v.ConvertToType(Type) got %v, wanted %v", inVal, conv, inVal.Type())
772 }
773 }
774 }
775
776 func TestNativeTypesWithOptional(t *testing.T) {
777 var nativeTests = []struct {
778 expr string
779 }{
780 {expr: `!optional.ofNonZeroValue(ext.TestAllTypes{}).hasValue()`},
781 {expr: `!ext.TestAllTypes{}.?BoolVal.orValue(false)`},
782 {expr: `!ext.TestAllTypes{}.?BoolVal.hasValue()`},
783 {expr: `!ext.TestAllTypes{BoolVal: false}.?BoolVal.hasValue()`},
784 {expr: `ext.TestAllTypes{BoolVal: true}.?BoolVal.hasValue()`},
785 {expr: `ext.TestAllTypes{}.NestedVal.?NestedMapVal.orValue({}).size() == 0`},
786 }
787 env := testNativeEnv(t, cel.OptionalTypes())
788 for i, tst := range nativeTests {
789 tc := tst
790 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
791 var asts []*cel.Ast
792 pAst, iss := env.Parse(tc.expr)
793 if iss.Err() != nil {
794 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
795 }
796 asts = append(asts, pAst)
797 cAst, iss := env.Check(pAst)
798 if iss.Err() != nil {
799 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
800 }
801 asts = append(asts, cAst)
802 for _, ast := range asts {
803 prg, err := env.Program(ast)
804 if err != nil {
805 t.Fatal(err)
806 }
807 out, _, err := prg.Eval(cel.NoVars())
808 if err != nil {
809 t.Fatal(err)
810 }
811 if !reflect.DeepEqual(out.Value(), true) {
812 t.Errorf("got %v, wanted true for expr: %s", out.Value(), tc.expr)
813 }
814 }
815 })
816 }
817 }
818
819 func TestNativeTypeConvertToType(t *testing.T) {
820 var nativeTests = []struct {
821 tag string
822 }{
823 {tag: "cel"},
824 {tag: "json"},
825 }
826
827 for i, tst := range nativeTests {
828 tc := tst
829 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
830 handler := fieldNameByTag(tc.tag)
831 nt, err := newNativeType(handler, reflect.TypeOf(&TestAllTypes{}))
832 if err != nil {
833 t.Fatalf("newNativeType() failed: %v", err)
834 }
835 if nt.ConvertToType(types.TypeType) != types.TypeType {
836 t.Error("ConvertToType(Type) failed")
837 }
838 if !types.IsError(nt.ConvertToType(types.StringType)) {
839 t.Errorf("ConvertToType(String) got %v, wanted error", nt.ConvertToType(types.StringType))
840 }
841 })
842 }
843 }
844
845 func TestNativeTypeConvertToNative(t *testing.T) {
846 nt, err := newNativeType(fieldNameByTag("cel"), reflect.TypeOf(&TestAllTypes{}))
847 if err != nil {
848 t.Fatalf("newNativeType() failed: %v", err)
849 }
850 out, err := nt.ConvertToNative(reflect.TypeOf(1))
851 if err == nil {
852 t.Errorf("nt.ConvertToNative(1) produced %v, wanted error", out)
853 }
854 }
855
856 func TestNativeTypeHasTrait(t *testing.T) {
857 nt, err := newNativeType(fieldNameByTag("cel"), reflect.TypeOf(&TestAllTypes{}))
858 if err != nil {
859 t.Fatalf("newNativeType() failed: %v", err)
860 }
861 if !nt.HasTrait(traits.IndexerType) || !nt.HasTrait(traits.FieldTesterType) {
862 t.Error("nt.HasTrait() failed indicate support for presence test and field access.")
863 }
864 }
865
866 func TestNativeTypeValue(t *testing.T) {
867 nt, err := newNativeType(fieldNameByTag("cel"), reflect.TypeOf(&TestAllTypes{}))
868 if err != nil {
869 t.Fatalf("newNativeType() failed: %v", err)
870 }
871 if nt.Value() != nt.String() {
872 t.Errorf("nt.Value() got %v, wanted %v", nt.Value(), nt.String())
873 }
874 }
875
876 func TestNativeStructWithMultipleSameFieldNames(t *testing.T) {
877 _, err := newNativeType(fieldNameByTag("cel"), reflect.TypeOf(TestStructWithMultipleSameNames{}))
878 if err == nil {
879 t.Fatal("newNativeType() did not fail as expected")
880 }
881 if !errors.Is(err, errDuplicatedFieldName) {
882 t.Fatalf("newNativeType() exepected duplicated field name error, but got: %v", err)
883 }
884 }
885
886 func TestNativeStructEmbedded(t *testing.T) {
887 var nativeTests = []struct {
888 expr string
889 in any
890 }{
891 {
892 expr: `test.embedded.custom_name == "name"`,
893 in: map[string]any{
894 "test": &TestEmbeddedTypes{TestNestedType{NestedCustomName: "name"}},
895 },
896 },
897 }
898
899 envOpts := []cel.EnvOption{
900 NativeTypes(
901 reflect.TypeOf(&TestEmbeddedTypes{}),
902 reflect.TypeOf(&TestNestedType{}),
903 ParseStructTag("json"),
904 ),
905 cel.Variable("test", cel.ObjectType("ext.TestEmbeddedTypes")),
906 }
907
908 env, err := cel.NewEnv(envOpts...)
909 if err != nil {
910 t.Fatalf("cel.NewEnv(NativeTypes()) failed: %v", err)
911 }
912
913 for i, tst := range nativeTests {
914 tc := tst
915 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
916 var asts []*cel.Ast
917 pAst, iss := env.Parse(tc.expr)
918 if iss.Err() != nil {
919 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
920 }
921 asts = append(asts, pAst)
922 cAst, iss := env.Check(pAst)
923 if iss.Err() != nil {
924 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
925 }
926 asts = append(asts, cAst)
927 for _, ast := range asts {
928 prg, err := env.Program(ast)
929 if err != nil {
930 t.Fatal(err)
931 }
932 out, _, err := prg.Eval(tc.in)
933 if err != nil {
934 t.Fatal(err)
935 }
936 if !reflect.DeepEqual(out.Value(), true) {
937 t.Errorf("got %v, wanted true for expr: %s", out.Value(), tc.expr)
938 }
939 }
940 })
941 }
942 }
943
944 type TestNestedStruct struct {
945 ListVal []*TestNestedType
946 }
947
948 func TestNativeNestedStruct(t *testing.T) {
949 var nativeTests = []struct {
950 expr string
951 in any
952 }{
953 {
954 expr: `test.ListVal.exists(x, x.custom_name == "name")`,
955 in: map[string]any{
956 "test": &TestNestedStruct{ListVal: []*TestNestedType{{NestedCustomName: "name"}}},
957 },
958 },
959 }
960
961 envOpts := []cel.EnvOption{
962 NativeTypes(
963 reflect.ValueOf(&TestNestedStruct{}),
964 ParseStructTag("json"),
965 ),
966 cel.Variable("test", cel.ObjectType("ext.TestNestedStruct")),
967 }
968
969 env, err := cel.NewEnv(envOpts...)
970 if err != nil {
971 t.Fatalf("cel.NewEnv(NativeTypes()) failed: %v", err)
972 }
973
974 for i, tst := range nativeTests {
975 tc := tst
976 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {
977 var asts []*cel.Ast
978 pAst, iss := env.Parse(tc.expr)
979 if iss.Err() != nil {
980 t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err())
981 }
982 asts = append(asts, pAst)
983 cAst, iss := env.Check(pAst)
984 if iss.Err() != nil {
985 t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err())
986 }
987 asts = append(asts, cAst)
988 for _, ast := range asts {
989 prg, err := env.Program(ast)
990 if err != nil {
991 t.Fatal(err)
992 }
993 out, _, err := prg.Eval(tc.in)
994 if err != nil {
995 t.Fatal(err)
996 }
997 if !reflect.DeepEqual(out.Value(), true) {
998 t.Errorf("got %v, wanted true for expr: %s", out.Value(), tc.expr)
999 }
1000 }
1001 })
1002 }
1003 }
1004
1005 func TestNativeTypesVersion(t *testing.T) {
1006 _, err := cel.NewEnv(NativeTypes(NativeTypesVersion(0)))
1007 if err != nil {
1008 t.Fatalf("NewEnv(NativeTypes(NativeTypesVersion(0))) failed: %v", err)
1009 }
1010 }
1011
1012 type Custom struct {
1013 Name string `cel:"name"`
1014 }
1015
1016 func TestTypeResolutionRace(t *testing.T) {
1017 customType := reflect.TypeFor[*Custom]()
1018 env, err := cel.NewEnv(
1019 cel.Container("ext"),
1020 NativeTypes(
1021 ParseStructTag("cel"),
1022 customType,
1023 ),
1024 )
1025 if err != nil {
1026 t.Fatal("NewEnv:", err)
1027 }
1028
1029 tests := []struct {
1030 name string
1031 expr string
1032 }{
1033 {name: "custom1", expr: `Custom{ name: "name1" }`},
1034 {name: "custom2", expr: `Custom{ name: "name2" }`},
1035 {name: "custom3", expr: `Custom{ name: "name3" }`},
1036 {name: "custom4", expr: `Custom{ name: "name4" }`},
1037 {name: "custom5", expr: `Custom{ name: "name5" }`},
1038 }
1039
1040 for _, test := range tests {
1041 t.Run(test.name, func(t *testing.T) {
1042 t.Parallel()
1043
1044 ast, iss := env.Compile(test.expr)
1045 if err := iss.Err(); err != nil {
1046 t.Fatal("Compile:", err)
1047 }
1048 prg, err := env.Program(ast)
1049 if err != nil {
1050 t.Fatalf("env.Program() failed: %s", err)
1051 }
1052 prg.Eval(cel.NoVars())
1053 })
1054 }
1055 }
1056
1057 // testEnv initializes the test environment common to all tests.
1058 func testNativeEnv(t *testing.T, opts ...any) *cel.Env {
1059 t.Helper()
1060 envOpts := []cel.EnvOption{
1061 cel.Container("ext"),
1062 cel.Abbrevs("google.expr.proto3.test"),
1063 cel.Types(&proto3pb.TestAllTypes{}),
1064 cel.Variable("tests", cel.ListType(cel.ObjectType("ext.TestAllTypes"))),
1065 }
1066 nativeOpts := []any{
1067 reflect.ValueOf(&TestAllTypes{}),
1068 }
1069 for _, o := range opts {
1070 switch opt := o.(type) {
1071 case NativeTypesOption:
1072 nativeOpts = append(nativeOpts, opt)
1073 case cel.EnvOption:
1074 envOpts = append(envOpts, opt)
1075 default:
1076 t.Fatalf("invalid option type: %s", reflect.TypeOf(o).Name())
1077 }
1078 }
1079
1080 envOpts = append(envOpts,
1081 NativeTypes(
1082 nativeOpts...,
1083 ),
1084 )
1085 env, err := cel.NewEnv(envOpts...)
1086 if err != nil {
1087 t.Fatalf("cel.NewEnv(NativeTypes()) failed: %v", err)
1088 }
1089 return env
1090 }
1091
1092 func mustParseTime(t *testing.T, timestamp string) time.Time {
1093 t.Helper()
1094 out, err := time.Parse(time.RFC3339, timestamp)
1095 if err != nil {
1096 t.Fatalf("time.Parse(%q) failed: %v", timestamp, err)
1097 }
1098 return out
1099 }
1100
1101 type TestStructWithMultipleSameNames struct {
1102 Name string
1103 custom_name string `cel:"Name"`
1104 }
1105
1106 type TestNestedType struct {
1107 NestedListVal []string
1108 NestedMapVal map[int64]bool
1109 NestedCustomName string `cel:"custom_name" json:"custom_name"`
1110 }
1111
1112 type TestAllTypes struct {
1113 NestedVal *TestNestedType `json:"nestedVal,omitempty"`
1114 NestedStructVal TestNestedType `json:"nestedStructVal"`
1115 BoolVal bool `json:"boolVal"`
1116 BytesVal []byte
1117 DurationVal time.Duration
1118 DoubleVal float64
1119 FloatVal float32
1120 Int32Val int32
1121 Int64Val int64
1122 StringVal string
1123 TimestampVal time.Time
1124 Uint32Val uint32
1125 Uint64Val uint64
1126 ListVal []*TestNestedType
1127 ArrayVal [1]*TestNestedType
1128 BytesArrayVal [4]byte
1129 MapVal map[string]TestAllTypes
1130 PbVal *proto3pb.TestAllTypes
1131 CustomSliceVal []TestNestedSliceType
1132 CustomMapVal map[string]TestMapVal
1133 CustomName string `cel:"custom_name"`
1134
1135 // channel types are not supported
1136 UnsupportedVal chan string
1137 UnsupportedListVal []chan string
1138 UnsupportedMapVal map[int]chan string
1139
1140 // unexported types can be found but not set or accessed
1141 privateVal map[string]string
1142 }
1143
1144 type TestNestedSliceType struct {
1145 Value string
1146 }
1147
1148 type TestMapVal struct {
1149 Value string
1150 }
1151
1152 type TestEmbeddedTypes struct {
1153 TestNestedType `json:"embedded,omitempty"`
1154 }