openapi.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package testing
  14. import (
  15. "io/ioutil"
  16. "os"
  17. "sync"
  18. yaml "gopkg.in/yaml.v2"
  19. "github.com/googleapis/gnostic/OpenAPIv2"
  20. "github.com/googleapis/gnostic/compiler"
  21. )
  22. // Fake opens and returns a openapi swagger from a file Path. It will
  23. // parse only once and then return the same copy everytime.
  24. type Fake struct {
  25. Path string
  26. once sync.Once
  27. document *openapi_v2.Document
  28. err error
  29. }
  30. // OpenAPISchema returns the openapi document and a potential error.
  31. func (f *Fake) OpenAPISchema() (*openapi_v2.Document, error) {
  32. f.once.Do(func() {
  33. _, err := os.Stat(f.Path)
  34. if err != nil {
  35. f.err = err
  36. return
  37. }
  38. spec, err := ioutil.ReadFile(f.Path)
  39. if err != nil {
  40. f.err = err
  41. return
  42. }
  43. var info yaml.MapSlice
  44. err = yaml.Unmarshal(spec, &info)
  45. if err != nil {
  46. f.err = err
  47. return
  48. }
  49. f.document, f.err = openapi_v2.NewDocument(info, compiler.NewContext("$root", nil))
  50. })
  51. return f.document, f.err
  52. }
  53. type Empty struct{}
  54. func (Empty) OpenAPISchema() (*openapi_v2.Document, error) {
  55. return nil, nil
  56. }