github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/util/strategicpatch/testing/openapi.go (about) 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 testing 18 19 import ( 20 "io/ioutil" 21 "os" 22 "sync" 23 24 openapi_v2 "github.com/google/gnostic/openapiv2" 25 openapi "k8s.io/kube-openapi/pkg/util/proto" 26 ) 27 28 // Fake opens and returns a openapi swagger from a file Path. It will 29 // parse only once and then return the same copy everytime. 30 type Fake struct { 31 Path string 32 33 once sync.Once 34 document *openapi_v2.Document 35 err error 36 } 37 38 // OpenAPISchema returns the openapi document and a potential error. 39 func (f *Fake) OpenAPISchema() (*openapi_v2.Document, error) { 40 f.once.Do(func() { 41 _, err := os.Stat(f.Path) 42 if err != nil { 43 f.err = err 44 return 45 } 46 spec, err := ioutil.ReadFile(f.Path) 47 if err != nil { 48 f.err = err 49 return 50 } 51 f.document, f.err = openapi_v2.ParseDocument(spec) 52 }) 53 return f.document, f.err 54 } 55 56 func getSchema(f *Fake, model string) (openapi.Schema, error) { 57 s, err := f.OpenAPISchema() 58 if err != nil { 59 return nil, err 60 } 61 m, err := openapi.NewOpenAPIData(s) 62 if err != nil { 63 return nil, err 64 } 65 return m.LookupModel(model), nil 66 } 67 68 // GetSchemaOrDie returns the openapi schema. 69 func GetSchemaOrDie(f *Fake, model string) openapi.Schema { 70 s, err := getSchema(f, model) 71 if err != nil { 72 panic(err) 73 } 74 return s 75 }