Debian Codegraph @

tools/celtest/test_runner.go

raw symbols SCIP
1 // Copyright 2025 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 // https://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 celtest provides functions for testing CEL policies and expressions.
16 package celtest
17
18 import (
19 "flag"
20 "fmt"
21 "os"
22 "path/filepath"
23 "reflect"
24 "slices"
25 "strings"
26 "testing"
27
28 "github.com/google/cel-go/cel"
29 "github.com/google/cel-go/common/ast"
30 "github.com/google/cel-go/common/operators"
31 "github.com/google/cel-go/common/types"
32 "github.com/google/cel-go/common/types/ref"
33 "github.com/google/cel-go/interpreter"
34 "github.com/google/cel-go/test"
35 "github.com/google/cel-go/tools/compiler"
36 "github.com/google/go-cmp/cmp"
37
38 "google.golang.org/protobuf/encoding/prototext"
39 "google.golang.org/protobuf/proto"
40 "google.golang.org/protobuf/reflect/protodesc"
41 "google.golang.org/protobuf/reflect/protoregistry"
42 "google.golang.org/protobuf/testing/protocmp"
43
44 "go.yaml.in/yaml/v3"
45
46 celpb "cel.dev/expr"
47 conformancepb "cel.dev/expr/conformance/test"
48 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
49 descpb "google.golang.org/protobuf/types/descriptorpb"
50 dynamicpb "google.golang.org/protobuf/types/dynamicpb"
51 )
52
53 var (
54 celExpression string
55 testSuitePath string
56 fileDescriptorSetPath string
57 configPath string
58 baseConfigPath string
59 enableCoverage bool
60 )
61
62 func init() {
63 flag.StringVar(&testSuitePath, "test_suite_path", "", "path to a test suite")
64 flag.StringVar(&fileDescriptorSetPath, "file_descriptor_set", "", "path to a file descriptor set")
65 flag.StringVar(&configPath, "config_path", "", "path to a config file")
66 flag.StringVar(&baseConfigPath, "base_config_path", "", "path to a base config file")
67 flag.StringVar(&celExpression, "cel_expr", "", "CEL expression to test")
68 flag.BoolVar(&enableCoverage, "enable_coverage", false, "Enable coverage calculation and reporting.")
69 }
70
71 func updateRunfilesPathForFlags(testResourcesDir string) error {
72 if testResourcesDir == "" {
73 return nil
74 }
75 paths := make([]*string, 0, 5)
76 if compiler.InferFileFormat(testSuitePath) != compiler.Unspecified {
77 paths = append(paths, &testSuitePath)
78 }
79 if compiler.InferFileFormat(fileDescriptorSetPath) != compiler.Unspecified {
80 paths = append(paths, &fileDescriptorSetPath)
81 }
82 if compiler.InferFileFormat(configPath) != compiler.Unspecified {
83 paths = append(paths, &configPath)
84 }
85 if compiler.InferFileFormat(baseConfigPath) != compiler.Unspecified {
86 paths = append(paths, &baseConfigPath)
87 }
88 if compiler.InferFileFormat(celExpression) != compiler.Unspecified {
89 paths = append(paths, &celExpression)
90 }
91 return UpdateTestResourcesPaths(testResourcesDir, paths)
92 }
93
94 // UpdateTestResourcesPaths updates the list of paths with their absolute paths as per their location
95 // in the testResourcesDir directory. This will allow the executable targets to locate and access the
96 // data dependencies needed to trigger the tests.
97 // For example: In case of Bazel, this method can be used to update the file paths with the corresponding
98 // location in the runfiles directory tree:
99 //
100 // UpdateTestResourcesPaths(os.Getenv("RUNFILES_DIR"), <file_paths_list>)
101 func UpdateTestResourcesPaths(testResourcesDir string, paths []*string) error {
102 if testResourcesDir == "" {
103 return nil
104 }
105 err := filepath.Walk(testResourcesDir, func(p string, info os.FileInfo, err error) error {
106 if err != nil {
107 return err
108 }
109 if info.IsDir() {
110 return nil
111 }
112 relPath, err := filepath.Rel(testResourcesDir, p)
113 if err != nil {
114 return err
115 }
116 for _, path := range paths {
117 if strings.Contains(relPath, *path) {
118 *path = p
119 }
120 }
121 return nil
122 })
123 return err
124 }
125
126 // TestRunnerOption is used to configure the following attributes of the Test Runner:
127 // - set the Compiler
128 // - add Input Expressions
129 // - set the test suite file path
130 // - set the test suite parser based on the file format: YAML or Textproto
131 type TestRunnerOption func(*TestRunner) (*TestRunner, error)
132
133 // TriggerTests triggers tests for a CEL policy, expression or checked expression
134 // with the provided set of options. The options can be used to:
135 // - configure the Compiler used for parsing and compiling the expression
136 // - configure the Test Runner used for parsing and executing the tests
137 func TriggerTests(t *testing.T, testRunnerOpts ...TestRunnerOption) {
138 tr, err := NewTestRunner(testRunnerOpts...)
139 if err != nil {
140 t.Fatalf("error creating test runner: %v", err)
141 }
142 programs, err := tr.Programs(t, tr.testProgramOptions...)
143 if err != nil {
144 t.Fatalf("error creating programs: %v", err)
145 }
146 if len(programs) == 0 {
147 t.Fatalf("no programs created for the provided expressions")
148 }
149 tests, err := tr.Tests(t)
150 if err != nil {
151 t.Fatalf("error creating tests: %v", err)
152 }
153 if len(tests) == 0 {
154 t.Fatalf("no tests found")
155 }
156 for _, test := range tests {
157 t.Run(test.name, func(t *testing.T) {
158 err := tr.ExecuteTest(t, programs, test)
159 if err != nil {
160 t.Fatalf("error executing test: %v", err)
161 }
162 })
163 }
164 if tr.EnableCoverage {
165 reportCoverage(t, programs)
166 }
167 }
168
169 // TestRunnerOptionsFromFlags returns a TestRunnerOption which configures the following attributes
170 // of the test runner using the parsed flags and the optionally provided test runner and test compiler options:
171 // - Test compiler - The `file_descriptor_set`, `base_config_path` and `config_path` flags are used
172 // to set up the test compiler. The optionally provided test compiler options are also used to
173 // augment the test compiler.
174 // - Test suite parser - The `test_suite_path` flag is used to set up the test suite parser.
175 // - File descriptor set path - The value of the `file_descriptor_set` flag is set as the
176 // File Descriptor Set Path of the test runner.
177 // - Test expression - The `cel_expr` flag is used to populate the test expressions which need to be
178 // evaluated by the test runner.
179 // - Enable coverage - The `enable_coverage` flag is used to enable coverage calculation and reporting.
180 func TestRunnerOptionsFromFlags(testResourcesDir string, testRunnerOpts []TestRunnerOption, testCompilerOpts ...any) TestRunnerOption {
181 if !flag.Parsed() {
182 flag.Parse()
183 }
184 if err := updateRunfilesPathForFlags(testResourcesDir); err != nil {
185 return nil
186 }
187 return func(tr *TestRunner) (*TestRunner, error) {
188 opts := []TestRunnerOption{
189 testRunnerCompilerFromFlags(testCompilerOpts...),
190 DefaultTestSuiteParser(testSuitePath),
191 AddFileDescriptorSet(fileDescriptorSetPath),
192 TestExpression(celExpression),
193 }
194 if enableCoverage {
195 opts = append(opts, EnableCoverage())
196 }
197 opts = append(opts, testRunnerOpts...)
198 var err error
199 for _, opt := range opts {
200 tr, err = opt(tr)
201 if err != nil {
202 return nil, err
203 }
204 }
205 return tr, nil
206 }
207 }
208
209 func testRunnerCompilerFromFlags(testCompilerOpts ...any) TestRunnerOption {
210 var opts []any
211 if fileDescriptorSetPath != "" {
212 opts = append(opts, compiler.TypeDescriptorSetFile(fileDescriptorSetPath))
213 }
214 if baseConfigPath != "" {
215 opts = append(opts, compiler.EnvironmentFile(baseConfigPath))
216 }
217 if configPath != "" {
218 opts = append(opts, compiler.EnvironmentFile(configPath))
219 }
220 if enableCoverage {
221 opts = append(opts, cel.EnableMacroCallTracking())
222 }
223 opts = append(opts, testCompilerOpts...)
224 return TestCompiler(opts...)
225 }
226
227 // TestSuiteParser is an interface for parsing a test suite:
228 // - ParseTextproto: Returns a cel.spec.expr.conformance.test.TestSuite message.
229 // - ParseYAML: Returns a test.Suite object.
230 // In case the test suite is serialized in a Textproto/YAML file, the path of the file is passed as
231 // an argument to the parse method.
232 type TestSuiteParser interface {
233 ParseTextproto(string) (*conformancepb.TestSuite, error)
234 ParseYAML(string) (*test.Suite, error)
235 }
236
237 type tsParser struct {
238 TestSuiteParser
239 }
240
241 // ParseTextproto parses a test suite file in Textproto format.
242 func (p *tsParser) ParseTextproto(path string) (*conformancepb.TestSuite, error) {
243 if path == "" {
244 return nil, nil
245 }
246 if fileFormat := compiler.InferFileFormat(path); fileFormat != compiler.TextProto {
247 return nil, fmt.Errorf("invalid file extension wanted: .textproto: found %v", fileFormat)
248 }
249 testSuite := &conformancepb.TestSuite{}
250 data, err := os.ReadFile(path)
251 if err != nil {
252 return nil, fmt.Errorf("os.ReadFile(%q) failed: %v", path, err)
253 }
254 err = prototext.Unmarshal(data, testSuite)
255 return testSuite, err
256 }
257
258 // ParseYAML parses a test suite file in YAML format.
259 func (p *tsParser) ParseYAML(path string) (*test.Suite, error) {
260 if path == "" {
261 return nil, nil
262 }
263 if fileFormat := compiler.InferFileFormat(path); fileFormat != compiler.TextYAML {
264 return nil, fmt.Errorf("invalid file extension wanted: .yaml: found %v", fileFormat)
265 }
266 testSuiteBytes, err := os.ReadFile(path)
267 if err != nil {
268 return nil, fmt.Errorf("os.ReadFile(%q) failed: %v", path, err)
269 }
270 testSuite := &test.Suite{}
271 err = yaml.Unmarshal(testSuiteBytes, testSuite)
272 return testSuite, err
273 }
274
275 // DefaultTestSuiteParser returns a TestRunnerOption which configures the test runner with
276 // the default test suite parser.
277 func DefaultTestSuiteParser(path string) TestRunnerOption {
278 return func(tr *TestRunner) (*TestRunner, error) {
279 if path == "" {
280 return tr, nil
281 }
282 tr.TestSuiteFilePath = path
283 tr.testSuiteParser = &tsParser{}
284 return tr, nil
285 }
286 }
287
288 // TestSuiteParserOption returns a TestRunnerOption which configures the test runner with
289 // a custom test suite parser.
290 func TestSuiteParserOption(p TestSuiteParser) TestRunnerOption {
291 return func(tr *TestRunner) (*TestRunner, error) {
292 tr.testSuiteParser = p
293 return tr, nil
294 }
295 }
296
297 // TestRunner provides a structure to hold the different components required to execute tests for
298 // a list of Input Expressions. The TestRunner can be configured with the following options:
299 // - Compiler: The compiler used for parsing and compiling the input expressions.
300 // - Input Expressions: The list of input expressions to be tested.
301 // - Test Suite File Path: The path to the test suite file.
302 // - File Descriptor Set Path: The path to the file descriptor set file.
303 // - test Suite Parser: A parser for a test suite file serialized in Textproto/YAML format.
304 // - test Program Options: A list of options to be used when creating the CEL programs.
305 // - EnableCoverage: A boolean to enable coverage calculation.
306 //
307 // The TestRunner provides the following methods:
308 // - Programs: Creates a list of CEL programs from the input expressions.
309 // - Tests: Creates a list of tests from the test suite file.
310 // - ExecuteTest: Executes a single
311 type TestRunner struct {
312 compiler.Compiler
313 Expressions []compiler.InputExpression
314 TestSuiteFilePath string
315 FileDescriptorSetPath string
316 testSuiteParser TestSuiteParser
317 testProgramOptions []cel.ProgramOption
318 EnableCoverage bool
319 }
320
321 // Test represents a single test case to be executed. It encompasses the following:
322 // - name: The name of the test case.
323 // - input: The input to be used for evaluating the CEL expression.
324 // - resultMatcher: A function that takes in the result of evaluating the CEL expression and
325 // returns a TestResult.
326 type Test struct {
327 name string
328 input interpreter.PartialActivation
329 resultMatcher func(ref.Val, error) TestResult
330 }
331
332 // NewTest creates a new Test with the provided name, input and result matcher.
333 func NewTest(name string, input interpreter.PartialActivation, resultMatcher func(ref.Val, error) TestResult) *Test {
334 return &Test{
335 name: name,
336 input: input,
337 resultMatcher: resultMatcher,
338 }
339 }
340
341 // TestResult represents the result of a test case execution. It contains the validation result
342 // along with the expected result and any errors encountered during the execution.
343 // - Success: Whether the result matcher condition validating the test case was satisfied.
344 // - Wanted: The expected result of the test case.
345 // - Error: Any error encountered during the execution.
346 type TestResult struct {
347 Success bool
348 Wanted string
349 Error error
350 }
351
352 // NewTestRunner creates a Test Runner with the provided options.
353 // The options can be used to:
354 // - configure the Compiler used for parsing and compiling the input expressions
355 // - configure the Test Runner used for parsing and executing the tests
356 func NewTestRunner(opts ...TestRunnerOption) (*TestRunner, error) {
357 tr := &TestRunner{}
358 var err error
359 for _, opt := range opts {
360 tr, err = opt(tr)
361 if err != nil {
362 return nil, err
363 }
364 }
365 return tr, nil
366 }
367
368 // TestExpression returns a TestRunnerOption which configures a policy file, expression file, or raw expression
369 // for testing
370 func TestExpression(value string) TestRunnerOption {
371 return func(tr *TestRunner) (*TestRunner, error) {
372 if value != "" {
373 tr.Expressions = append(tr.Expressions,
374 &compiler.CompiledExpression{Path: value},
375 &compiler.FileExpression{Path: value},
376 &compiler.RawExpression{Value: value},
377 )
378 }
379 return tr, nil
380 }
381 }
382
383 // TestCompiler returns a TestRunnerOption which configures the test runner with
384 // a compiler created using the set of compiler options.
385 func TestCompiler(compileOpts ...any) TestRunnerOption {
386 return func(tr *TestRunner) (*TestRunner, error) {
387 c, err := compiler.NewCompiler(compileOpts...)
388 if err != nil {
389 return nil, err
390 }
391 tr.Compiler = c
392 return tr, nil
393 }
394 }
395
396 // CustomTestCompiler returns a TestRunnerOption which configures the test runner with
397 // a custom compiler.
398 func CustomTestCompiler(c compiler.Compiler) TestRunnerOption {
399 return func(tr *TestRunner) (*TestRunner, error) {
400 tr.Compiler = c
401 return tr, nil
402 }
403 }
404
405 // AddFileDescriptorSet creates a Test Runner Option which adds a file descriptor set to the test
406 // runner. The file descriptor set is used to register proto messages in the global proto registry.
407 func AddFileDescriptorSet(path string) TestRunnerOption {
408 return func(tr *TestRunner) (*TestRunner, error) {
409 if path != "" {
410 tr.FileDescriptorSetPath = path
411 }
412 return tr, nil
413 }
414 }
415
416 func registerMessages(path string) error {
417 if path == "" {
418 return nil
419 }
420 fds, err := fileDescriptorSet(path)
421 if err != nil {
422 return err
423 }
424 for _, file := range fds.GetFile() {
425 reflectFD, err := protodesc.NewFile(file, protoregistry.GlobalFiles)
426 if err != nil {
427 return fmt.Errorf("protodesc.NewFile(%q) failed: %v", file.GetName(), err)
428 }
429 if _, err := protoregistry.GlobalFiles.FindFileByPath(reflectFD.Path()); err == nil {
430 continue
431 }
432 err = protoregistry.GlobalFiles.RegisterFile(reflectFD)
433 if err != nil {
434 return fmt.Errorf("protoregistry.GlobalFiles.RegisterFile() failed: %v", err)
435 }
436 for i := 0; i < reflectFD.Messages().Len(); i++ {
437 msg := reflectFD.Messages().Get(i)
438 msgType := dynamicpb.NewMessageType(msg)
439 err = protoregistry.GlobalTypes.RegisterMessage(msgType)
440 if err != nil && !strings.Contains(err.Error(), "already registered") {
441 return fmt.Errorf("protoregistry.GlobalTypes.RegisterMessage(%q) failed: %v", msgType, err)
442 }
443 }
444 }
445 return nil
446 }
447
448 func fileDescriptorSet(path string) (*descpb.FileDescriptorSet, error) {
449 bytes, err := os.ReadFile(path)
450 if err != nil {
451 return nil, fmt.Errorf("failed to read file descriptor set file %q: %v", fileDescriptorSetPath, err)
452 }
453 fds := &descpb.FileDescriptorSet{}
454 if err := proto.Unmarshal(bytes, fds); err != nil {
455 return nil, fmt.Errorf("failed to unmarshal file descriptor set file %q: %v", fileDescriptorSetPath, err)
456 }
457 return fds, nil
458 }
459
460 // PartialEvalProgramOption returns a TestRunnerOption which enables partial evaluation for the CEL
461 // program by setting the OptPartialEval eval option.
462 //
463 // Note: The test setup uses env.PartialVars() for creating PartialActivation.
464 func PartialEvalProgramOption() TestRunnerOption {
465 return func(tr *TestRunner) (*TestRunner, error) {
466 tr.testProgramOptions = append(tr.testProgramOptions, cel.EvalOptions(cel.OptPartialEval))
467 return tr, nil
468 }
469 }
470
471 // EnableCoverage returns a TestRunnerOption which enables coverage calculation for the test run.
472 func EnableCoverage() TestRunnerOption {
473 return func(tr *TestRunner) (*TestRunner, error) {
474 tr.EnableCoverage = true
475 tr.testProgramOptions = append(tr.testProgramOptions, cel.EvalOptions(cel.OptTrackState))
476 return tr, nil
477 }
478 }
479
480 // Program represents the result of creating CEL programs for the configured expressions in the
481 // test runner. It encompasses the following:
482 // - CELProgram - the evaluable CEL program
483 // - PolicyMetadata - the metadata map obtained while creating the CEL AST from the expression
484 // - Ast - the CEL AST created from the expression
485 // - CoverageStats - the coverage report map obtained from calculating the coverage if enabled.
486 type Program struct {
487 cel.Program
488 PolicyMetadata map[string]any
489 Ast *cel.Ast
490 CoverageStats map[int64]set
491 }
492
493 // set is a generic set implementation using a map where the keys are the elements of the set
494 // and the values are empty structs. This approach is memory-efficient because an empty struct
495 // occupies zero bytes. This will be used to store the values observed for each expression during
496 // coverage calculation.
497 type set map[ref.Val]struct{}
498
499 // Programs creates a list of CEL programs from the input expressions configured in the test runner
500 // using the provided program options.
501 func (tr *TestRunner) Programs(t *testing.T, opts ...cel.ProgramOption) ([]Program, error) {
502 t.Helper()
503 if tr.Compiler == nil {
504 return nil, fmt.Errorf("compiler is not set")
505 }
506 e, err := tr.CreateEnv()
507 if err != nil {
508 return nil, err
509 }
510 programs := make([]Program, 0, len(tr.Expressions))
511 for _, expr := range tr.Expressions {
512 ast, policyMetadata, err := expr.CreateAST(tr.Compiler)
513 if err != nil {
514 if strings.Contains(err.Error(), "invalid file extension") ||
515 strings.Contains(err.Error(), "invalid raw expression") {
516 continue
517 }
518 return nil, err
519 }
520 prg, err := e.Program(ast, opts...)
521 if err != nil {
522 return nil, err
523 }
524 programs = append(programs, Program{
525 Program: prg,
526 PolicyMetadata: policyMetadata,
527 Ast: ast,
528 })
529 }
530 return programs, nil
531 }
532
533 // Tests creates a list of tests from the test suite file and test suite parser configured in the
534 // test runner.
535 //
536 // Note: The test setup uses env.PartialVars() for creating PartialActivation.
537 func (tr *TestRunner) Tests(t *testing.T) ([]*Test, error) {
538 if tr.Compiler == nil {
539 return nil, fmt.Errorf("compiler is not set")
540 }
541 if tr.testSuiteParser == nil {
542 return nil, fmt.Errorf("test suite parser is not set")
543 }
544 if testSuite, err := tr.testSuiteParser.ParseYAML(tr.TestSuiteFilePath); err != nil &&
545 !strings.Contains(err.Error(), "invalid file extension") {
546 return nil, fmt.Errorf("tr.testSuiteParser.ParseYAML(%q) failed: %v", tr.TestSuiteFilePath, err)
547 } else if testSuite != nil {
548 return tr.createTestsFromYAML(t, testSuite)
549 }
550 err := registerMessages(tr.FileDescriptorSetPath)
551 if err != nil {
552 return nil, fmt.Errorf("registerMessages(%q) failed: %v", tr.FileDescriptorSetPath, err)
553 }
554 if testSuite, err := tr.testSuiteParser.ParseTextproto(tr.TestSuiteFilePath); err != nil &&
555 !strings.Contains(err.Error(), "invalid file extension") {
556 return nil, fmt.Errorf("tr.testSuiteParser.ParseTextproto(%q) failed: %v", tr.TestSuiteFilePath, err)
557 } else if testSuite != nil {
558 return tr.createTestsFromTextproto(t, testSuite)
559 }
560 return nil, nil
561 }
562
563 func (tr *TestRunner) createTestsFromTextproto(t *testing.T, testSuite *conformancepb.TestSuite) ([]*Test, error) {
564 var tests []*Test
565 for _, section := range testSuite.GetSections() {
566 sectionName := section.GetName()
567 for _, testCase := range section.GetTests() {
568 testName := fmt.Sprintf("%s/%s", sectionName, testCase.GetName())
569 testInput, err := tr.createTestInputFromPB(t, testCase)
570 if err != nil {
571 return nil, err
572 }
573 testResultMatcher, err := tr.createResultMatcherFromPB(t, testCase)
574 if err != nil {
575 return nil, err
576 }
577 tests = append(tests, NewTest(testName, testInput, testResultMatcher))
578 }
579 }
580 return tests, nil
581 }
582
583 func (tr *TestRunner) createTestInputFromPB(t *testing.T, testCase *conformancepb.TestCase) (interpreter.PartialActivation, error) {
584 t.Helper()
585 input := map[string]any{}
586 e, err := tr.CreateEnv()
587 if err != nil {
588 return nil, err
589 }
590 var activation interpreter.Activation
591 if testCase.GetInputContext() != nil {
592 if len(testCase.GetInput()) != 0 {
593 return nil, fmt.Errorf("only one of input and input_context can be provided at a time")
594 }
595 switch testInput := testCase.GetInputContext().GetInputContextKind().(type) {
596 case *conformancepb.InputContext_ContextExpr:
597 refVal, err := tr.eval(testInput.ContextExpr)
598 if err != nil {
599 return nil, fmt.Errorf("eval(%q) failed: %w", testInput.ContextExpr, err)
600 }
601 ctx, err := refVal.ConvertToNative(
602 reflect.TypeOf((*proto.Message)(nil)).Elem())
603 if err != nil {
604 return nil, fmt.Errorf("context variable is not a valid proto: %w", err)
605 }
606 activation, err = cel.ContextProtoVars(ctx.(proto.Message))
607 if err != nil {
608 return nil, fmt.Errorf("cel.ContextProtoVars() failed: %w", err)
609 }
610 case *conformancepb.InputContext_ContextMessage:
611 refVal := e.CELTypeAdapter().NativeToValue(testInput.ContextMessage)
612 ctx, err := refVal.ConvertToNative(reflect.TypeOf((*proto.Message)(nil)).Elem())
613 if err != nil {
614 return nil, fmt.Errorf("context variable is not a valid proto: %w", err)
615 }
616 activation, err = cel.ContextProtoVars(ctx.(proto.Message))
617 if err != nil {
618 return nil, fmt.Errorf("cel.ContextProtoVars() failed: %w", err)
619 }
620 }
621 return e.PartialVars(activation)
622 }
623 for k, v := range testCase.GetInput() {
624 switch v.GetKind().(type) {
625 case *conformancepb.InputValue_Value:
626 input[k], err = cel.ProtoAsValue(e.CELTypeAdapter(), v.GetValue())
627 if err != nil {
628 return nil, fmt.Errorf("cel.ProtoAsValue(%q) failed: %w", v, err)
629 }
630 case *conformancepb.InputValue_Expr:
631 input[k], err = tr.eval(v.GetExpr())
632 if err != nil {
633 return nil, fmt.Errorf("eval(%q) failed: %w", v.GetExpr(), err)
634 }
635 }
636 }
637 activation, err = interpreter.NewActivation(input)
638 if err != nil {
639 return nil, fmt.Errorf("interpreter.NewActivation(%q) failed: %w", input, err)
640 }
641 return e.PartialVars(activation)
642 }
643
644 func (tr *TestRunner) createResultMatcherFromPB(t *testing.T, testCase *conformancepb.TestCase) (func(ref.Val, error) TestResult, error) {
645 t.Helper()
646 if testCase.GetOutput() == nil {
647 return nil, fmt.Errorf("expected output is nil")
648 }
649 successResult := TestResult{Success: true}
650 e, err := tr.CreateEnv()
651 if err != nil {
652 return nil, err
653 }
654 switch testOutput := testCase.GetOutput().GetResultKind().(type) {
655 case *conformancepb.TestOutput_ResultValue:
656 return func(val ref.Val, err error) TestResult {
657 want := e.CELTypeAdapter().NativeToValue(testOutput.ResultValue)
658 if err != nil {
659 return TestResult{Success: false, Wanted: fmt.Sprintf("simple value %v", want), Error: err}
660 }
661 outputVal, err := refValueToExprValue(val)
662 if err != nil {
663 return TestResult{Success: false, Wanted: fmt.Sprintf("simple value %v", want), Error: fmt.Errorf("refValueToExprValue(%q) failed: %v", val, err)}
664 }
665 testResultVal, err := canonicalValueToV1Alpha1(testOutput.ResultValue)
666 if err != nil {
667 return TestResult{Success: false, Wanted: fmt.Sprintf("simple value %v", want), Error: fmt.Errorf("canonicalValueToV1Alpha1(%q) failed: %v", testOutput.ResultValue, err)}
668 }
669 testVal := &exprpb.ExprValue{
670 Kind: &exprpb.ExprValue_Value{Value: testResultVal}}
671
672 if diff := cmp.Diff(testVal, outputVal, protocmp.Transform(),
673 protocmp.SortRepeatedFields(&exprpb.MapValue{}, "entries")); diff != "" {
674 return TestResult{Success: false, Wanted: fmt.Sprintf("simple value %v", want), Error: fmt.Errorf("mismatched test output with diff (-want +got):\n%s", diff)}
675 }
676 return successResult
677 }, nil
678 case *conformancepb.TestOutput_ResultExpr:
679 return func(val ref.Val, err error) TestResult {
680 if err != nil {
681 return TestResult{Success: false, Error: err}
682 }
683 testOut, err := tr.eval(testOutput.ResultExpr)
684 if err != nil {
685 return TestResult{Success: false, Error: fmt.Errorf("eval(%q) failed: %v", testOutput.ResultExpr, err)}
686 }
687 if optOut, ok := val.(*types.Optional); ok {
688 if optOut.Equal(types.OptionalNone) == types.True {
689 if testOut.Equal(types.OptionalNone) != types.True {
690 return TestResult{Success: false, Wanted: fmt.Sprintf("optional value %v", testOut), Error: fmt.Errorf("policy eval got %v", val)}
691 }
692 } else if testOut.Equal(optOut.GetValue()) != types.True {
693 return TestResult{Success: false, Wanted: fmt.Sprintf("optional value %v", testOut), Error: fmt.Errorf("policy eval got %v", val)}
694 }
695 } else if val.Equal(testOut) != types.True {
696 return TestResult{Success: false, Wanted: fmt.Sprintf("optional value %v", testOut), Error: fmt.Errorf("policy eval got %v", val)}
697 }
698 return successResult
699 }, nil
700 case *conformancepb.TestOutput_EvalError:
701 return func(val ref.Val, err error) TestResult {
702 failureResult := TestResult{Success: false, Wanted: fmt.Sprintf("error %v", testOutput.EvalError)}
703 if err == nil {
704 return failureResult
705 }
706 // Compare the evaluated error with the expected error message only.
707 for _, want := range testOutput.EvalError.GetErrors() {
708 if strings.Contains(err.Error(), want.GetMessage()) {
709 return successResult
710 }
711 }
712 return failureResult
713 }, nil
714 case *conformancepb.TestOutput_Unknown:
715 // Validate that all expected unknown expression ids are returned by the evaluation result.
716 return func(out ref.Val, err error) TestResult {
717 expectedUnknownIDs := testOutput.Unknown.GetExprs()
718 if err == nil && types.IsUnknown(out) {
719 actualUnknownIDs := out.Value().(*types.Unknown).IDs()
720 return compareUnknownIDs(expectedUnknownIDs, actualUnknownIDs)
721 }
722 return TestResult{Success: false, Wanted: fmt.Sprintf("unknown value %v", expectedUnknownIDs), Error: err}
723 }, nil
724 }
725 return nil, nil
726 }
727
728 func compareUnknownIDs(expectedUnknownIDs, actualUnknownIDs []int64) TestResult {
729 sortOption := cmp.Transformer("Sort", func(in []int64) []int64 {
730 out := append([]int64{}, in...)
731 slices.Sort(out)
732 return out
733 })
734 if diff := cmp.Diff(expectedUnknownIDs, actualUnknownIDs, sortOption); diff != "" {
735 return TestResult{
736 Success: false,
737 Wanted: fmt.Sprintf("unknown value %v", expectedUnknownIDs),
738 Error: fmt.Errorf("mismatched test output with diff (-got +want):\n%s", diff)}
739 }
740 return TestResult{Success: true}
741 }
742
743 func refValueToExprValue(refVal ref.Val) (*exprpb.ExprValue, error) {
744 if types.IsUnknown(refVal) {
745 return &exprpb.ExprValue{
746 Kind: &exprpb.ExprValue_Unknown{
747 Unknown: &exprpb.UnknownSet{
748 Exprs: refVal.Value().([]int64),
749 },
750 }}, nil
751 }
752 v, err := cel.RefValueToValue(refVal)
753 if err != nil {
754 return nil, err
755 }
756 return &exprpb.ExprValue{
757 Kind: &exprpb.ExprValue_Value{Value: v}}, nil
758 }
759
760 func canonicalValueToV1Alpha1(val *celpb.Value) (*exprpb.Value, error) {
761 var v1val exprpb.Value
762 b, err := prototext.Marshal(val)
763 if err != nil {
764 return nil, err
765 }
766 if err := prototext.Unmarshal(b, &v1val); err != nil {
767 return nil, err
768 }
769 return &v1val, nil
770 }
771
772 func (tr *TestRunner) eval(expr string) (ref.Val, error) {
773 e, err := tr.CreateEnv()
774 if err != nil {
775 return nil, err
776 }
777 e, err = e.Extend(cel.OptionalTypes())
778 if err != nil {
779 return nil, fmt.Errorf("e.Extend() failed: %v", err)
780 }
781 ast, iss := e.Compile(expr)
782 if iss.Err() != nil {
783 return nil, fmt.Errorf("e.Compile(%q) failed: %v", expr, iss.Err())
784 }
785 prg, err := e.Program(ast)
786 if err != nil {
787 return nil, fmt.Errorf("e.Program(%q) failed: %v", expr, err)
788 }
789 out, _, err := prg.Eval(cel.NoVars())
790 if err != nil {
791 return nil, fmt.Errorf("prg.Eval(%q) failed: %v", expr, err)
792 }
793 return out, nil
794 }
795
796 func (tr *TestRunner) createTestsFromYAML(t *testing.T, testSuite *test.Suite) ([]*Test, error) {
797 var tests []*Test
798 for _, section := range testSuite.Sections {
799 for _, testCase := range section.Tests {
800 testName := fmt.Sprintf("%s/%s", section.Name, testCase.Name)
801 testInput, err := tr.createTestInput(t, testCase)
802 if err != nil {
803 return nil, err
804 }
805 testResultMatcher, err := tr.createResultMatcher(t, testCase.Output)
806 if err != nil {
807 return nil, err
808 }
809 tests = append(tests, NewTest(testName, testInput, testResultMatcher))
810 }
811 }
812 return tests, nil
813 }
814
815 func (tr *TestRunner) createTestInput(t *testing.T, testCase *test.Case) (interpreter.PartialActivation, error) {
816 t.Helper()
817 e, err := tr.CreateEnv()
818 if err != nil {
819 return nil, err
820 }
821 var activation interpreter.Activation
822 if testCase.InputContext != nil && testCase.InputContext.ContextExpr != "" {
823 if len(testCase.Input) != 0 {
824 return nil, fmt.Errorf("only one of input and input_context can be provided at a time")
825 }
826 contextExpr := testCase.InputContext.ContextExpr
827 out, err := tr.eval(contextExpr)
828 if err != nil {
829 return nil, fmt.Errorf("eval(%q) failed: %w", contextExpr, err)
830 }
831 ctx, err := out.ConvertToNative(reflect.TypeOf((*proto.Message)(nil)).Elem())
832 if err != nil {
833 return nil, fmt.Errorf("context variable is not a valid proto: %w", err)
834 }
835 activation, err = cel.ContextProtoVars(ctx.(proto.Message))
836 if err != nil {
837 return nil, fmt.Errorf("cel.ContextProtoVars() failed: %w", err)
838 }
839 return e.PartialVars(activation)
840 }
841 input := map[string]any{}
842 for k, v := range testCase.Input {
843 if v.Expr != "" {
844 val, err := tr.eval(v.Expr)
845 if err != nil {
846 return nil, fmt.Errorf("eval(%q) failed: %w", v.Expr, err)
847 }
848 input[k] = val
849 continue
850 }
851 input[k] = v.Value
852 }
853 activation, err = interpreter.NewActivation(input)
854 if err != nil {
855 return nil, fmt.Errorf("interpreter.NewActivation(%q) failed: %w", input, err)
856 }
857 return e.PartialVars(activation)
858 }
859
860 func (tr *TestRunner) createResultMatcher(t *testing.T, testOutput *test.Output) (func(ref.Val, error) TestResult, error) {
861 t.Helper()
862 e, err := tr.CreateEnv()
863 if err != nil {
864 return nil, err
865 }
866 successResult := TestResult{Success: true}
867 if testOutput.Value != nil {
868 want := e.CELTypeAdapter().NativeToValue(testOutput.Value)
869 return func(out ref.Val, err error) TestResult {
870 if err == nil {
871 if out.Equal(want) == types.True {
872 return successResult
873 }
874 if optOut, ok := out.(*types.Optional); ok {
875 if optOut.HasValue() && optOut.GetValue().Equal(want) == types.True {
876 return successResult
877 }
878 }
879 }
880 return TestResult{Success: false, Wanted: fmt.Sprintf("simple value %v", want), Error: err}
881 }, nil
882 }
883 if testOutput.Expr != "" {
884 want, err := tr.eval(testOutput.Expr)
885 if err != nil {
886 return nil, fmt.Errorf("eval(%q) failed: %w", testOutput.Expr, err)
887 }
888 return func(out ref.Val, err error) TestResult {
889 if err == nil {
890 if out.Equal(want) == types.True {
891 return successResult
892 }
893 if optOut, ok := out.(*types.Optional); ok {
894 if optOut.HasValue() && optOut.GetValue().Equal(want) == types.True {
895 return successResult
896 }
897 }
898 }
899 return TestResult{Success: false, Wanted: fmt.Sprintf("simple value %v", want), Error: err}
900 }, nil
901 }
902 if testOutput.ErrorSet != nil {
903 return func(out ref.Val, err error) TestResult {
904 failureResult := TestResult{Success: false, Wanted: fmt.Sprintf("error %v", testOutput.ErrorSet)}
905 if err == nil {
906 return failureResult
907 }
908 for _, want := range testOutput.ErrorSet {
909 if strings.Contains(err.Error(), want) {
910 return successResult
911 }
912 }
913 return failureResult
914 }, nil
915 }
916 if testOutput.UnknownSet != nil {
917 return func(out ref.Val, err error) TestResult {
918 if err == nil && types.IsUnknown(out) {
919 unknownIDs := out.Value().(*types.Unknown).IDs()
920 return compareUnknownIDs(testOutput.UnknownSet, unknownIDs)
921 }
922 return TestResult{Success: false, Wanted: fmt.Sprintf("unknown value %v", testOutput.UnknownSet), Error: err}
923 }, nil
924 }
925 return nil, nil
926 }
927
928 // ExecuteTest executes the test case against the provided list of programs and returns an error if
929 // the test fails.
930 // During the test execution, the intermediate values encountered during the evaluation of each
931 // program are collected and stored in the CoverageStats map of the TestRunner.
932 func (tr *TestRunner) ExecuteTest(t *testing.T, programs []Program, test *Test) error {
933 t.Helper()
934 if tr.Compiler == nil {
935 return fmt.Errorf("compiler is not set")
936 }
937 for i, pr := range programs {
938 if pr.Program == nil {
939 return fmt.Errorf("CEL program not set")
940 }
941 out, details, err := pr.Eval(test.input)
942 if testResult := test.resultMatcher(out, err); !testResult.Success {
943 return fmt.Errorf("test: %s \n wanted: %v \n failed: %v", test.name, testResult.Wanted, testResult.Error)
944 }
945 if tr.EnableCoverage {
946 collectCoverageStats(details, &pr)
947 programs[i] = pr
948 }
949 }
950 return nil
951 }
952
953 // collectCoverageStats collects the coverage stats from the EvalDetails and stores them in the
954 // CoverageStats map of the Program.
955 func collectCoverageStats(details *cel.EvalDetails, p *Program) {
956 if details == nil || details.State() == nil {
957 return
958 }
959 if p.CoverageStats == nil {
960 p.CoverageStats = make(map[int64]set)
961 }
962 state := details.State()
963 for _, id := range state.IDs() {
964 value, found := state.Value(id)
965 if !found {
966 continue
967 }
968 if _, ok := p.CoverageStats[id]; !ok {
969 p.CoverageStats[id] = make(set)
970 }
971 p.CoverageStats[id][value] = struct{}{}
972 }
973 // Propagate visitedness after collecting direct observations
974 propagateVisitedness(p.Ast, p.CoverageStats, state)
975 }
976
977 // propagateVisitedness implements two rules for extending the coverage report:
978 // - If a node is visited, all its ancestors are visited.
979 // - If a node is visited, and it has only one child, then the child is visited.
980 func propagateVisitedness(root *cel.Ast, coverageStats map[int64]set, state interpreter.EvalState) {
981 if root == nil || coverageStats == nil {
982 return
983 }
984 // Propagate visitedness upwards for ancestors.
985 ast.PostOrderVisit(root.NativeRep().Expr(), parentVisitor{coverageStats: coverageStats, evalState: state})
986 // Propagate visitedness downwards for single-child nodes.
987 ast.PostOrderVisit(root.NativeRep().Expr(), childrenVisitor{coverageStats: coverageStats, evalState: state})
988 }
989
990 // childrenVisitor is a visitor that populates the coverageStats for the child nodes of a given expression.
991 type childrenVisitor struct {
992 coverageStats map[int64]set
993 evalState interpreter.EvalState
994 }
995
996 // VisitExpr sets the coverageStats for the child of the given expression when the expression has just one child.
997 func (cv childrenVisitor) VisitExpr(e ast.Expr) {
998 if cv.coverageStats[e.ID()] == nil {
999 return
1000 }
1001 switch e.Kind() {
1002 case ast.SelectKind:
1003 selExprOperand := e.AsSelect().Operand()
1004 if _, ok := cv.coverageStats[selExprOperand.ID()]; !ok {
1005 cv.coverageStats[selExprOperand.ID()] = make(set)
1006 }
1007 case ast.CallKind:
1008 if c := e.AsCall(); c.FunctionName() == operators.Negate || c.FunctionName() == operators.LogicalNot {
1009 if _, ok := cv.coverageStats[c.Args()[0].ID()]; !ok {
1010 cv.coverageStats[c.Args()[0].ID()] = make(set)
1011 }
1012 }
1013 }
1014 }
1015
1016 // VisitEntryExpr does not affect the coverageStats for the child nodes of the given entry expression.
1017 func (cv childrenVisitor) VisitEntryExpr(e ast.EntryExpr) {}
1018
1019 // parentVisitor is a visitor that populates the coverageStats of a given expression based on the
1020 // coverageStats of its direct children.
1021 type parentVisitor struct {
1022 coverageStats map[int64]set
1023 evalState interpreter.EvalState
1024 }
1025
1026 // VisitExpr populates the coverageStats for the current expression based on the coverageStats of its direct children.
1027 func (pv parentVisitor) VisitExpr(e ast.Expr) {
1028 switch e.Kind() {
1029 case ast.SelectKind:
1030 if pv.coverageStats[e.ID()] != nil {
1031 return
1032 }
1033 if _, ok := pv.coverageStats[e.AsSelect().Operand().ID()]; ok {
1034 pv.coverageStats[e.ID()] = make(set)
1035 }
1036 case ast.CallKind:
1037 c := e.AsCall()
1038 if c.FunctionName() == "cel.@block" {
1039 pv.coverageStats[e.ID()] = pv.coverageStats[c.Args()[1].ID()]
1040 return
1041 }
1042 if c.FunctionName() == operators.Conditional {
1043 truthyID := c.Args()[1].ID()
1044 if truthyVal, ok := pv.evalState.Value(truthyID); ok {
1045 if pv.coverageStats[e.ID()] == nil {
1046 pv.coverageStats[e.ID()] = make(set)
1047 }
1048 pv.coverageStats[e.ID()][truthyVal] = struct{}{}
1049 }
1050 falsyID := c.Args()[2].ID()
1051 if falsyVal, ok := pv.evalState.Value(falsyID); ok {
1052 if pv.coverageStats[e.ID()] == nil {
1053 pv.coverageStats[e.ID()] = make(set)
1054 }
1055 pv.coverageStats[e.ID()][falsyVal] = struct{}{}
1056 }
1057 return
1058 }
1059 if pv.coverageStats[e.ID()] != nil {
1060 return
1061 }
1062 for _, arg := range c.Args() {
1063 if _, ok := pv.coverageStats[arg.ID()]; ok {
1064 pv.coverageStats[e.ID()] = make(set)
1065 break
1066 }
1067 }
1068 if c.IsMemberFunction() && pv.coverageStats[c.Target().ID()] == nil && pv.coverageStats[e.ID()] != nil {
1069 pv.coverageStats[c.Target().ID()] = make(set)
1070 }
1071 case ast.ListKind:
1072 if pv.coverageStats[e.ID()] != nil {
1073 return
1074 }
1075 l := e.AsList()
1076 for _, element := range l.Elements() {
1077 if _, ok := pv.coverageStats[element.ID()]; ok {
1078 pv.coverageStats[e.ID()] = make(set)
1079 break
1080 }
1081 }
1082 case ast.MapKind:
1083 if pv.coverageStats[e.ID()] != nil {
1084 return
1085 }
1086 m := e.AsMap()
1087 for _, entry := range m.Entries() {
1088 if _, ok := pv.coverageStats[entry.ID()]; ok {
1089 pv.coverageStats[e.ID()] = make(set)
1090 break
1091 }
1092 }
1093 case ast.StructKind:
1094 if pv.coverageStats[e.ID()] != nil {
1095 return
1096 }
1097 s := e.AsStruct()
1098 for _, field := range s.Fields() {
1099 if _, ok := pv.coverageStats[field.ID()]; ok {
1100 pv.coverageStats[e.ID()] = make(set)
1101 break
1102 }
1103 }
1104 case ast.ComprehensionKind:
1105 if pv.coverageStats[e.ID()] != nil {
1106 return
1107 }
1108 comp := e.AsComprehension()
1109 if _, ok := pv.coverageStats[comp.IterRange().ID()]; ok {
1110 pv.coverageStats[e.ID()] = make(set)
1111 } else if _, ok = pv.coverageStats[comp.AccuInit().ID()]; ok {
1112 pv.coverageStats[e.ID()] = make(set)
1113 } else if _, ok = pv.coverageStats[comp.LoopCondition().ID()]; ok {
1114 pv.coverageStats[e.ID()] = make(set)
1115 } else if _, ok = pv.coverageStats[comp.LoopStep().ID()]; ok {
1116 pv.coverageStats[e.ID()] = make(set)
1117 } else if _, ok = pv.coverageStats[comp.Result().ID()]; ok {
1118 pv.coverageStats[e.ID()] = make(set)
1119 }
1120 }
1121 }
1122
1123 // VisitEntryExpr populates the coverageStats for the current entry expression based on the coverageStats
1124 // of its direct children.
1125 func (pv parentVisitor) VisitEntryExpr(e ast.EntryExpr) {
1126 if pv.coverageStats[e.ID()] != nil {
1127 return
1128 }
1129 switch e.Kind() {
1130 case ast.MapEntryKind:
1131 me := e.AsMapEntry()
1132 if _, ok := pv.coverageStats[me.Key().ID()]; ok {
1133 pv.coverageStats[e.ID()] = make(set)
1134 }
1135 if _, ok := pv.coverageStats[me.Value().ID()]; ok {
1136 pv.coverageStats[e.ID()] = make(set)
1137 }
1138 case ast.StructFieldKind:
1139 sf := e.AsStructField()
1140 if _, ok := pv.coverageStats[sf.Value().ID()]; ok {
1141 pv.coverageStats[e.ID()] = make(set)
1142 }
1143 }
1144 }