Debian Codegraph @

conformance/conformance_test.go

raw
1 package conformance_test
2
3 import (
4 "errors"
5 "flag"
6 "fmt"
7 "log"
8 "os"
9 "strings"
10 "testing"
11
12 "github.com/bazelbuild/rules_go/go/runfiles"
13
14 "github.com/google/cel-go/cel"
15 "github.com/google/cel-go/common"
16 "github.com/google/cel-go/common/ast"
17 "github.com/google/cel-go/common/types"
18 "github.com/google/cel-go/common/types/ref"
19 "github.com/google/cel-go/ext"
20 "github.com/google/go-cmp/cmp"
21
22 "google.golang.org/protobuf/encoding/prototext"
23 "google.golang.org/protobuf/proto"
24 "google.golang.org/protobuf/testing/protocmp"
25
26 valuepb "cel.dev/expr"
27 test2pb "cel.dev/expr/conformance/proto2"
28 test3pb "cel.dev/expr/conformance/proto3"
29 testpb "cel.dev/expr/conformance/test"
30 )
31
32 type testsFlag []string
33
34 func (t *testsFlag) String() string {
35 return strings.Join(([]string)(*t), ",")
36 }
37
38 func (t *testsFlag) Set(v string) error {
39 *t = strings.Split(v, ",")
40 for i, v := range *t {
41 (*t)[i] = strings.TrimSpace(v)
42 }
43 return nil
44 }
45
46 func (t *testsFlag) Get() any {
47 return ([]string)(*t)
48 }
49
50 type skipTestsFlag []string
51
52 func (t *skipTestsFlag) String() string {
53 return strings.Join(([]string)(*t), ",")
54 }
55
56 func (t *skipTestsFlag) Set(v string) error {
57 *t = strings.Split(v, ",")
58 for i, v := range *t {
59 (*t)[i] = strings.TrimSpace(v)
60 }
61 return nil
62 }
63
64 func (t *skipTestsFlag) Get() any {
65 return ([]string)(*t)
66 }
67
68 var (
69 dashboard bool
70 tests testsFlag
71 skipTests skipTestsFlag
72
73 envWithMacros *cel.Env
74 envNoMacros *cel.Env
75 )
76
77 func init() {
78 flag.BoolVar(&dashboard, "dashboard", false, "Dashboard.")
79 flag.Var(&tests, "tests", "Paths to run, separate by a comma.")
80 flag.Var(&skipTests, "skip_tests", "Tests to skip, separate by a comma.")
81
82 stdOpts := []cel.EnvOption{
83 cel.StdLib(),
84 cel.ClearMacros(),
85 cel.OptionalTypes(),
86 cel.EagerlyValidateDeclarations(true),
87 cel.EnableErrorOnBadPresenceTest(true),
88 cel.Types(&test2pb.TestAllTypes{}, &test2pb.Proto2ExtensionScopedMessage{}, &test3pb.TestAllTypes{}),
89 ext.Bindings(),
90 ext.Encoders(),
91 ext.Math(),
92 ext.Protos(),
93 ext.Strings(),
94 ext.TwoVarComprehensions(),
95 cel.Lib(celBlockLib{}),
96 cel.EnableIdentifierEscapeSyntax(),
97 }
98
99 var err error
100 envNoMacros, err = cel.NewCustomEnv(stdOpts...)
101 if err != nil {
102 log.Fatalf("cel.NewCustomEnv() = %v", err)
103 }
104 envWithMacros, err = envNoMacros.Extend(cel.Macros(cel.StandardMacros...))
105 if err != nil {
106 log.Fatalf("cel.NewCustomEnv() = %v", err)
107 }
108 }
109
110 func TestMain(m *testing.M) {
111 flag.Parse()
112 code := m.Run()
113 if dashboard {
114 code = 0
115 }
116 os.Exit(code)
117 }
118
119 func shouldSkipTest(s string) bool {
120 for _, t := range skipTests {
121 if strings.HasPrefix(s, t) {
122 n := s[len(t):]
123 if n == "" || strings.HasPrefix(n, "/") {
124 return true
125 }
126 }
127 }
128 return false
129 }
130
131 func refValueToExprValue(res ref.Val) (*valuepb.ExprValue, error) {
132 if types.IsUnknown(res) {
133 return &valuepb.ExprValue{
134 Kind: &valuepb.ExprValue_Unknown{
135 Unknown: &valuepb.UnknownSet{
136 Exprs: res.Value().([]int64),
137 },
138 }}, nil
139 }
140 v, err := cel.ValueAsProto(res)
141 if err != nil {
142 return nil, err
143 }
144 return &valuepb.ExprValue{
145 Kind: &valuepb.ExprValue_Value{Value: v}}, nil
146 }
147
148 func exprValueToRefValue(adapter types.Adapter, ev *valuepb.ExprValue) (ref.Val, error) {
149 switch ev.Kind.(type) {
150 case *valuepb.ExprValue_Value:
151 return cel.ProtoAsValue(adapter, ev.GetValue())
152 case *valuepb.ExprValue_Error:
153 // An error ExprValue is a repeated set of statuspb.Status
154 // messages, with no convention for the status details.
155 // To convert this to a types.Err, we need to convert
156 // these Status messages to a single string, and be
157 // able to decompose that string on output so we can
158 // round-trip arbitrary ExprValue messages.
159 // TODO(jimlarson) make a convention for this.
160 return types.NewErr("XXX add details later"), nil
161 case *valuepb.ExprValue_Unknown:
162 var unk *types.Unknown
163 for _, id := range ev.GetUnknown().GetExprs() {
164 if unk == nil {
165 unk = types.NewUnknown(id, nil)
166 }
167 unk = types.MergeUnknowns(types.NewUnknown(id, nil), unk)
168 }
169 return unk, nil
170 }
171 return nil, errors.New("unknown ExprValue kind")
172 }
173
174 func diffType(want proto.Message, t *cel.Type) (string, error) {
175 got, err := types.TypeToProto(t)
176 if err != nil {
177 return "", err
178 }
179 return cmp.Diff(want, got, protocmp.Transform()), nil
180
181 }
182
183 func diffValue(want *valuepb.Value, got *valuepb.ExprValue) string {
184 return cmp.Diff(
185 &valuepb.ExprValue{Kind: &valuepb.ExprValue_Value{Value: want}},
186 got,
187 protocmp.Transform(),
188 protocmp.SortRepeatedFields(&valuepb.MapValue{}, "entries"))
189 }
190
191 func conformanceTest(t *testing.T, name string, pb *testpb.SimpleTest) {
192 if shouldSkipTest(name) {
193 t.SkipNow()
194 return
195 }
196 var env *cel.Env
197 if pb.GetDisableMacros() {
198 env = envNoMacros
199 } else {
200 env = envWithMacros
201 }
202 src := common.NewStringSource(pb.GetExpr(), pb.GetName())
203 ast, iss := env.ParseSource(src)
204 if err := iss.Err(); err != nil {
205 t.Fatal(err)
206 }
207 var opts []cel.EnvOption
208 if pb.GetContainer() != "" {
209 opts = append(opts, cel.Container(pb.GetContainer()))
210 }
211 for _, d := range pb.GetTypeEnv() {
212 opt, err := cel.ProtoAsDeclaration(d)
213 if err != nil {
214 t.Fatal(err)
215 }
216 opts = append(opts, opt)
217 }
218 var err error
219 env, err = env.Extend(opts...)
220 if err != nil {
221 t.Fatal(err)
222 }
223 if !pb.GetDisableCheck() {
224 ast, iss = env.Check(ast)
225 if err := iss.Err(); err != nil {
226 t.Fatal(err)
227 }
228 }
229 if pb.GetCheckOnly() {
230 m, ok := pb.GetResultMatcher().(*testpb.SimpleTest_TypedResult)
231 if !ok {
232 t.Fatalf("unexpected matcher kind for check only test: %T", pb.GetResultMatcher())
233 }
234 if diff, err := diffType(m.TypedResult.DeducedType, ast.OutputType()); err != nil || diff != "" {
235 t.Errorf("env.Check() output type err: %v (-want +got):\n%s", err, diff)
236 }
237 return
238 }
239 program, err := env.Program(ast)
240 if err != nil {
241 t.Fatal(err)
242 }
243 act := make(map[string]any, len(pb.GetBindings()))
244 for k, v := range pb.GetBindings() {
245 act[k], err = exprValueToRefValue(env.CELTypeAdapter(), v)
246 if err != nil {
247 t.Fatal(err)
248 }
249 }
250 ret, _, err := program.Eval(act)
251 switch m := pb.GetResultMatcher().(type) {
252 case *testpb.SimpleTest_Value:
253 if err != nil {
254 t.Fatalf("program.Eval(): got %v, want nil", err)
255 }
256 val, err := refValueToExprValue(ret)
257 if err != nil {
258 t.Fatal(err)
259 }
260 if diff := diffValue(m.Value, val); diff != "" {
261 t.Errorf("program.Eval() diff (-want +got):\n%s", diff)
262 }
263 case *testpb.SimpleTest_TypedResult:
264 if err != nil {
265 t.Fatalf("program.Eval(): got %v, want nil", err)
266 }
267 val, err := refValueToExprValue(ret)
268 if err != nil {
269 t.Fatal(err)
270 }
271 if diff := diffValue(m.TypedResult.Result, val); diff != "" {
272 t.Errorf("program.Eval() diff (-want +got):\n%s", diff)
273 }
274 if diff, err := diffType(m.TypedResult.DeducedType, ast.OutputType()); err != nil || diff != "" {
275 t.Errorf("env.Check() output type err: %v (-want +got):\n%s", err, diff)
276 }
277 case *testpb.SimpleTest_EvalError:
278 if err == nil && types.IsError(ret) {
279 err = ret.(*types.Err).Unwrap()
280 }
281 if err == nil {
282 t.Errorf("program.Eval(): got nil, want %v", m.EvalError)
283 }
284 default:
285 t.Errorf("unexpected matcher kind: %T", pb.GetResultMatcher())
286 }
287 }
288
289 func TestConformance(t *testing.T) {
290 var files []*testpb.SimpleTestFile
291 for _, path := range tests {
292 path = strings.TrimPrefix(path, "external/")
293 f, err := runfiles.RlocationFrom(path, "com_google_cel_spec")
294 if err != nil {
295 log.Fatalf("failed to find runfile %q: %v", path, err)
296 }
297 b, err := os.ReadFile(f)
298 if err != nil {
299 log.Fatalf("failed to read file %q: %v", f, err)
300 }
301 file := &testpb.SimpleTestFile{}
302 err = prototext.Unmarshal(b, file)
303 if err != nil {
304 log.Fatalf("failed to parse file %q: %v", path, err)
305 }
306 files = append(files, file)
307 }
308 for _, file := range files {
309 for _, section := range file.GetSection() {
310 for _, test := range section.GetTest() {
311 name := fmt.Sprintf("%s/%s/%s", file.GetName(), section.GetName(), test.GetName())
312 if test.GetResultMatcher() == nil {
313 test.ResultMatcher = &testpb.SimpleTest_Value{
314 Value: &valuepb.Value{
315 Kind: &valuepb.Value_BoolValue{
316 BoolValue: true,
317 },
318 },
319 }
320 }
321 t.Run(name, func(t *testing.T) {
322 conformanceTest(t, name, test)
323 })
324 }
325 }
326 }
327 }
328
329 type celBlockLib struct{}
330
331 func (celBlockLib) LibraryName() string {
332 return "cel.lib.ext.cel.block.conformance"
333 }
334
335 func (celBlockLib) CompileOptions() []cel.EnvOption {
336 // Simulate indexed arguments which would normally have strong types associated
337 // with the values as part of a static optimization pass
338 maxIndices := 30
339 indexOpts := make([]cel.EnvOption, maxIndices)
340 for i := 0; i < maxIndices; i++ {
341 indexOpts[i] = cel.Variable(fmt.Sprintf("@index%d", i), cel.DynType)
342 }
343 return append([]cel.EnvOption{
344 cel.Macros(
345 // cel.block([args], expr)
346 cel.ReceiverMacro("block", 2, celBlock),
347 // cel.index(int)
348 cel.ReceiverMacro("index", 1, celIndex),
349 // cel.iterVar(int, int)
350 cel.ReceiverMacro("iterVar", 2, celCompreVar("cel.iterVar", "@it")),
351 // cel.accuVar(int, int)
352 cel.ReceiverMacro("accuVar", 2, celCompreVar("cel.accuVar", "@ac")),
353 ),
354 }, indexOpts...)
355 }
356
357 func (celBlockLib) ProgramOptions() []cel.ProgramOption {
358 return []cel.ProgramOption{}
359 }
360
361 func celBlock(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) {
362 if !isCELNamespace(target) {
363 return nil, nil
364 }
365 bindings := args[0]
366 if bindings.Kind() != ast.ListKind {
367 return bindings, mef.NewError(bindings.ID(), "cel.block requires the first arg to be a list literal")
368 }
369 return mef.NewCall("cel.@block", args...), nil
370 }
371
372 func celIndex(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) {
373 if !isCELNamespace(target) {
374 return nil, nil
375 }
376 index := args[0]
377 if !isNonNegativeInt(index) {
378 return index, mef.NewError(index.ID(), "cel.index requires a single non-negative int constant arg")
379 }
380 indexVal := index.AsLiteral().(types.Int)
381 return mef.NewIdent(fmt.Sprintf("@index%d", indexVal)), nil
382 }
383
384 func celCompreVar(funcName, varPrefix string) cel.MacroFactory {
385 return func(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) {
386 if !isCELNamespace(target) {
387 return nil, nil
388 }
389 depth := args[0]
390 if !isNonNegativeInt(depth) {
391 return depth, mef.NewError(depth.ID(), fmt.Sprintf("%s requires two non-negative int constant args", funcName))
392 }
393 unique := args[1]
394 if !isNonNegativeInt(unique) {
395 return unique, mef.NewError(unique.ID(), fmt.Sprintf("%s requires two non-negative int constant args", funcName))
396 }
397 depthVal := depth.AsLiteral().(types.Int)
398 uniqueVal := unique.AsLiteral().(types.Int)
399 return mef.NewIdent(fmt.Sprintf("%s:%d:%d", varPrefix, depthVal, uniqueVal)), nil
400 }
401 }
402
403 func isCELNamespace(target ast.Expr) bool {
404 return target.Kind() == ast.IdentKind && target.AsIdent() == "cel"
405 }
406
407 func isNonNegativeInt(expr ast.Expr) bool {
408 if expr.Kind() != ast.LiteralKind {
409 return false
410 }
411 val := expr.AsLiteral()
412 return val.Type() == cel.IntType && val.(types.Int) >= 0
413 }