Debian Codegraph @

cel/io_test.go

raw symbols SCIP
1 // Copyright 2019 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 cel
16
17 import (
18 "fmt"
19 "strings"
20 "testing"
21 "time"
22
23 "google.golang.org/protobuf/proto"
24
25 "github.com/google/cel-go/checker/decls"
26 celast "github.com/google/cel-go/common/ast"
27 "github.com/google/cel-go/common/operators"
28 "github.com/google/cel-go/common/types"
29 "github.com/google/cel-go/common/types/ref"
30
31 proto3pb "github.com/google/cel-go/test/proto3pb"
32 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
33 )
34
35 func TestRefValueToValueRoundTrip(t *testing.T) {
36 tests := []struct {
37 value any
38 }{
39 {value: types.NullValue},
40 {value: types.Bool(true)},
41 {value: types.String("abc")},
42 {value: types.Double(0.0)},
43 {value: types.Bytes(make([]byte, 0, 5))},
44 {value: types.Int(0)},
45 {value: types.Uint(0)},
46 {value: types.Duration{Duration: time.Hour}},
47 {value: types.Timestamp{Time: time.Unix(0, 0)}},
48 {value: types.IntType},
49 {value: types.NewOpaqueType("CustomType")},
50 {value: map[int64]int64{1: 1}},
51 {value: []any{true, "abc"}},
52 {value: &proto3pb.TestAllTypes{SingleString: "abc"}},
53 }
54
55 env, err := NewEnv(Types(&proto3pb.TestAllTypes{}))
56 if err != nil {
57 t.Fatalf("NewEnv() failed: %v", err)
58 }
59
60 for i, tst := range tests {
61 tc := tst
62 t.Run(fmt.Sprintf("[%d]%v", i, tc.value), func(t *testing.T) {
63 refVal := env.TypeAdapter().NativeToValue(tc.value)
64 val, err := RefValueToValue(refVal)
65 if err != nil {
66 t.Fatalf("RefValueToValue(%v) failed with error: %v", refVal, err)
67 }
68 actual, err := ValueToRefValue(env.TypeAdapter(), val)
69 if err != nil {
70 t.Fatalf("ValueToRefValue() failed: %v", err)
71 }
72 if refVal.Equal(actual) != types.True {
73 t.Errorf("got val %v, wanted %v", actual, refVal)
74 }
75 })
76 }
77 }
78
79 func TestAstToProto(t *testing.T) {
80 stdEnv, _ := NewEnv(Declarations(
81 decls.NewVar("a", decls.Dyn),
82 decls.NewVar("b", decls.Dyn),
83 ))
84 ast, iss := stdEnv.Parse("a + b")
85 if iss.Err() != nil {
86 t.Fatalf("Parse('a + b') failed: %v", iss.Err())
87 }
88 parsed, err := AstToParsedExpr(ast)
89 if err != nil {
90 t.Fatalf("AstToParsedExpr() failed: %v", err)
91 }
92 ast2 := ParsedExprToAst(parsed)
93 if !proto.Equal(ast2.Expr(), ast.Expr()) {
94 t.Errorf("got expr %v, wanted %v", ast2, ast)
95 }
96 ast3 := ParsedExprToAstWithSource(parsed, ast.Source())
97 if !proto.Equal(ast3.Expr(), ast.Expr()) {
98 t.Errorf("got expr %v, wanted %v", ast2, ast)
99 }
100 if ast3.Source() != ast.Source() {
101 t.Errorf("got source %v, wanted %v", ast3.Source(), ast.Source())
102 }
103
104 _, err = AstToCheckedExpr(ast)
105 if err == nil {
106 t.Error("expected error converting unchecked ast")
107 }
108 ast, iss = stdEnv.Check(ast)
109 if iss != nil && iss.Err() != nil {
110 t.Fatalf("stdEnv.Check(ast) failed: %v", iss.Err())
111 }
112 checked, err := AstToCheckedExpr(ast)
113 if err != nil {
114 t.Fatalf("AstToCheckedExpr(ast) failed: %v", err)
115 }
116 ast4 := CheckedExprToAst(checked)
117 if !proto.Equal(ast4.Expr(), ast.Expr()) {
118 t.Fatalf("got ast %v, wanted %v", ast4, ast)
119 }
120 ast5, err := CheckedExprToAstWithSource(checked, ast.Source())
121 if err != nil {
122 t.Fatalf("CheckedExprToAstWithSource() failed: %v", err)
123 }
124 if !proto.Equal(ast5.Expr(), ast.Expr()) {
125 t.Errorf("got expr %v, wanted %v", ast5, ast)
126 }
127 if ast5.Source() != ast.Source() {
128 t.Errorf("got source %v, wanted %v", ast5.Source(), ast.Source())
129 }
130 }
131
132 func TestAstToString(t *testing.T) {
133 stdEnv, err := NewEnv()
134 if err != nil {
135 t.Fatalf("NewEnv() failed: %v", err)
136 }
137 in := "a + b - (c ? (-d + 4) : e)"
138 ast, iss := stdEnv.Parse(in)
139 if iss.Err() != nil {
140 t.Fatalf("stdEnv.Parse(%q) failed: %v", in, iss.Err())
141 }
142 expr, err := AstToString(ast)
143 if err != nil {
144 t.Fatalf("AstToString(ast) failed: %v", err)
145 }
146 if expr != in {
147 t.Errorf("got %v, wanted %v", expr, in)
148 }
149 }
150
151 func TestExprToString(t *testing.T) {
152 stdEnv, err := NewEnv(EnableMacroCallTracking())
153 if err != nil {
154 t.Fatalf("NewEnv() failed: %v", err)
155 }
156 in := "[a, b].filter(i, (i > 0) ? (-i + 4) : i)"
157 ast, iss := stdEnv.Parse(in)
158 if iss.Err() != nil {
159 t.Fatalf("stdEnv.Parse(%q) failed: %v", in, iss.Err())
160 }
161 expr, err := ExprToString(ast.NativeRep().Expr(), ast.NativeRep().SourceInfo())
162 if err != nil {
163 t.Fatalf("ExprToString(ast) failed: %v", err)
164 }
165 if expr != in {
166 t.Errorf("got %v, wanted %v", expr, in)
167 }
168
169 // Test sub-expression unparsing.
170 navExpr := celast.NavigateAST(ast.NativeRep())
171 condExpr := celast.MatchDescendants(navExpr, celast.FunctionMatcher(operators.Conditional))[0]
172 want := `(i > 0) ? (-i + 4) : i`
173 expr, err = ExprToString(condExpr, ast.NativeRep().SourceInfo())
174 if err != nil {
175 t.Fatalf("ExprToString(ast) failed: %v", err)
176 }
177 if expr != want {
178 t.Errorf("got %v, wanted %v", expr, want)
179 }
180
181 // Also passes with a nil source info, but only because the sub-expr doesn't contain macro calls.
182 expr, err = ExprToString(condExpr, nil)
183 if err != nil {
184 t.Fatalf("ExprToString(ast) failed: %v", err)
185 }
186 if expr != want {
187 t.Errorf("got %v, wanted %v", expr, want)
188 }
189
190 // Fails do to missing macro information.
191 _, err = ExprToString(ast.NativeRep().Expr(), nil)
192 if err == nil {
193 t.Error("ExprToString() succeeded, wanted error")
194 }
195 }
196
197 func TestRefValToExprValue(t *testing.T) {
198 tests := []struct {
199 name string
200 refVal ref.Val
201 expectError bool
202 }{
203 {
204 name: "unknown value",
205 refVal: types.NewUnknown(1, nil),
206 expectError: false,
207 },
208 {
209 name: "error value",
210 refVal: types.NewErr("test error"),
211 expectError: false,
212 },
213 {
214 name: "bool value",
215 refVal: types.Bool(true),
216 expectError: false,
217 },
218 {
219 name: "string value",
220 refVal: types.String("test"),
221 expectError: false,
222 },
223 {
224 name: "int value",
225 refVal: types.Int(1),
226 expectError: false,
227 },
228 }
229 for _, tst := range tests {
230 tc := tst
231 t.Run(tc.name, func(t *testing.T) {
232 exprVal, err := ExprValueAsProto(tc.refVal)
233 if tc.expectError {
234 if err == nil {
235 t.Errorf("RefValToExprValue(%v) expected error, got %v", tc.refVal, exprVal)
236 }
237 } else {
238 if err != nil {
239 t.Errorf("RefValToExprValue(%v) failed with error: %v", tc.refVal, err)
240 }
241 if exprVal == nil {
242 t.Errorf("RefValToExprValue(%v) expected value, got nil", tc.refVal)
243 }
244 }
245 })
246 }
247 }
248
249 func TestAstToStringNil(t *testing.T) {
250 expr, err := AstToString(nil)
251 if err == nil || !strings.Contains(err.Error(), "unsupported expr") {
252 t.Errorf("env.AstToString() got (%v, %v) wanted unsupported expr error", expr, err)
253 }
254 }
255
256 func TestAstToCheckedExprNil(t *testing.T) {
257 expr, err := AstToCheckedExpr(nil)
258 if err == nil || !strings.Contains(err.Error(), "cannot convert unchecked ast") {
259 t.Errorf("env.AstToCheckedExpr() got (%v, %v) wanted conversion error", expr, err)
260 }
261 }
262
263 func TestAstToParsedExprNil(t *testing.T) {
264 expr, err := AstToParsedExpr(nil)
265 if err != nil {
266 t.Errorf("env.AstToParsedExpr() got (%v, %v) wanted conversion error", expr, err)
267 }
268 }
269
270 func TestCheckedExprToAstConstantExpr(t *testing.T) {
271 stdEnv, err := NewEnv()
272 if err != nil {
273 t.Fatalf("NewEnv() failed: %v", err)
274 }
275 in := "10"
276 ast, iss := stdEnv.Compile(in)
277 if iss.Err() != nil {
278 t.Fatalf("stdEnv.Compile(%q) failed: %v", in, iss.Err())
279 }
280 expr, err := AstToCheckedExpr(ast)
281 if err != nil {
282 t.Fatalf("AstToCheckedExpr(ast) failed: %v", err)
283 }
284 ast2 := CheckedExprToAst(expr)
285 if !proto.Equal(ast2.Expr(), ast.Expr()) {
286 t.Fatalf("got ast %v, wanted %v", ast2, ast)
287 }
288 }
289
290 func TestCheckedExprToAstMissingInfo(t *testing.T) {
291 stdEnv, err := NewEnv()
292 if err != nil {
293 t.Fatalf("NewEnv() failed: %v", err)
294 }
295 in := "10"
296 ast, iss := stdEnv.Parse(in)
297 if iss.Err() != nil {
298 t.Fatalf("stdEnv.Compile(%q) failed: %v", in, iss.Err())
299 }
300 if ast.ResultType() != decls.Dyn {
301 t.Fatalf("ast.ResultType() got %v, wanted 'dyn'", ast.ResultType())
302 }
303 expr, err := AstToParsedExpr(ast)
304 if err != nil {
305 t.Fatalf("AstToParsedExpr(ast) failed: %v", err)
306 }
307 checkedExpr := &exprpb.CheckedExpr{
308 TypeMap: map[int64]*exprpb.Type{expr.GetExpr().GetId(): decls.Int},
309 Expr: expr.GetExpr(),
310 }
311 ast2 := CheckedExprToAst(checkedExpr)
312 if !ast2.IsChecked() {
313 t.Fatal("CheckedExprToAst() did not produce a 'checked' ast")
314 }
315 if ast2.ResultType() != decls.Int {
316 t.Fatalf("ast2.ResultType() got %v, wanted 'int'", ast.ResultType())
317 }
318 }