| 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 checker |
| 16 | |
| 17 | import ( |
| 18 | "testing" |
| 19 | |
| 20 | "github.com/google/cel-go/checker/decls" |
| 21 | "github.com/google/cel-go/common/types" |
| 22 | ) |
| 23 | |
| 24 | func TestFormatType(t *testing.T) { |
| 25 | tests := []*types.Type{ |
| 26 | types.AnyType, |
| 27 | types.BoolType, |
| 28 | types.BytesType, |
| 29 | types.DoubleType, |
| 30 | types.DurationType, |
| 31 | types.DynType, |
| 32 | types.ErrorType, |
| 33 | types.IntType, |
| 34 | types.NewListType(types.StringType), |
| 35 | types.NewMapType(types.IntType, types.DynType), |
| 36 | types.NewObjectType("dev.cel.Expr"), |
| 37 | types.NewOptionalType(types.BoolType), |
| 38 | types.NewNullableType(types.IntType), |
| 39 | types.NewTypeParamType("T"), |
| 40 | types.NewTypeTypeWithParam(types.NewListType(types.IntType)), |
| 41 | types.NullType, |
| 42 | types.StringType, |
| 43 | types.TimestampType, |
| 44 | types.TypeType, |
| 45 | types.UintType, |
| 46 | } |
| 47 | for _, tst := range tests { |
| 48 | tc := tst |
| 49 | t.Run(tc.DeclaredTypeName(), func(t *testing.T) { |
| 50 | exprType, err := types.TypeToExprType(tc) |
| 51 | if err != nil { |
| 52 | t.Fatalf("types.TypeToExprType(%v) failed: %v", tc, err) |
| 53 | } |
| 54 | if FormatCELType(tc) != FormatCheckedType(exprType) { |
| 55 | t.Errorf("FormatCELType(%v) not equal to FormatCheckedType(%v), got %s, wanted %s", |
| 56 | tc, exprType, FormatCELType(tc), FormatCheckedType(exprType)) |
| 57 | } |
| 58 | }) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func TestFormatFunctionType(t *testing.T) { |
| 63 | // native type representation of function(string, int) -> bool |
| 64 | ct := FormatCELType(newFunctionType(types.BoolType, types.StringType, types.IntType)) |
| 65 | // protobuf-based function type |
| 66 | et := FormatCheckedType(decls.NewFunctionType(decls.Bool, decls.String, decls.Int)) |
| 67 | if ct != et { |
| 68 | t.Errorf("FormatCELType() not equal to FormatCheckedType(), got %s, wanted %s", ct, et) |
| 69 | } |
| 70 | } |