Debian Codegraph @

common/types/provider_test.go

raw
1 // Copyright 2018 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 types
16
17 import (
18 "bytes"
19 "fmt"
20 "reflect"
21 "sort"
22 "strings"
23 "testing"
24 "time"
25
26 "github.com/google/cel-go/common/types/ref"
27 "github.com/google/cel-go/common/types/traits"
28 "google.golang.org/protobuf/proto"
29
30 proto3pb "github.com/google/cel-go/test/proto3pb"
31 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
32 anypb "google.golang.org/protobuf/types/known/anypb"
33 dpb "google.golang.org/protobuf/types/known/durationpb"
34 structpb "google.golang.org/protobuf/types/known/structpb"
35 tpb "google.golang.org/protobuf/types/known/timestamppb"
36 wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
37 )
38
39 func TestRegistryCopy(t *testing.T) {
40 reg := NewEmptyRegistry()
41 reg2 := reg.Copy()
42 if !reflect.DeepEqual(reg, reg2) {
43 t.Fatal("type registry copy did not produce equivalent values.")
44 }
45 reg = newTestRegistry(t)
46 reg2 = reg.Copy()
47 if !reflect.DeepEqual(reg, reg2) {
48 t.Fatal("type registry copy did not produce equivalent values.")
49 }
50 }
51
52 func TestRegistryRegisterType(t *testing.T) {
53 reg := newTestRegistry(t)
54 err := reg.RegisterType(
55 NewTypeValue("http.Request", traits.ReceiverType),
56 NewObjectType("http.Request", traits.ReceiverType),
57 )
58 if err == nil {
59 t.Error("RegisterType() for differing type definitions with the same name did not fail")
60 }
61 }
62
63 func TestRegistryRegisterTypeNoConflict(t *testing.T) {
64 reg := newTestRegistry(t)
65 err := reg.RegisterType(
66 NewOpaqueType("http.Request", NewTypeParamType("T")),
67 NewOpaqueType("http.Request", NewTypeParamType("V")),
68 )
69 if err != nil {
70 t.Errorf("RegisterType() failed for equivalent types: %v", err)
71 }
72 }
73
74 func TestRegistryRegisterTypeConflict(t *testing.T) {
75 reg := newTestRegistry(t)
76 err := reg.RegisterType(
77 NewOpaqueType("http.Request", NewTypeParamType("T"), NewTypeParamType("V")),
78 NewOpaqueType("http.Request", NewTypeParamType("V")),
79 )
80 if err == nil {
81 t.Error("RegisterType() for differing type definitions with the same name did not fail")
82 }
83 }
84
85 func TestRegistryEnumValue(t *testing.T) {
86 reg := newTestRegistry(t)
87 err := reg.RegisterDescriptor(proto3pb.GlobalEnum_GOO.Descriptor().ParentFile())
88 if err != nil {
89 t.Fatalf("RegisterDescriptor() failed: %v", err)
90 }
91 enumVal := reg.EnumValue("google.expr.proto3.test.GlobalEnum.GOO")
92 if Int(proto3pb.GlobalEnum_GOO.Number()) != enumVal.(Int) {
93 t.Errorf("enum values were not equal between registry and proto: %v", enumVal)
94 }
95 enumVal2, found := reg.FindIdent("google.expr.proto3.test.GlobalEnum.GOO")
96 if !found {
97 t.Fatal("Ident not found google.expr.proto3.test.GlobalEnum.GOO")
98 }
99 if enumVal.(Int) != enumVal2.(Int) {
100 t.Errorf("got enum value %v, wanted %v", enumVal2, enumVal)
101 }
102 }
103
104 func TestRegistryFindStructType(t *testing.T) {
105 reg := newTestRegistry(t)
106 err := reg.RegisterDescriptor(proto3pb.GlobalEnum_GOO.Descriptor().ParentFile())
107 if err != nil {
108 t.Fatalf("RegisterDescriptor() failed: %v", err)
109 }
110 msgTypeName := ".google.expr.proto3.test.TestAllTypes"
111 exprType, found := reg.FindType(msgTypeName)
112 if !found {
113 t.Fatalf("FindType() did not find: %q", msgTypeName)
114 }
115 celType, found := reg.FindStructType(msgTypeName)
116 if !found {
117 t.Fatalf("FindStructType() did not find %q", msgTypeName)
118 }
119 exprConvType, err := ExprTypeToType(exprType)
120 if err != nil {
121 t.Fatalf("ExprTypeToType(%v) failed: %v", exprType, err)
122 }
123 if !exprConvType.IsExactType(celType) {
124 t.Errorf("Got %v type, wanted %v", exprConvType, celType)
125 }
126 _, found = reg.FindType(msgTypeName + "Undefined")
127 if found {
128 t.Fatalf("FindType() found: %q", msgTypeName+"Undefined")
129 }
130 _, found = reg.FindStructType(msgTypeName + "Undefined")
131 if found {
132 t.Fatalf("FindStructType() found: %q", msgTypeName+"Undefined")
133 }
134 }
135
136 func TestRegistryFindStructFieldNames(t *testing.T) {
137 reg := newTestRegistry(t, &exprpb.Decl{}, &exprpb.Reference{})
138 tests := []struct {
139 typeName string
140 fields []string
141 }{
142 {
143 typeName: "google.api.expr.v1alpha1.Reference",
144 fields: []string{"name", "overload_id", "value"},
145 },
146 {
147 typeName: "google.api.expr.v1alpha1.Decl",
148 fields: []string{"name", "ident", "function"},
149 },
150 {
151 typeName: "invalid.TypeName",
152 fields: []string{},
153 },
154 }
155
156 for _, tst := range tests {
157 tc := tst
158 t.Run(fmt.Sprintf("%s", tc.typeName), func(t *testing.T) {
159 fields, _ := reg.FindStructFieldNames(tc.typeName)
160 sort.Strings(fields)
161 sort.Strings(tc.fields)
162 if !reflect.DeepEqual(fields, tc.fields) {
163 t.Errorf("got %v, wanted %v", fields, tc.fields)
164 }
165 })
166 }
167 }
168
169 func TestRegistryFindStructFieldType(t *testing.T) {
170 reg := newTestRegistry(t)
171 err := reg.RegisterDescriptor(proto3pb.GlobalEnum_GOO.Descriptor().ParentFile())
172 if err != nil {
173 t.Fatalf("RegisterDescriptor() failed: %v", err)
174 }
175 msgTypeName := ".google.expr.proto3.test.TestAllTypes"
176 tests := []struct {
177 typeName string
178 field string
179 found bool
180 }{
181 {
182 typeName: msgTypeName,
183 field: "single_bool",
184 found: true,
185 },
186 {
187 typeName: msgTypeName,
188 field: "single_nested_message",
189 found: true,
190 },
191 {
192 typeName: msgTypeName,
193 field: "single_nested_message",
194 found: true,
195 },
196 {
197 typeName: msgTypeName,
198 field: "standalone_enum",
199 found: true,
200 },
201 {
202 typeName: msgTypeName,
203 field: "single_duration",
204 found: true,
205 },
206 {
207 typeName: msgTypeName,
208 field: "single_timestamp",
209 found: true,
210 },
211 {
212 typeName: msgTypeName,
213 field: "single_any",
214 found: true,
215 },
216 {
217 typeName: msgTypeName,
218 field: "single_int64_wrapper",
219 found: true,
220 },
221 {
222 typeName: msgTypeName,
223 field: "repeated_bool",
224 found: true,
225 },
226 {
227 typeName: msgTypeName,
228 field: "map_string_string",
229 found: true,
230 },
231 {
232 typeName: msgTypeName,
233 field: "double_bool",
234 found: false,
235 },
236 {
237 typeName: msgTypeName + "Undefined",
238 field: "map_string_string",
239 found: false,
240 },
241 }
242
243 for _, tst := range tests {
244 tc := tst
245 t.Run(fmt.Sprintf("%s.%s", tc.typeName, tc.field), func(t *testing.T) {
246 // When the field is expected to be found, test parity of the results
247 if tc.found {
248 refField, found := reg.FindFieldType(tc.typeName, tc.field)
249 if !found {
250 t.Fatalf("FindFieldType() did not find: %s.%s", tc.typeName, tc.field)
251 }
252 celField, found := reg.FindStructFieldType(tc.typeName, tc.field)
253 if !found {
254 t.Fatalf("FindStructFieldType() found: %s.%s", tc.typeName, tc.field)
255 }
256 convCelFieldType, err := ExprTypeToType(refField.Type)
257 if err != nil {
258 t.Fatalf("ExprTypeToType(%v) failed: %v", refField.Type, err)
259 }
260 if !convCelFieldType.IsExactType(celField.Type) {
261 t.Errorf("Got %v type, wanted %v", convCelFieldType, celField.Type)
262 }
263 return
264 }
265 // When the field is not expected to be round ensure both return not found.
266 if !tc.found {
267 _, found := reg.FindFieldType(tc.typeName, tc.field)
268 if found {
269 t.Errorf("FindFieldType() found: %s.%s", tc.typeName, tc.field)
270 }
271 _, found = reg.FindStructFieldType(tc.typeName, tc.field)
272 if found {
273 t.Errorf("FindStructFieldType() found: %s.%s", tc.typeName, tc.field)
274 }
275 }
276 })
277 }
278 }
279
280 func TestRegistryNewValue(t *testing.T) {
281 reg := newTestRegistry(t, &proto3pb.TestAllTypes{}, &exprpb.SourceInfo{})
282 tests := []struct {
283 typeName string
284 fields map[string]ref.Val
285 out proto.Message
286 }{
287 {
288 typeName: "google.expr.proto3.test.TestAllTypes",
289 fields: map[string]ref.Val{},
290 out: &proto3pb.TestAllTypes{},
291 },
292 {
293 typeName: "google.expr.proto3.test.TestAllTypes",
294 fields: map[string]ref.Val{
295 "standalone_enum": Int(1),
296 },
297 out: &proto3pb.TestAllTypes{
298 StandaloneEnum: proto3pb.TestAllTypes_BAR,
299 },
300 },
301 {
302 typeName: "google.expr.proto3.test.TestAllTypes",
303 fields: map[string]ref.Val{
304 "single_int32_wrapper": Int(123),
305 "single_int64_wrapper": NullValue,
306 },
307 out: &proto3pb.TestAllTypes{
308 SingleInt32Wrapper: wrapperspb.Int32(123),
309 },
310 },
311 {
312 typeName: "google.expr.proto3.test.TestAllTypes",
313 fields: map[string]ref.Val{
314 "repeated_int64": reg.NativeToValue([]int64{3, 2, 1}),
315 },
316 out: &proto3pb.TestAllTypes{
317 RepeatedInt64: []int64{3, 2, 1},
318 },
319 },
320 {
321 typeName: "google.expr.proto3.test.TestAllTypes",
322 fields: map[string]ref.Val{
323 "single_nested_enum": Int(2),
324 },
325 out: &proto3pb.TestAllTypes{
326 NestedType: &proto3pb.TestAllTypes_SingleNestedEnum{
327 SingleNestedEnum: proto3pb.TestAllTypes_BAZ,
328 },
329 },
330 },
331 {
332 typeName: "google.expr.proto3.test.TestAllTypes",
333 fields: map[string]ref.Val{
334 "single_value": True,
335 },
336 out: &proto3pb.TestAllTypes{
337 SingleValue: structpb.NewBoolValue(true),
338 },
339 },
340 {
341 typeName: "google.expr.proto3.test.TestAllTypes",
342 fields: map[string]ref.Val{
343 "single_value": reg.NativeToValue([]any{"hello", 10.2}),
344 },
345 out: &proto3pb.TestAllTypes{
346 SingleValue: structpb.NewListValue(
347 &structpb.ListValue{
348 Values: []*structpb.Value{
349 structpb.NewStringValue("hello"),
350 structpb.NewNumberValue(10.2),
351 },
352 },
353 ),
354 },
355 },
356 {
357 typeName: "google.expr.proto3.test.TestAllTypes",
358 fields: map[string]ref.Val{
359 "repeated_nested_message": reg.NativeToValue([]any{
360 &proto3pb.TestAllTypes_NestedMessage{Bb: 123},
361 }),
362 },
363 out: &proto3pb.TestAllTypes{
364 RepeatedNestedMessage: []*proto3pb.TestAllTypes_NestedMessage{{Bb: 123}},
365 },
366 },
367 {
368 typeName: "google.expr.proto3.test.TestAllTypes",
369 fields: map[string]ref.Val{
370 "map_int64_nested_type": reg.NativeToValue(map[int64]any{
371 1234: &proto3pb.NestedTestAllTypes{Payload: &proto3pb.TestAllTypes{SingleInt32: 1234}},
372 }),
373 },
374 out: &proto3pb.TestAllTypes{
375 MapInt64NestedType: map[int64]*proto3pb.NestedTestAllTypes{
376 1234: {Payload: &proto3pb.TestAllTypes{SingleInt32: 1234}},
377 },
378 },
379 },
380 {
381 typeName: "google.api.expr.v1alpha1.SourceInfo",
382 fields: map[string]ref.Val{
383 "location": String("TestRegistryNewValue"),
384 "line_offsets": reg.NativeToValue([]int64{0, 2}),
385 "positions": reg.NativeToValue(map[int64]int64{1: 2, 2: 4}),
386 },
387 out: &exprpb.SourceInfo{
388 Location: "TestRegistryNewValue",
389 LineOffsets: []int32{0, 2},
390 Positions: map[int64]int32{1: 2, 2: 4},
391 },
392 },
393 }
394 for i, tst := range tests {
395 tc := tst
396 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
397 out := reg.NewValue(tc.typeName, tc.fields)
398 if IsError(out) {
399 t.Fatalf("reg.NewValue(%s, %v) failed: %v", tc.typeName, tc.fields, out)
400 }
401 if !proto.Equal(tc.out, out.Value().(proto.Message)) {
402 t.Errorf("reg.NewValue() got %v, wanted %v", out, tc.out)
403 }
404 })
405 }
406 }
407
408 func TestRegistryNewValueErrors(t *testing.T) {
409 reg := newTestRegistry(t, &proto3pb.TestAllTypes{}, &exprpb.SourceInfo{})
410 tests := []struct {
411 typeName string
412 fields map[string]ref.Val
413 err string
414 }{
415 {
416 typeName: "google.expr.proto3.test.TestAllType",
417 fields: map[string]ref.Val{},
418 err: "unknown type",
419 },
420 {
421 typeName: "google.expr.proto3.test.TestAllTypes",
422 fields: map[string]ref.Val{
423 "undefined": Int(1),
424 },
425 err: "no such field",
426 },
427 {
428 typeName: "google.expr.proto3.test.TestAllTypes",
429 fields: map[string]ref.Val{
430 "single_int32_wrapper": True,
431 },
432 err: "type conversion error",
433 },
434 {
435 typeName: "google.expr.proto3.test.TestAllTypes",
436 fields: map[string]ref.Val{
437 "repeated_int64": reg.NativeToValue([]float64{1.0, 2.3}),
438 },
439 err: "type conversion error",
440 },
441 {
442 typeName: "google.expr.proto3.test.TestAllTypes",
443 fields: map[string]ref.Val{
444 "repeated_int64": Int(10),
445 },
446 err: "unsupported field type",
447 },
448 {
449 typeName: "google.expr.proto3.test.TestAllTypes",
450 fields: map[string]ref.Val{
451 "map_string_string": NullValue,
452 },
453 err: "unsupported field type",
454 },
455 {
456 typeName: "google.expr.proto3.test.TestAllTypes",
457 fields: map[string]ref.Val{
458 "map_string_string": reg.NativeToValue(map[string]int{"hello": 1}),
459 },
460 err: "type conversion error",
461 },
462 {
463 typeName: "google.expr.proto3.test.TestAllTypes",
464 fields: map[string]ref.Val{
465 "map_string_string": reg.NativeToValue(map[int]int{1: 1}),
466 },
467 err: "type conversion error",
468 },
469 }
470 for i, tst := range tests {
471 tc := tst
472 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
473 out := reg.NewValue(tc.typeName, tc.fields)
474 if !IsError(out) {
475 t.Fatalf("reg.NewValue(%s, %v) got %v, wanted error", tc.typeName, tc.fields, out)
476 }
477 err := out.(*Err)
478 if !strings.Contains(err.Error(), tc.err) {
479 t.Errorf("reg.NewValue() got error %v, wanted error %s", err, tc.err)
480 }
481 })
482 }
483 }
484
485 func TestRegistryGetters(t *testing.T) {
486 reg := newTestRegistry(t, &exprpb.ParsedExpr{})
487 if sourceInfo := reg.NewValue(
488 "google.api.expr.v1alpha1.SourceInfo",
489 map[string]ref.Val{
490 "location": String("TestTypeRegistryGetFieldValue"),
491 "line_offsets": NewDynamicList(reg, []int64{0, 2}),
492 "positions": NewDynamicMap(reg, map[int64]int64{1: 2, 2: 4}),
493 }); IsError(sourceInfo) {
494 t.Error(sourceInfo)
495 } else {
496 si := sourceInfo.(traits.Indexer)
497 if loc := si.Get(String("location")); IsError(loc) {
498 t.Error(loc)
499 } else if loc.(String) != "TestTypeRegistryGetFieldValue" {
500 t.Errorf("Expected %s, got %s", "TestTypeRegistryGetFieldValue", loc)
501 }
502 if pos := si.Get(String("positions")); IsError(pos) {
503 t.Error(pos)
504 } else if pos.Equal(NewDynamicMap(reg, map[int64]int32{1: 2, 2: 4})) != True {
505 t.Errorf("Expected map[int64]int32, got %v", pos)
506 } else if posKeyVal := pos.(traits.Indexer).Get(Int(1)); IsError(posKeyVal) {
507 t.Error(posKeyVal)
508 } else if posKeyVal.(Int) != 2 {
509 t.Error("Expected value to be int64, not int32")
510 }
511 if offsets := si.Get(String("line_offsets")); IsError(offsets) {
512 t.Error(offsets)
513 } else if offset1 := offsets.(traits.Lister).Get(Int(1)); IsError(offset1) {
514 t.Error(offset1)
515 } else if offset1.(Int) != 2 {
516 t.Errorf("Expected index 1 to be value 2, was %v", offset1)
517 }
518 }
519 }
520
521 func TestConvertToNative(t *testing.T) {
522 reg := newTestRegistry(t, &exprpb.ParsedExpr{})
523
524 // Core type conversion tests.
525 expectValueToNative(t, True, true)
526 expectValueToNative(t, True, True)
527 expectValueToNative(t, NewDynamicList(reg, []Bool{True, False}), []any{true, false})
528 expectValueToNative(t, NewDynamicList(reg, []Bool{True, False}), []ref.Val{True, False})
529 expectValueToNative(t, Int(-1), int32(-1))
530 expectValueToNative(t, Int(2), int64(2))
531 expectValueToNative(t, Int(-1), Int(-1))
532 expectValueToNative(t, NewDynamicList(reg, []Int{4}), []any{int64(4)})
533 expectValueToNative(t, NewDynamicList(reg, []Int{5}), []ref.Val{Int(5)})
534 expectValueToNative(t, Uint(3), uint32(3))
535 expectValueToNative(t, Uint(4), uint64(4))
536 expectValueToNative(t, Uint(5), Uint(5))
537 expectValueToNative(t, NewDynamicList(reg, []Uint{4}), []any{uint64(4)})
538 expectValueToNative(t, NewDynamicList(reg, []Uint{5}), []ref.Val{Uint(5)})
539 expectValueToNative(t, Double(5.5), float32(5.5))
540 expectValueToNative(t, Double(-5.5), float64(-5.5))
541 expectValueToNative(t, NewDynamicList(reg, []Double{-5.5}), []any{-5.5})
542 expectValueToNative(t, NewDynamicList(reg, []Double{-5.5}), []ref.Val{Double(-5.5)})
543 expectValueToNative(t, Double(-5.5), Double(-5.5))
544 expectValueToNative(t, String("hello"), "hello")
545 expectValueToNative(t, String("hello"), String("hello"))
546 expectValueToNative(t, NullValue, structpb.NullValue_NULL_VALUE)
547 expectValueToNative(t, NullValue, NullValue)
548 expectValueToNative(t, NewDynamicList(reg, []Null{NullValue}), []any{structpb.NullValue_NULL_VALUE})
549 expectValueToNative(t, NewDynamicList(reg, []Null{NullValue}), []ref.Val{NullValue})
550 expectValueToNative(t, Bytes("world"), []byte("world"))
551 expectValueToNative(t, Bytes("world"), Bytes("world"))
552 expectValueToNative(t, NewDynamicList(reg, []Bytes{Bytes("hello")}), []any{[]byte("hello")})
553 expectValueToNative(t, NewDynamicList(reg, []Bytes{Bytes("hello")}), []ref.Val{Bytes("hello")})
554 expectValueToNative(t, NewDynamicList(reg, []int64{1, 2, 3}), []int32{1, 2, 3})
555 expectValueToNative(t, Duration{Duration: time.Duration(500)}, time.Duration(500))
556 expectValueToNative(t, Duration{Duration: time.Duration(500)}, Duration{Duration: time.Duration(500)})
557 expectValueToNative(t, Timestamp{Time: time.Unix(12345, 0)}, time.Unix(12345, 0))
558 expectValueToNative(t, Timestamp{Time: time.Unix(12345, 0)}, Timestamp{Time: time.Unix(12345, 0)})
559 expectValueToNative(t, NewDynamicMap(reg,
560 map[int64]int64{1: 1, 2: 1, 3: 1}),
561 map[int32]int32{1: 1, 2: 1, 3: 1})
562
563 // Null conversion tests.
564 expectValueToNative(t, Null(structpb.NullValue_NULL_VALUE), structpb.NullValue_NULL_VALUE)
565
566 // Proto conversion tests.
567 parsedExpr := &exprpb.ParsedExpr{}
568 expectValueToNative(t, reg.NativeToValue(parsedExpr), parsedExpr)
569
570 // Custom scalars
571 expectValueToNative(t, Int(1), testInt(1))
572 expectValueToNative(t, Int(1), testInt8(1))
573 expectValueToNative(t, Int(1), testInt16(1))
574 expectValueToNative(t, Int(1), testInt32(1))
575 expectValueToNative(t, Int(1), testInt64(1))
576 expectValueToNative(t, Uint(1), testUint(1))
577 expectValueToNative(t, Uint(1), testUint8(1))
578 expectValueToNative(t, Uint(1), testUint16(1))
579 expectValueToNative(t, Uint(1), testUint32(1))
580 expectValueToNative(t, Uint(1), testUint64(1))
581 expectValueToNative(t, Double(4.5), testFloat32(4.5))
582 expectValueToNative(t, Double(-5.1), testFloat64(-5.1))
583 expectValueToNative(t, String("foo"), testString("foo"))
584 }
585
586 func TestNativeToValue_Any(t *testing.T) {
587 reg := newTestRegistry(t, &exprpb.ParsedExpr{})
588 // NullValue
589 anyValue, err := NullValue.ConvertToNative(anyValueType)
590 if err != nil {
591 t.Error(err)
592 }
593 expectNativeToValue(t, anyValue, NullValue)
594
595 // Json Struct
596 anyValue, err = anypb.New(
597 structpb.NewStructValue(
598 &structpb.Struct{
599 Fields: map[string]*structpb.Value{
600 "a": structpb.NewStringValue("world"),
601 "b": structpb.NewStringValue("five!"),
602 },
603 },
604 ),
605 )
606 if err != nil {
607 t.Error(err)
608 }
609 expected := NewJSONStruct(reg, &structpb.Struct{
610 Fields: map[string]*structpb.Value{
611 "a": structpb.NewStringValue("world"),
612 "b": structpb.NewStringValue("five!"),
613 },
614 })
615 expectNativeToValue(t, anyValue, expected)
616
617 //Json List
618 anyValue, err = anypb.New(structpb.NewListValue(
619 &structpb.ListValue{
620 Values: []*structpb.Value{
621 structpb.NewStringValue("world"),
622 structpb.NewStringValue("five!"),
623 },
624 },
625 ))
626 if err != nil {
627 t.Error(err)
628 }
629 expectedList := NewJSONList(reg, &structpb.ListValue{
630 Values: []*structpb.Value{
631 structpb.NewStringValue("world"),
632 structpb.NewStringValue("five!"),
633 }})
634 expectNativeToValue(t, anyValue, expectedList)
635
636 // Object
637 pbMessage := exprpb.ParsedExpr{
638 SourceInfo: &exprpb.SourceInfo{
639 LineOffsets: []int32{1, 2, 3}}}
640 anyValue, err = anypb.New(&pbMessage)
641 if err != nil {
642 t.Error(err)
643 }
644 expectNativeToValue(t, anyValue, reg.NativeToValue(&pbMessage))
645 }
646
647 func TestNativeToValue_Json(t *testing.T) {
648 reg := newTestRegistry(t, &exprpb.ParsedExpr{})
649 // Json primitive conversion test.
650 expectNativeToValue(t, structpb.NewBoolValue(false), False)
651 expectNativeToValue(t, structpb.NewNumberValue(1.1), Double(1.1))
652 expectNativeToValue(t, structpb.NewNullValue(), Null(structpb.NullValue_NULL_VALUE))
653 expectNativeToValue(t, structpb.NewStringValue("hello"), String("hello"))
654
655 // Json list conversion.
656 expectNativeToValue(t,
657 structpb.NewListValue(
658 &structpb.ListValue{
659 Values: []*structpb.Value{
660 structpb.NewStringValue("world"),
661 structpb.NewStringValue("five!"),
662 },
663 },
664 ),
665 NewJSONList(reg, &structpb.ListValue{
666 Values: []*structpb.Value{
667 structpb.NewStringValue("world"),
668 structpb.NewStringValue("five!"),
669 },
670 }))
671
672 // Json struct conversion.
673 expectNativeToValue(t,
674 structpb.NewStructValue(
675 &structpb.Struct{
676 Fields: map[string]*structpb.Value{
677 "a": structpb.NewStringValue("world"),
678 "b": structpb.NewStringValue("five!"),
679 },
680 },
681 ),
682 NewJSONStruct(reg, &structpb.Struct{
683 Fields: map[string]*structpb.Value{
684 "a": structpb.NewStringValue("world"),
685 "b": structpb.NewStringValue("five!"),
686 },
687 }))
688
689 // Proto conversion test.
690 parsedExpr := &exprpb.ParsedExpr{}
691 expectNativeToValue(t, parsedExpr, reg.NativeToValue(parsedExpr))
692 }
693
694 func TestNativeToValue_Wrappers(t *testing.T) {
695 // Wrapper conversion test.
696 expectNativeToValue(t, wrapperspb.Bool(true), True)
697 expectNativeToValue(t, &wrapperspb.BoolValue{}, False)
698 expectNativeToValue(t, (*wrapperspb.BoolValue)(nil), NullValue)
699 expectNativeToValue(t, &wrapperspb.BytesValue{}, Bytes{})
700 expectNativeToValue(t, wrapperspb.Bytes([]byte("hi")), Bytes("hi"))
701 expectNativeToValue(t, (*wrapperspb.BytesValue)(nil), NullValue)
702 expectNativeToValue(t, &wrapperspb.DoubleValue{}, Double(0.0))
703 expectNativeToValue(t, wrapperspb.Double(6.4), Double(6.4))
704 expectNativeToValue(t, (*wrapperspb.DoubleValue)(nil), NullValue)
705 expectNativeToValue(t, &wrapperspb.FloatValue{}, Double(0.0))
706 expectNativeToValue(t, wrapperspb.Float(3.0), Double(3.0))
707 expectNativeToValue(t, (*wrapperspb.FloatValue)(nil), NullValue)
708 expectNativeToValue(t, &wrapperspb.Int32Value{}, IntZero)
709 expectNativeToValue(t, wrapperspb.Int32(-32), Int(-32))
710 expectNativeToValue(t, (*wrapperspb.Int32Value)(nil), NullValue)
711 expectNativeToValue(t, &wrapperspb.Int64Value{}, IntZero)
712 expectNativeToValue(t, wrapperspb.Int64(-64), Int(-64))
713 expectNativeToValue(t, (*wrapperspb.Int64Value)(nil), NullValue)
714 expectNativeToValue(t, &wrapperspb.StringValue{}, String(""))
715 expectNativeToValue(t, wrapperspb.String("hello"), String("hello"))
716 expectNativeToValue(t, (*wrapperspb.StringValue)(nil), NullValue)
717 expectNativeToValue(t, &wrapperspb.UInt32Value{}, Uint(0))
718 expectNativeToValue(t, wrapperspb.UInt32(32), Uint(32))
719 expectNativeToValue(t, (*wrapperspb.UInt32Value)(nil), NullValue)
720 expectNativeToValue(t, &wrapperspb.UInt64Value{}, Uint(0))
721 expectNativeToValue(t, wrapperspb.UInt64(64), Uint(64))
722 expectNativeToValue(t, (*wrapperspb.UInt64Value)(nil), NullValue)
723 }
724
725 func TestNativeToValue_Primitive(t *testing.T) {
726 reg := newTestRegistry(t)
727
728 // Core type conversions.
729 expectNativeToValue(t, true, True)
730 expectNativeToValue(t, int(-10), Int(-10))
731 expectNativeToValue(t, int32(-1), Int(-1))
732 expectNativeToValue(t, int64(2), Int(2))
733 expectNativeToValue(t, uint(6), Uint(6))
734 expectNativeToValue(t, uint32(3), Uint(3))
735 expectNativeToValue(t, uint64(4), Uint(4))
736 expectNativeToValue(t, float32(5.5), Double(5.5))
737 expectNativeToValue(t, float64(-5.5), Double(-5.5))
738 expectNativeToValue(t, "hello", String("hello"))
739 expectNativeToValue(t, []byte("world"), Bytes("world"))
740 expectNativeToValue(t, [4]byte{1, 2, 3, 4}, Bytes([]byte{1, 2, 3, 4}))
741 expectNativeToValue(t, &[4]byte{1, 2, 3, 4}, Bytes([]byte{1, 2, 3, 4}))
742 expectNativeToValue(t, time.Duration(500), Duration{Duration: time.Duration(500)})
743 expectNativeToValue(t, time.Unix(12345, 0), Timestamp{Time: time.Unix(12345, 0)})
744 expectNativeToValue(t, dpb.New(time.Duration(500)), Duration{Duration: time.Duration(500)})
745 expectNativeToValue(t, tpb.New(time.Unix(12345, 0)), Timestamp{Time: time.Unix(12345, 0)})
746 expectNativeToValue(t, []int32{1, 2, 3}, NewDynamicList(reg, []int32{1, 2, 3}))
747 expectNativeToValue(t, map[int32]int32{1: 1, 2: 1, 3: 1},
748 NewDynamicMap(reg, map[int32]int32{1: 1, 2: 1, 3: 1}))
749
750 // Pointers to core types.
751 pBool := true
752 expectNativeToValue(t, &pBool, True)
753 pDub32 := float32(2.5)
754 pDub64 := float64(-1000.2)
755 expectNativeToValue(t, &pDub32, Double(2.5))
756 expectNativeToValue(t, &pDub64, Double(-1000.2))
757 pInt := int(1)
758 pInt32 := int32(2)
759 pInt64 := int64(-1000)
760 expectNativeToValue(t, &pInt, Int(1))
761 expectNativeToValue(t, &pInt32, Int(2))
762 expectNativeToValue(t, &pInt64, Int(-1000))
763 pStr := "hello"
764 expectNativeToValue(t, &pStr, String("hello"))
765 pUint := uint(1)
766 pUint32 := uint32(2)
767 pUint64 := uint64(1000)
768 expectNativeToValue(t, &pUint, Uint(1))
769 expectNativeToValue(t, &pUint32, Uint(2))
770 expectNativeToValue(t, &pUint64, Uint(1000))
771
772 // Pointers to ref.Val extensions of core types.
773 rBool := True
774 expectNativeToValue(t, &rBool, True)
775 rDub := Double(32.1)
776 expectNativeToValue(t, &rDub, rDub)
777 rInt := Int(-12)
778 expectNativeToValue(t, &rInt, rInt)
779 rStr := String("hello")
780 expectNativeToValue(t, &rStr, rStr)
781 rUint := Uint(12405)
782 expectNativeToValue(t, &rUint, rUint)
783 rBytes := Bytes([]byte("hello"))
784 expectNativeToValue(t, &rBytes, rBytes)
785
786 // Extensions to core types.
787 expectNativeToValue(t, testInt(1), Int(1))
788 expectNativeToValue(t, testInt8(1), Int(1))
789 expectNativeToValue(t, testInt16(1), Int(1))
790 expectNativeToValue(t, testInt32(1), Int(1))
791 expectNativeToValue(t, testInt64(-100), Int(-100))
792 expectNativeToValue(t, testUint(1), Uint(1))
793 expectNativeToValue(t, testUint8(1), Uint(1))
794 expectNativeToValue(t, testUint16(1), Uint(1))
795 expectNativeToValue(t, testUint32(2), Uint(2))
796 expectNativeToValue(t, testUint64(3), Uint(3))
797 expectNativeToValue(t, testFloat32(4.5), Double(4.5))
798 expectNativeToValue(t, testFloat64(-5.1), Double(-5.1))
799 expectNativeToValue(t, testString("foo"), String("foo"))
800
801 // Null conversion test.
802 expectNativeToValue(t, nil, NullValue)
803 expectNativeToValue(t, structpb.NullValue_NULL_VALUE, Null(structpb.NullValue_NULL_VALUE))
804 }
805
806 func TestUnsupportedConversion(t *testing.T) {
807 reg := newTestRegistry(t)
808 if val := reg.NativeToValue(nonConvertible{}); !IsError(val) {
809 t.Error("Expected error when converting non-proto struct to proto", val)
810 }
811 }
812
813 func expectValueToNative(t *testing.T, in ref.Val, out any) {
814 t.Helper()
815 if val, err := in.ConvertToNative(reflect.TypeOf(out)); err != nil {
816 t.Error(err)
817 } else {
818 var equals bool
819 switch val.(type) {
820 case []byte:
821 equals = bytes.Equal(val.([]byte), out.([]byte))
822 case proto.Message:
823 equals = proto.Equal(val.(proto.Message), out.(proto.Message))
824 case bool, int32, int64, uint32, uint64, float32, float64, string:
825 equals = val == out
826 default:
827 equals = reflect.DeepEqual(val, out)
828 }
829 if !equals {
830 t.Errorf("Unexpected conversion from expr to proto.\n"+
831 "expected: %T, actual: %T", out, val)
832 }
833 }
834 }
835
836 func expectNativeToValue(t *testing.T, in any, out ref.Val) {
837 t.Helper()
838 reg := newTestRegistry(t, &exprpb.ParsedExpr{})
839 if val := reg.NativeToValue(in); IsError(val) {
840 t.Error(val)
841 } else {
842 if val.Equal(out) != True {
843 t.Errorf("Unexpected conversion from expr to proto.\n"+
844 "expected: %T, actual: %T", val, out)
845 }
846 }
847 }
848
849 func BenchmarkNativeToValue(b *testing.B) {
850 reg, err := NewRegistry()
851 if err != nil {
852 b.Fatalf("NewRegistry() failed: %v", err)
853 }
854 inputs := []any{
855 true,
856 false,
857 float32(-1.2),
858 float64(-2.4),
859 1,
860 int32(2),
861 int64(3),
862 "",
863 "hello",
864 String("hello world"),
865 }
866 for _, in := range inputs {
867 input := in
868 b.Run(fmt.Sprintf("%T/%v", in, in), func(b *testing.B) {
869 for i := 0; i < b.N; i++ {
870 reg.NativeToValue(input)
871 }
872 })
873 }
874 }
875
876 func BenchmarkTypeProviderNewValue(b *testing.B) {
877 reg, err := NewRegistry(&exprpb.ParsedExpr{})
878 if err != nil {
879 b.Fatalf("NewRegistry() failed: %v", err)
880 }
881 for i := 0; i < b.N; i++ {
882 reg.NewValue(
883 "google.api.expr.v1.SourceInfo",
884 map[string]ref.Val{
885 "Location": String("BenchmarkTypeProvider_NewValue"),
886 "LineOffsets": NewDynamicList(reg, []int64{0, 2}),
887 "Positions": NewDynamicMap(reg, map[int64]int64{1: 2, 2: 4}),
888 })
889 }
890 }
891
892 func BenchmarkTypeProviderCopy(b *testing.B) {
893 reg, err := NewRegistry()
894 if err != nil {
895 b.Fatalf("NewRegistry() failed: %v", err)
896 }
897 for i := 0; i < b.N; i++ {
898 reg.Copy()
899 }
900 }
901
902 // Helper types useful for testing extensions of primitive types.
903 type nonConvertible struct {
904 Field string
905 }
906 type testBool bool
907 type testInt int
908 type testInt8 int8
909 type testInt16 int16
910 type testInt32 int32
911 type testInt64 int64
912 type testUint uint
913 type testUint8 uint8
914 type testUint16 uint16
915 type testUint32 uint32
916 type testUint64 uint64
917 type testFloat32 float32
918 type testFloat64 float64
919 type testString string
920
921 func newTestRegistry(t *testing.T, types ...proto.Message) *Registry {
922 t.Helper()
923 reg, err := NewRegistry(types...)
924 if err != nil {
925 t.Fatalf("NewRegistry(%v) failed: %v", types, err)
926 }
927 return reg
928 }