Skip to content

Commit 0d18ae3

Browse files
committed
apiextensions: add pkg/test with CEL unit test helpers
Signed-off-by: Dr. Stefan Schimanski <[email protected]>
1 parent 810e9e2 commit 0d18ae3

File tree

4 files changed

+853
-0
lines changed

4 files changed

+853
-0
lines changed
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
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 test
18+
19+
import (
20+
"context"
21+
"fmt"
22+
"os"
23+
"testing"
24+
25+
"github.com/stretchr/testify/require"
26+
27+
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
28+
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
29+
"k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
30+
"k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel"
31+
"k8s.io/apimachinery/pkg/util/validation/field"
32+
"k8s.io/apimachinery/pkg/util/yaml"
33+
celconfig "k8s.io/apiserver/pkg/apis/cel"
34+
)
35+
36+
// FieldValidatorsFromFile extracts the CEL validators by version and JSONPath from a CRD file and returns
37+
// a validator func for testing against samples.
38+
func FieldValidatorsFromFile(t *testing.T, crdFilePath string) (validatorsByVersionByJSONPath map[string]map[string]CELValidateFunc) {
39+
data, err := os.ReadFile(crdFilePath)
40+
require.NoError(t, err)
41+
42+
var crd apiextensionsv1.CustomResourceDefinition
43+
err = yaml.Unmarshal(data, &crd)
44+
require.NoError(t, err)
45+
46+
return FieldValidators(t, &crd)
47+
}
48+
49+
// FieldValidators extracts the CEL validators by version and JSONPath from a CRD and returns
50+
// a validator func for testing against samples.
51+
func FieldValidators(t *testing.T, crd *apiextensionsv1.CustomResourceDefinition) (validatorsByVersionByJSONPath map[string]map[string]CELValidateFunc) {
52+
ret := map[string]map[string]CELValidateFunc{}
53+
for _, v := range crd.Spec.Versions {
54+
var internalSchema apiextensions.JSONSchemaProps
55+
err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(v.Schema.OpenAPIV3Schema, &internalSchema, nil)
56+
require.NoError(t, err, "failed to convert JSONSchemaProps for version %s: %v", v.Name, err)
57+
structuralSchema, err := schema.NewStructural(&internalSchema)
58+
require.NoError(t, err, "failed to create StructuralSchema for version %s: %v", v.Name, err)
59+
60+
versionVals, err := findCEL(t, structuralSchema, true, field.NewPath("openAPIV3Schema"))
61+
require.NoError(t, err, "failed to find CEL for version %s: %v", v.Name, err)
62+
ret[v.Name] = versionVals
63+
}
64+
65+
return ret
66+
}
67+
68+
// VersionValidatorsFromFile extracts the CEL validators by version from a CRD file and returns
69+
// a validator func for testing against samples.
70+
func VersionValidatorsFromFile(t *testing.T, crdFilePath string) map[string]CELValidateFunc {
71+
data, err := os.ReadFile(crdFilePath)
72+
require.NoError(t, err)
73+
74+
var crd apiextensionsv1.CustomResourceDefinition
75+
err = yaml.Unmarshal(data, &crd)
76+
require.NoError(t, err)
77+
78+
ret := map[string]CELValidateFunc{}
79+
for _, v := range crd.Spec.Versions {
80+
var internalSchema apiextensions.JSONSchemaProps
81+
err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(v.Schema.OpenAPIV3Schema, &internalSchema, nil)
82+
require.NoError(t, err, "failed to convert JSONSchemaProps for version %s: %v", v.Name, err)
83+
structuralSchema, err := schema.NewStructural(&internalSchema)
84+
require.NoError(t, err, "failed to create StructuralSchema for version %s: %v", v.Name, err)
85+
ret[v.Name] = func(obj, old interface{}) field.ErrorList {
86+
errs, _ := cel.NewValidator(structuralSchema, true, celconfig.RuntimeCELCostBudget).Validate(context.TODO(), nil, structuralSchema, obj, old, celconfig.PerCallLimit)
87+
return errs
88+
}
89+
}
90+
91+
return ret
92+
}
93+
94+
// VersionValidatorFromFile extracts the CEL validators for a given version from a CRD file and returns
95+
// a validator func for testing against samples.
96+
func VersionValidatorFromFile(t *testing.T, crdFilePath string, version string) (CELValidateFunc, error) {
97+
vals := VersionValidatorsFromFile(t, crdFilePath)
98+
if val, ok := vals[version]; ok {
99+
return val, nil
100+
}
101+
return nil, fmt.Errorf("version %s not found", version)
102+
}
103+
104+
// CELValidateFunc tests a sample object against a CEL validator.
105+
type CELValidateFunc func(obj, old interface{}) field.ErrorList
106+
107+
func findCEL(t *testing.T, s *schema.Structural, root bool, pth *field.Path) (map[string]CELValidateFunc, error) {
108+
ret := map[string]CELValidateFunc{}
109+
110+
if len(s.XValidations) > 0 {
111+
s := *s
112+
pth := *pth
113+
ret[pth.String()] = func(obj, old interface{}) field.ErrorList {
114+
errs, _ := cel.NewValidator(&s, root, celconfig.RuntimeCELCostBudget).Validate(context.TODO(), &pth, &s, obj, old, celconfig.PerCallLimit)
115+
return errs
116+
}
117+
}
118+
119+
for k, v := range s.Properties {
120+
v := v
121+
sub, err := findCEL(t, &v, false, pth.Child("properties").Child(k))
122+
if err != nil {
123+
return nil, err
124+
}
125+
126+
for pth, val := range sub {
127+
ret[pth] = val
128+
}
129+
}
130+
if s.Items != nil {
131+
sub, err := findCEL(t, s.Items, false, pth.Child("items"))
132+
if err != nil {
133+
return nil, err
134+
}
135+
for pth, val := range sub {
136+
ret[pth] = val
137+
}
138+
}
139+
if s.AdditionalProperties != nil && s.AdditionalProperties.Structural != nil {
140+
sub, err := findCEL(t, s.AdditionalProperties.Structural, false, pth.Child("additionalProperties"))
141+
if err != nil {
142+
return nil, err
143+
}
144+
for pth, val := range sub {
145+
ret[pth] = val
146+
}
147+
}
148+
149+
return ret, nil
150+
}

0 commit comments

Comments
 (0)