k8s.io/apiserver@v0.31.1/pkg/cel/library/test.go (about) 1 /* 2 Copyright 2023 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 library 18 19 import ( 20 "math" 21 22 "github.com/google/cel-go/cel" 23 "github.com/google/cel-go/common/types" 24 "github.com/google/cel-go/common/types/ref" 25 ) 26 27 // Test provides a test() function that returns true. 28 func Test(options ...TestOption) cel.EnvOption { 29 t := &testLib{version: math.MaxUint32} 30 for _, o := range options { 31 t = o(t) 32 } 33 return cel.Lib(t) 34 } 35 36 type testLib struct { 37 version uint32 38 } 39 40 func (*testLib) LibraryName() string { 41 return "k8s.test" 42 } 43 44 type TestOption func(*testLib) *testLib 45 46 func TestVersion(version uint32) func(lib *testLib) *testLib { 47 return func(sl *testLib) *testLib { 48 sl.version = version 49 return sl 50 } 51 } 52 53 func (t *testLib) CompileOptions() []cel.EnvOption { 54 var options []cel.EnvOption 55 56 if t.version == 0 { 57 options = append(options, cel.Function("test", 58 cel.Overload("test", []*cel.Type{}, cel.BoolType, 59 cel.FunctionBinding(func(args ...ref.Val) ref.Val { 60 return types.True 61 })))) 62 } 63 64 if t.version >= 1 { 65 options = append(options, cel.Function("test", 66 cel.Overload("test", []*cel.Type{}, cel.BoolType, 67 cel.FunctionBinding(func(args ...ref.Val) ref.Val { 68 // Return false here so tests can observe which version of the function is registered 69 // Actual function libraries must not break backward compatibility 70 return types.False 71 })))) 72 options = append(options, cel.Function("testV1", 73 cel.Overload("testV1", []*cel.Type{}, cel.BoolType, 74 cel.FunctionBinding(func(args ...ref.Val) ref.Val { 75 return types.True 76 })))) 77 } 78 return options 79 } 80 81 func (*testLib) ProgramOptions() []cel.ProgramOption { 82 return []cel.ProgramOption{} 83 }