Debian Codegraph @

pkg/cel/mutation/typeresolver_test.go

raw
1 /*
2 Copyright 2024 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package mutation
18
19 import (
20 "reflect"
21 "strings"
22 "testing"
23
24 "github.com/google/cel-go/cel"
25 "github.com/google/cel-go/common/types"
26 "github.com/google/cel-go/common/types/ref"
27
28 "k8s.io/apimachinery/pkg/util/version"
29 "k8s.io/apiserver/pkg/cel/common"
30 "k8s.io/apiserver/pkg/cel/environment"
31 "k8s.io/apiserver/pkg/cel/mutation/dynamic"
32 )
33
34 func TestTypeResolver(t *testing.T) {
35 for _, tc := range []struct {
36 name string
37 expression string
38 expectedValue any
39 expectCompileError string
40 }{
41 {
42 name: "not an object",
43 expression: `string(114514)`,
44 expectedValue: "114514",
45 },
46 {
47 name: "empty",
48 expression: "Object{}",
49 expectedValue: map[string]any{},
50 },
51 {
52 name: "Object.spec",
53 expression: "Object{spec: Object.spec{replicas: 3}}",
54 expectedValue: map[string]any{
55 "spec": map[string]any{
56 // an integer maps to int64
57 "replicas": int64(3),
58 },
59 },
60 },
61 {
62 // list literal does not require new Path code of the type provider
63 // comparing to the object literal.
64 // This test case serves as a note of "supported syntax"
65 name: "Object.spec.template.containers",
66 expression: `Object{
67 spec: Object.spec{
68 template: Object.spec.template{
69 containers: [
70 Object.spec.template.containers.item{
71 name: "nginx",
72 image: "nginx",
73 args: ["-g"]
74 }
75 ]
76 }
77 }
78 }`,
79 expectedValue: map[string]any{
80 "spec": map[string]any{
81 "template": map[string]any{
82 "containers": []any{
83 map[string]any{
84 "name": "nginx",
85 "image": "nginx",
86 "args": []any{"-g"},
87 },
88 },
89 },
90 },
91 },
92 },
93 {
94 name: "list of ints",
95 expression: `Object{
96 intList: [1, 2, 3]
97 }`,
98 expectedValue: map[string]any{
99 "intList": []any{int64(1), int64(2), int64(3)},
100 },
101 },
102 {
103 name: "map string-to-string",
104 expression: `Object{
105 annotations: {"foo": "bar"}
106 }`,
107 expectedValue: map[string]any{
108 "annotations": map[string]any{
109 "foo": "bar",
110 },
111 },
112 },
113 {
114 name: "field access",
115 expression: `Object{
116 intList: [1, 2, 3]
117 }.intList.sum()`,
118 expectedValue: int64(6),
119 },
120 {
121 name: "equality check",
122 expression: "Object{spec: Object.spec{replicas: 3}} == Object{spec: Object.spec{replicas: 1 + 2}}",
123 expectedValue: true,
124 },
125 {
126 name: "invalid type",
127 expression: "Invalid{}",
128 expectCompileError: "undeclared reference to 'Invalid'",
129 },
130 {
131 name: "logic around JSONPatch",
132 expression: `true ? JSONPatch{op: "add", path: "/spec/replicas", value: 3} : JSONPatch{op: "remove", path: "/spec/replicas"}`,
133 expectedValue: &JSONPatchVal{Op: "add", Path: "/spec/replicas", Val: types.Int(3)},
134 },
135 {
136 name: "JSONPatch add",
137 expression: `JSONPatch{op: "add", path: "/spec/replicas", value: 3}`,
138 expectedValue: &JSONPatchVal{Op: "add", Path: "/spec/replicas", Val: types.Int(3)},
139 },
140 {
141 name: "JSONPatch remove",
142 expression: `JSONPatch{op: "remove", path: "/spec/replicas"}`,
143 expectedValue: &JSONPatchVal{Op: "remove", Path: "/spec/replicas"},
144 },
145 {
146 name: "JSONPatch replace",
147 expression: `JSONPatch{op: "replace", path: "/spec/replicas", value: 3}`,
148 expectedValue: &JSONPatchVal{Op: "replace", Path: "/spec/replicas", Val: types.Int(3)},
149 },
150 {
151 name: "JSONPatch move",
152 expression: `JSONPatch{op: "move", from: "/spec/replicas", path: "/spec/replicas"}`,
153 expectedValue: &JSONPatchVal{Op: "move", From: "/spec/replicas", Path: "/spec/replicas"},
154 },
155 {
156 name: "JSONPatch copy",
157 expression: `JSONPatch{op: "copy", from: "/spec/replicas", path: "/spec/replicas"}`,
158 expectedValue: &JSONPatchVal{Op: "copy", From: "/spec/replicas", Path: "/spec/replicas"},
159 },
160 {
161 name: "JSONPatch test",
162 expression: `JSONPatch{op: "test", path: "/spec/replicas", value: 3}`,
163 expectedValue: &JSONPatchVal{Op: "test", Path: "/spec/replicas", Val: types.Int(3)},
164 },
165 {
166 name: "JSONPatch invalid op",
167 expression: `JSONPatch{op: "invalid", path: "/spec/replicas", value: 3}`,
168 expectedValue: &JSONPatchVal{Op: "invalid", Path: "/spec/replicas", Val: types.Int(3)},
169 // no error because the values are not checked in compilation.
170 },
171 {
172 name: "JSONPatch missing path",
173 expression: `JSONPatch{op: "add", value: 3}`,
174 expectedValue: &JSONPatchVal{Op: "add", Val: types.Int(3)},
175 // no error because the values are not checked in compilation.
176 },
177 {
178 name: "JSONPatch missing value",
179 expression: `JSONPatch{op: "add", path: "/spec/replicas"}`,
180 expectedValue: &JSONPatchVal{Op: "add", Path: "/spec/replicas"},
181 // no error because the values are not checked in compilation.
182 },
183 {
184 name: "JSONPatch invalid value",
185 expression: `JSONPatch{op: "add", path: "/spec/replicas", value: Invalid{}}`,
186 expectCompileError: "undeclared reference to 'Invalid'",
187 },
188 {
189 name: "JSONPatch invalid path",
190 expression: `JSONPatch{op: "add", path: Invalid{}, value: 3}`,
191 expectCompileError: "undeclared reference to 'Invalid'",
192 },
193 {
194 name: "JSONPatch invalid from",
195 expression: `JSONPatch{op: "move", from: Invalid{}, path: "/spec/replicas"}`,
196 expectCompileError: "undeclared reference to 'Invalid'",
197 },
198 {
199 name: "JSONPatch invalid op type",
200 expression: `JSONPatch{op: 1, path: "/spec/replicas", value: 3}`,
201 expectCompileError: "expected type of field 'op' is 'string' but provided type is 'int'",
202 },
203 {
204 name: "JSONPatch invalid path type",
205 expression: `JSONPatch{op: "add", path: 1, value: 3}`,
206 expectCompileError: "expected type of field 'path' is 'string' but provided type is 'int'",
207 },
208 {
209 name: "JSONPatch invalid from type",
210 expression: `JSONPatch{op: "move", from: 1, path: "/spec/replicas"}`,
211 expectCompileError: "expected type of field 'from' is 'string' but provided type is 'int'",
212 },
213 } {
214 t.Run(tc.name, func(t *testing.T) {
215 _, option := common.NewResolverTypeProviderAndEnvOption(&DynamicTypeResolver{})
216 env := mustCreateEnv(t, option)
217 ast, issues := env.Compile(tc.expression)
218 if len(tc.expectCompileError) > 0 {
219 if issues == nil {
220 t.Fatalf("expected error %v but got no error", tc.expectCompileError)
221 }
222 if !strings.Contains(issues.String(), tc.expectCompileError) {
223 t.Fatalf("expected error %v but got %v", tc.expectCompileError, issues.String())
224 }
225 return
226 }
227
228 if issues != nil {
229 t.Fatalf("unexpected issues during compilation: %v", issues)
230 }
231 program, err := env.Program(ast)
232 if err != nil {
233 t.Fatalf("unexpected error while creating program: %v", err)
234 }
235 r, _, err := program.Eval(map[string]any{})
236 if err != nil {
237 t.Fatalf("unexpected error during evaluation: %v", err)
238 }
239 if v := r.Value(); !reflect.DeepEqual(v, tc.expectedValue) {
240 t.Errorf("expected %#v but got %#v", tc.expectedValue, v)
241 }
242 })
243 }
244 }
245
246 // TestCELOptional is an exploration test to demonstrate how CEL optional library
247 // behave for the use cases that the mutation library requires.
248 func TestCELOptional(t *testing.T) {
249 for _, tc := range []struct {
250 name string
251 expression string
252 expectedVal ref.Val
253 expectedCompileError string
254 }{
255 {
256 name: "construct existing field with none, empty object",
257 expression: `Object{
258 ?existing: optional.none()
259 }`,
260 expectedVal: dynamic.NewObjectVal(types.NewObjectType("Object"), map[string]ref.Val{
261 // "existing" field was not set.
262 }),
263 },
264 {
265 name: "object of zero value, ofNonZeroValue",
266 expression: `Object{?spec: optional.ofNonZeroValue(Object.spec{?replicas: Object{}.?replicas})}`,
267 expectedVal: dynamic.NewObjectVal(types.NewObjectType("Object"), map[string]ref.Val{
268 // "existing" field was not set.
269 }),
270 },
271 {
272 name: "access existing field, return none",
273 expression: `Object{}.?existing`,
274 expectedVal: types.OptionalNone,
275 },
276 {
277 name: "map non-existing field, return none",
278 expression: `{"foo": 1}[?"bar"]`,
279 expectedVal: types.OptionalNone,
280 },
281 {
282 name: "map existing field, return actual value",
283 expression: `{"foo": 1}[?"foo"]`,
284 expectedVal: types.OptionalOf(types.Int(1)),
285 },
286 {
287 // Map has a different behavior than Object
288 //
289 // Quoting from
290 // https://github.com/google/cel-spec/blob/master/doc/langdef.md#field-selection
291 //
292 // To test for the presence of a field, the boolean-valued macro has(e.f) can be used.
293 //
294 // 1. If e evaluates to a map, then has(e.f) indicates whether the string f is
295 // a key in the map (note that f must syntactically be an identifier).
296 //
297 name: "has on a map, de-sugared, non-existing field, returns false",
298 // has marco supports only the dot access syntax.
299 expression: `has({"foo": 1}.bar)`,
300 expectedVal: types.False,
301 },
302 {
303 name: "has on a map, de-sugared, existing field, returns true",
304 // has marco supports only the dot access syntax.
305 expression: `has({"foo": 1}.foo)`,
306 expectedVal: types.True,
307 },
308 } {
309 t.Run(tc.name, func(t *testing.T) {
310 _, option := common.NewResolverTypeProviderAndEnvOption(&DynamicTypeResolver{})
311 env := mustCreateEnvWithOptional(t, option)
312 ast, issues := env.Compile(tc.expression)
313 if len(tc.expectedCompileError) > 0 {
314 if issues == nil {
315 t.Fatalf("expected error %v but got no error", tc.expectedCompileError)
316 }
317 if !strings.Contains(issues.String(), tc.expectedCompileError) {
318 t.Fatalf("expected error %v but got %v", tc.expectedCompileError, issues.String())
319 }
320 return
321 }
322 if issues != nil {
323 t.Fatalf("unexpected issues during compilation: %v", issues)
324 }
325 program, err := env.Program(ast)
326 if err != nil {
327 t.Fatalf("unexpected error while creating program: %v", err)
328 }
329 r, _, err := program.Eval(map[string]any{})
330 if err != nil {
331 t.Fatalf("unexpected error during evaluation: %v", err)
332 }
333 if equals := tc.expectedVal.Equal(r); equals.Value() != true {
334 t.Errorf("expected %#+v but got %#+v", tc.expectedVal, r)
335 }
336 })
337 }
338 }
339
340 // mustCreateEnv creates the default env for testing, with given option.
341 // it fatally fails the test if the env fails to set up.
342 func mustCreateEnv(t testing.TB, envOptions ...cel.EnvOption) *cel.Env {
343 envSet, err := environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion(), true).
344 Extend(environment.VersionedOptions{
345 IntroducedVersion: version.MajorMinor(1, 0), // Always enabled. This is just for test.
346 EnvOptions: envOptions,
347 })
348 if err != nil {
349 t.Fatalf("fail to create env set: %v", err)
350 }
351 env, err := envSet.Env(environment.StoredExpressions)
352 if err != nil {
353 t.Fatalf("fail to setup env: %v", env)
354 }
355 return env
356 }
357
358 // mustCreateEnvWithOptional creates the default env for testing, with given option,
359 // and set up the optional library with default configuration.
360 // it fatally fails the test if the env fails to set up.
361 func mustCreateEnvWithOptional(t testing.TB, envOptions ...cel.EnvOption) *cel.Env {
362 return mustCreateEnv(t, append(envOptions, cel.OptionalTypes())...)
363 }