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