Debian Codegraph @

pkg/util/proto/validation/validation_test.go

raw
1 /*
2 Copyright 2017 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 validation_test
18
19 import (
20 "fmt"
21 "path/filepath"
22 "reflect"
23 "testing"
24
25 "sigs.k8s.io/yaml"
26
27 "k8s.io/kube-openapi/pkg/util/proto"
28 prototesting "k8s.io/kube-openapi/pkg/util/proto/testing"
29 "k8s.io/kube-openapi/pkg/util/proto/validation"
30 )
31
32 var fakeSchema = prototesting.Fake{Path: filepath.Join("..", "testdata", "swagger.json")}
33
34 func Validate(models proto.Models, model string, data string) []error {
35 var obj interface{}
36 if err := yaml.Unmarshal([]byte(data), &obj); err != nil {
37 return []error{fmt.Errorf("pre-validation: failed to parse yaml: %v", err)}
38 }
39 return ValidateObj(models, model, obj)
40 }
41
42 // ValidateObj validates an object produced by decoding json or yaml.
43 // Numbers may be int64 or float64.
44 func ValidateObj(models proto.Models, model string, obj interface{}) []error {
45 schema := models.LookupModel(model)
46 if schema == nil {
47 return []error{fmt.Errorf("pre-validation: couldn't find model %s", model)}
48 }
49
50 return validation.ValidateModel(obj, schema, model)
51 }
52
53 func loadModels(t *testing.T) proto.Models {
54 t.Helper()
55 s, err := fakeSchema.OpenAPISchema()
56 if err != nil {
57 t.Fatalf("failed to open schema: %v", err)
58 }
59 models, err := proto.NewOpenAPIData(s)
60 if err != nil {
61 t.Fatalf("failed to create OpenAPI data: %v", err)
62 }
63 return models
64 }
65
66 func TestResourceValidation(t *testing.T) {
67 t.Run("finds Deployment in Schema and validates it", func(t *testing.T) {
68 models := loadModels(t)
69 err := Validate(models, "io.k8s.api.apps.v1beta1.Deployment", `
70 apiVersion: extensions/v1beta1
71 kind: Deployment
72 metadata:
73 labels:
74 name: redis-master
75 name: name
76 spec:
77 replicas: 1
78 template:
79 metadata:
80 labels:
81 app: redis
82 spec:
83 containers:
84 - image: redis
85 name: redis
86 `)
87 if err != nil {
88 t.Errorf("unexpected error: %v", err)
89 }
90 })
91
92 t.Run("validates a valid pod", func(t *testing.T) {
93 models := loadModels(t)
94 err := Validate(models, "io.k8s.api.core.v1.Pod", `
95 apiVersion: v1
96 kind: Pod
97 metadata:
98 labels:
99 name: redis-master
100 name: name
101 spec:
102 containers:
103 - args:
104 - this
105 - is
106 - an
107 - ok
108 - command
109 image: gcr.io/fake_project/fake_image:fake_tag
110 name: master
111 `)
112 if err != nil {
113 t.Errorf("unexpected error: %v", err)
114 }
115 })
116
117 t.Run("finds invalid command (string instead of []string) in Json Pod", func(t *testing.T) {
118 models := loadModels(t)
119 err := Validate(models, "io.k8s.api.core.v1.Pod", `
120 {
121 "kind": "Pod",
122 "apiVersion": "v1",
123 "metadata": {
124 "name": "name",
125 "labels": {
126 "name": "redis-master"
127 }
128 },
129 "spec": {
130 "containers": [
131 {
132 "name": "master",
133 "image": "gcr.io/fake_project/fake_image:fake_tag",
134 "args": "this is a bad command"
135 }
136 ]
137 }
138 }
139 `)
140 want := []error{
141 validation.ValidationError{
142 Path: "io.k8s.api.core.v1.Pod.spec.containers[0].args",
143 Err: validation.InvalidTypeError{
144 Path: "io.k8s.api.core.v1.Container.args",
145 Expected: "array",
146 Actual: "string",
147 },
148 },
149 }
150 if !reflect.DeepEqual(err, want) {
151 t.Errorf("err = %v, want %v", err, want)
152 }
153 })
154
155 t.Run("fails because hostPort is string instead of int", func(t *testing.T) {
156 models := loadModels(t)
157 err := Validate(models, "io.k8s.api.core.v1.Pod", `
158 {
159 "kind": "Pod",
160 "apiVersion": "v1",
161 "metadata": {
162 "name": "apache-php",
163 "labels": {
164 "name": "apache-php"
165 }
166 },
167 "spec": {
168 "volumes": [{
169 "name": "shared-disk"
170 }],
171 "containers": [
172 {
173 "name": "apache-php",
174 "image": "gcr.io/fake_project/fake_image:fake_tag",
175 "ports": [
176 {
177 "name": "apache",
178 "hostPort": "13380",
179 "containerPort": 80,
180 "protocol": "TCP"
181 }
182 ],
183 "volumeMounts": [
184 {
185 "name": "shared-disk",
186 "mountPath": "/var/www/html"
187 }
188 ]
189 }
190 ]
191 }
192 }
193 `)
194 want := []error{
195 validation.ValidationError{
196 Path: "io.k8s.api.core.v1.Pod.spec.containers[0].ports[0].hostPort",
197 Err: validation.InvalidTypeError{
198 Path: "io.k8s.api.core.v1.ContainerPort.hostPort",
199 Expected: "integer",
200 Actual: "string",
201 },
202 },
203 }
204 if !reflect.DeepEqual(err, want) {
205 t.Errorf("err = %v, want %v", err, want)
206 }
207 })
208
209 t.Run("fails because volume is not an array of object", func(t *testing.T) {
210 models := loadModels(t)
211 err := Validate(models, "io.k8s.api.core.v1.Pod", `
212 {
213 "kind": "Pod",
214 "apiVersion": "v1",
215 "metadata": {
216 "name": "apache-php",
217 "labels": {
218 "name": "apache-php"
219 }
220 },
221 "spec": {
222 "volumes": [
223 "name": "shared-disk"
224 ],
225 "containers": [
226 {
227 "name": "apache-php",
228 "image": "gcr.io/fake_project/fake_image:fake_tag",
229 "ports": [
230 {
231 "name": "apache",
232 "hostPort": 13380,
233 "containerPort": 80,
234 "protocol": "TCP"
235 }
236 ],
237 "volumeMounts": [
238 {
239 "name": "shared-disk",
240 "mountPath": "/var/www/html"
241 }
242 ]
243 }
244 ]
245 }
246 }
247 `)
248 if err != nil {
249 t.Errorf("unexpected error: %v", err)
250 }
251 })
252
253 t.Run("fails because some string lists have empty strings", func(t *testing.T) {
254 models := loadModels(t)
255 err := Validate(models, "io.k8s.api.core.v1.Pod", `
256 apiVersion: v1
257 kind: Pod
258 metadata:
259 labels:
260 name: redis-master
261 name: name
262 spec:
263 containers:
264 - image: gcr.io/fake_project/fake_image:fake_tag
265 name: master
266 args:
267 -
268 command:
269 -
270 `)
271 want := []error{
272 validation.ValidationError{
273 Path: "io.k8s.api.core.v1.Pod.spec.containers[0].args",
274 Err: validation.InvalidObjectTypeError{
275 Path: "io.k8s.api.core.v1.Pod.spec.containers[0].args[0]",
276 Type: "nil",
277 },
278 },
279 validation.ValidationError{
280 Path: "io.k8s.api.core.v1.Pod.spec.containers[0].command",
281 Err: validation.InvalidObjectTypeError{
282 Path: "io.k8s.api.core.v1.Pod.spec.containers[0].command[0]",
283 Type: "nil",
284 },
285 },
286 }
287 if !reflect.DeepEqual(err, want) {
288 t.Errorf("err = %v, want %v", err, want)
289 }
290 })
291
292 t.Run("fails if required fields are missing", func(t *testing.T) {
293 models := loadModels(t)
294 err := Validate(models, "io.k8s.api.core.v1.Pod", `
295 apiVersion: v1
296 kind: Pod
297 metadata:
298 labels:
299 name: redis-master
300 name: name
301 spec:
302 containers:
303 - command: ["my", "command"]
304 `)
305 want := []error{
306 validation.ValidationError{
307 Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
308 Err: validation.MissingRequiredFieldError{
309 Path: "io.k8s.api.core.v1.Container",
310 Field: "name",
311 },
312 },
313 validation.ValidationError{
314 Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
315 Err: validation.MissingRequiredFieldError{
316 Path: "io.k8s.api.core.v1.Container",
317 Field: "image",
318 },
319 },
320 }
321 if !reflect.DeepEqual(err, want) {
322 t.Errorf("err = %v, want %v", err, want)
323 }
324 })
325
326 t.Run("fails if required fields are empty", func(t *testing.T) {
327 models := loadModels(t)
328 err := Validate(models, "io.k8s.api.core.v1.Pod", `
329 apiVersion: v1
330 kind: Pod
331 metadata:
332 labels:
333 name: redis-master
334 name: name
335 spec:
336 containers:
337 - image:
338 name:
339 `)
340 want := []error{
341 validation.ValidationError{
342 Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
343 Err: validation.MissingRequiredFieldError{
344 Path: "io.k8s.api.core.v1.Container",
345 Field: "name",
346 },
347 },
348 validation.ValidationError{
349 Path: "io.k8s.api.core.v1.Pod.spec.containers[0]",
350 Err: validation.MissingRequiredFieldError{
351 Path: "io.k8s.api.core.v1.Container",
352 Field: "image",
353 },
354 },
355 }
356 if !reflect.DeepEqual(err, want) {
357 t.Errorf("err = %v, want %v", err, want)
358 }
359 })
360
361 t.Run("is fine with empty non-mandatory fields", func(t *testing.T) {
362 models := loadModels(t)
363 err := Validate(models, "io.k8s.api.core.v1.Pod", `
364 apiVersion: v1
365 kind: Pod
366 metadata:
367 labels:
368 name: redis-master
369 name: name
370 spec:
371 containers:
372 - image: image
373 name: name
374 command:
375 `)
376 if err != nil {
377 t.Errorf("unexpected error: %v", err)
378 }
379 })
380
381 t.Run("fails because apiVersion is not provided", func(t *testing.T) {
382 models := loadModels(t)
383 err := Validate(models, "io.k8s.api.core.v1.Pod", `
384 kind: Pod
385 metadata:
386 name: name
387 spec:
388 containers:
389 - name: name
390 image: image
391 `)
392 if err != nil {
393 t.Errorf("unexpected error: %v", err)
394 }
395 })
396
397 t.Run("fails because apiVersion type is not string and kind is not provided", func(t *testing.T) {
398 models := loadModels(t)
399 err := Validate(models, "io.k8s.api.core.v1.Pod", `
400 apiVersion: 1
401 metadata:
402 name: name
403 spec:
404 containers:
405 - name: name
406 image: image
407 `)
408 if err != nil {
409 t.Errorf("unexpected error: %v", err)
410 }
411 })
412
413 t.Run("validates integer values for float fields", func(t *testing.T) {
414 models := loadModels(t)
415 err := ValidateObj(models, "io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinition", map[string]interface{}{
416 "apiVersion": "apiextensions.k8s.io/v1",
417 "kind": "CustomResourceDefinition",
418 "metadata": map[string]interface{}{"name": "foo"},
419 "spec": map[string]interface{}{
420 "scope": "Namespaced",
421 "group": "example.com",
422 "names": map[string]interface{}{
423 "plural": "numbers",
424 "kind": "Number",
425 },
426 "versions": []interface{}{
427 map[string]interface{}{
428 "name": "v1",
429 "served": true,
430 "storage": true,
431 "schema": map[string]interface{}{
432 "openAPIV3Schema": map[string]interface{}{
433 "properties": map[string]interface{}{
434 "replicas": map[string]interface{}{
435 "default": int64(1),
436 "minimum": int64(0),
437 "type": "integer",
438 },
439 "resources": map[string]interface{}{
440 "default": float64(1.1),
441 "minimum": float64(0.1),
442 "type": "number",
443 },
444 },
445 },
446 },
447 },
448 },
449 },
450 })
451 if err != nil {
452 t.Errorf("unexpected error: %v", err)
453 }
454 })
455 }