Debian Codegraph @

tools/celtest/test_runner_test.go

raw
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 "testing"
20
21 "github.com/google/cel-go/cel"
22 "github.com/google/cel-go/common/decls"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 "github.com/google/cel-go/policy"
26 "github.com/google/cel-go/test"
27 "github.com/google/cel-go/tools/compiler"
28
29 "go.yaml.in/yaml/v3"
30
31 conformancepb "cel.dev/expr/conformance/test"
32 )
33
34 type testCase struct {
35 name string
36 celExpression string
37 testSuitePath string
38 fileDescriptorSetPath string
39 configPath string
40 opts []any
41 }
42
43 func setupTests() []*testCase {
44 testCases := []*testCase{
45 {
46 name: "policy test with custom policy parser",
47 celExpression: "../../policy/testdata/k8s/policy.yaml",
48 testSuitePath: "../../policy/testdata/k8s/tests.yaml",
49 configPath: "../../policy/testdata/k8s/config.yaml",
50 opts: []any{k8sParserOpts()},
51 },
52 {
53 name: "policy test with function binding",
54 celExpression: "../../policy/testdata/restricted_destinations/policy.yaml",
55 testSuitePath: "../../policy/testdata/restricted_destinations/tests.yaml",
56 configPath: "../../policy/testdata/restricted_destinations/config.yaml",
57 opts: []any{locationCodeEnvOption()},
58 },
59 {
60 name: "policy test with custom policy metadata",
61 celExpression: "testdata/custom_policy.celpolicy",
62 testSuitePath: "testdata/custom_policy_tests.yaml",
63 opts: []any{customPolicyParserOption(), compiler.PolicyMetadataEnvOption(ParsePolicyVariables)},
64 },
65 {
66 name: "raw expression file test",
67 celExpression: "testdata/raw_expr.cel",
68 testSuitePath: "testdata/raw_expr_tests.yaml",
69 configPath: "testdata/config.yaml",
70 opts: []any{fnEnvOption()},
71 },
72 {
73 name: "raw expression test",
74 celExpression: "a || i + fn(j) == 42",
75 testSuitePath: "testdata/raw_expr_tests.yaml",
76 configPath: "testdata/config.yaml",
77 opts: []any{fnEnvOption()},
78 },
79 }
80 return testCases
81 }
82
83 func locationCodeEnvOption() cel.EnvOption {
84 return cel.Function("locationCode",
85 cel.Overload("locationCode_string", []*cel.Type{cel.StringType}, cel.StringType,
86 cel.UnaryBinding(locationCode)))
87 }
88
89 func locationCode(ip ref.Val) ref.Val {
90 switch ip.(types.String) {
91 case "10.0.0.1":
92 return types.String("us")
93 case "10.0.0.2":
94 return types.String("de")
95 default:
96 return types.String("ir")
97 }
98 }
99
100 func k8sParserOpts() policy.ParserOption {
101 return func(p *policy.Parser) (*policy.Parser, error) {
102 p.TagVisitor = policy.K8sTestTagHandler()
103 return p, nil
104 }
105 }
106
107 // TestTriggerTestsWithRunnerOptions tests the TriggerTestsFromCompiler function for a custom policy
108 // by providing test runner and compiler options without setting the flag variables.
109 func TestTriggerTestsWithRunnerOptions(t *testing.T) {
110 t.Run("test trigger tests custom policy", func(t *testing.T) {
111 envOpt := compiler.EnvironmentFile("../../policy/testdata/k8s/config.yaml")
112 testSuiteParser := DefaultTestSuiteParser("../../policy/testdata/k8s/tests.yaml")
113 testCELPolicy := TestExpression("../../policy/testdata/k8s/policy.yaml")
114 c, err := compiler.NewCompiler(envOpt, k8sParserOpts())
115 if err != nil {
116 t.Fatalf("compiler.NewCompiler() failed: %v", err)
117 }
118 compilerOpt := CustomTestCompiler(c)
119 opts := []TestRunnerOption{compilerOpt, testSuiteParser, testCELPolicy}
120 TriggerTests(t, opts...)
121 })
122 }
123
124 func customPolicyParserOption() policy.ParserOption {
125 return func(p *policy.Parser) (*policy.Parser, error) {
126 p.TagVisitor = customTagHandler{TagVisitor: policy.DefaultTagVisitor()}
127 return p, nil
128 }
129 }
130 func ParsePolicyVariables(metadata map[string]any) cel.EnvOption {
131 var variables []*decls.VariableDecl
132 for n, t := range metadata {
133 variables = append(variables, decls.NewVariable(n, parseCustomPolicyVariableType(t.(string))))
134 }
135 return cel.VariableDecls(variables...)
136 }
137
138 func parseCustomPolicyVariableType(t string) *types.Type {
139 switch t {
140 case "int":
141 return types.IntType
142 case "string":
143 return types.StringType
144 default:
145 return types.UnknownType
146 }
147 }
148
149 type variableType struct {
150 VariableName string `yaml:"variable_name"`
151 VariableType string `yaml:"variable_type"`
152 }
153
154 type customTagHandler struct {
155 policy.TagVisitor
156 }
157
158 func (customTagHandler) PolicyTag(ctx policy.ParserContext, id int64, tagName string, node *yaml.Node, p *policy.Policy) {
159 switch tagName {
160 case "variable_types":
161 var varList []*variableType
162 if err := node.Decode(&varList); err != nil {
163 ctx.ReportErrorAtID(id, "invalid yaml variable_types node: %v, error: %w", node, err)
164 return
165 }
166 for _, v := range varList {
167 p.SetMetadata(v.VariableName, v.VariableType)
168 }
169 default:
170 ctx.ReportErrorAtID(id, "unsupported policy tag: %s", tagName)
171 }
172 }
173
174 func fnEnvOption() cel.EnvOption {
175 return cel.Function("fn",
176 cel.Overload("fn_int", []*cel.Type{cel.IntType}, cel.IntType,
177 cel.UnaryBinding(func(in ref.Val) ref.Val {
178 i := in.(types.Int)
179 return i / types.Int(2)
180 })))
181 }
182
183 // TestTriggerTests tests different scenarios of the TriggerTestsFromCompiler function.
184 func TestTriggerTests(t *testing.T) {
185 for _, tc := range setupTests() {
186 t.Run(tc.name, func(t *testing.T) {
187 var testOpts []TestRunnerOption
188 compileOpts := make([]any, 0, len(tc.opts)+2)
189 for _, opt := range tc.opts {
190 compileOpts = append(compileOpts, opt)
191 }
192 if tc.fileDescriptorSetPath != "" {
193 compileOpts = append(compileOpts, compiler.TypeDescriptorSetFile(tc.fileDescriptorSetPath))
194 }
195 if tc.configPath != "" {
196 compileOpts = append(compileOpts, compiler.EnvironmentFile(tc.configPath))
197 }
198 testOpts = append(testOpts,
199 TestCompiler(compileOpts...),
200 DefaultTestSuiteParser(tc.testSuitePath),
201 AddFileDescriptorSet(tc.fileDescriptorSetPath),
202 TestExpression(tc.celExpression),
203 PartialEvalProgramOption(),
204 )
205 TriggerTests(t, testOpts...)
206 })
207 }
208 }
209
210 // TestCustomTestSuiteParser triggers the test runner where the tests are provided by a custom
211 // test suite parser configured using TestSuiteParserOption.
212 func TestCustomTestSuiteParser(t *testing.T) {
213 t.Run("test custom test suite parser", func(t *testing.T) {
214 celExpr := "a || i + fn(j) == 42"
215 compilerOpts := []any{compiler.EnvironmentFile("testdata/config.yaml"), fnEnvOption()}
216 testRunnerOpts := []TestRunnerOption{
217 TestCompiler(compilerOpts...),
218 TestExpression(celExpr),
219 TestSuiteParserOption(&tsparser{}),
220 }
221 TriggerTests(t, testRunnerOpts...)
222 })
223 }
224
225 type tsparser struct {
226 TestSuiteParser
227 }
228
229 // ParseTextproto implements the ParseTextproto method of the TestSuiteParser interface.
230 func (p *tsparser) ParseTextproto(_ string) (*conformancepb.TestSuite, error) {
231 return nil, nil
232 }
233
234 // ParseYAML implements the ParseYAML method of the TestSuiteParser interface.
235 func (p *tsparser) ParseYAML(_ string) (*test.Suite, error) {
236 testCase := &test.Case{
237 Name: "sample test case",
238 Input: map[string]*test.InputValue{
239 "i": {Value: 21},
240 "j": {Value: 42},
241 "a": {Value: false},
242 },
243 Output: &test.Output{Value: true},
244 }
245 testSection := &test.Section{
246 Name: "sample test section",
247 Tests: []*test.Case{testCase},
248 }
249 suite := &test.Suite{
250 Description: "sample test suite",
251 Sections: []*test.Section{testSection},
252 }
253 return suite, nil
254 }