blob: 3f0a5d05fc66c5744e7ee6a010c3ff59bb68a63a [file] [log] [blame]
Serge Bazanskibe538db2020-11-12 00:22:42 +01001// Copyright 2017 The kubecfg authors
2//
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
16package utils
17
18import (
19 "io/ioutil"
20 "path/filepath"
21 "strings"
22 "testing"
23
24 "github.com/golang/protobuf/proto"
25 openapi_v2 "github.com/googleapis/gnostic/openapiv2"
26 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
27 "k8s.io/apimachinery/pkg/runtime/schema"
28 utilerrors "k8s.io/apimachinery/pkg/util/errors"
29)
30
31type schemaFromFile struct {
32 dir string
33}
34
35func (s schemaFromFile) OpenAPISchema() (*openapi_v2.Document, error) {
36 var doc openapi_v2.Document
37 b, err := ioutil.ReadFile(filepath.Join(s.dir, "schema.pb"))
38 if err != nil {
39 return nil, err
40 }
41 if err := proto.Unmarshal(b, &doc); err != nil {
42 return nil, err
43 }
44 return &doc, nil
45}
46
47func TestValidate(t *testing.T) {
48 schemaReader := schemaFromFile{dir: filepath.FromSlash("../testdata")}
49 s, err := NewOpenAPISchemaFor(schemaReader, schema.GroupVersionKind{Version: "v1", Kind: "Service"})
50 if err != nil {
51 t.Fatalf("Error reading schema: %v", err)
52 }
53
54 valid := &unstructured.Unstructured{
55 Object: map[string]interface{}{
56 "apiVersion": "v1",
57 "kind": "Service",
58 "spec": map[string]interface{}{
59 "ports": []interface{}{
60 map[string]interface{}{"port": 80},
61 },
62 },
63 },
64 }
65 if errs := s.Validate(valid); len(errs) != 0 {
66 t.Errorf("schema errors from valid object: %v", errs)
67 }
68
69 invalid := &unstructured.Unstructured{
70 Object: map[string]interface{}{
71 "apiVersion": "v1",
72 "kind": "Service",
73 "spec": map[string]interface{}{
74 "bogus": false,
75 "ports": []interface{}{
76 map[string]interface{}{"port": "bogus"},
77 },
78 },
79 },
80 }
81 errs := s.Validate(invalid)
82 if len(errs) == 0 {
83 t.Error("no schema errors from invalid object :(")
84 }
85 err = utilerrors.NewAggregate(errs)
86 t.Logf("Invalid object produced error: %v", err)
87
88 if !strings.Contains(err.Error(), `invalid type for io.k8s.api.core.v1.ServicePort.port: got "string", expected "integer"`) {
89 t.Errorf("Wrong error1 produced from invalid object: %v", err)
90 }
91 if !strings.Contains(err.Error(), `ValidationError(v1.Service.spec): unknown field "bogus" in io.k8s.api.core.v1.ServiceSpec`) {
92 t.Errorf("Wrong error2 produced from invalid object: %q", err)
93 }
94}