1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package openapi_test
18
19import (
20	"fmt"
21
22	openapi_v2 "github.com/googleapis/gnostic/openapiv2"
23	. "github.com/onsi/ginkgo"
24	. "github.com/onsi/gomega"
25
26	"k8s.io/kubectl/pkg/util/openapi"
27)
28
29// FakeCounter returns a "null" document and the specified error. It
30// also counts how many times the OpenAPISchema method has been called.
31type FakeCounter struct {
32	Calls int
33	Err   error
34}
35
36func (f *FakeCounter) OpenAPISchema() (*openapi_v2.Document, error) {
37	f.Calls = f.Calls + 1
38	return nil, f.Err
39}
40
41var _ = Describe("Getting the Resources", func() {
42	var client FakeCounter
43	var instance openapi.Getter
44	var expectedData openapi.Resources
45
46	BeforeEach(func() {
47		client = FakeCounter{}
48		instance = openapi.NewOpenAPIGetter(&client)
49		var err error
50		expectedData, err = openapi.NewOpenAPIData(nil)
51		Expect(err).To(BeNil())
52	})
53
54	Context("when the server returns a successful result", func() {
55		It("should return the same data for multiple calls", func() {
56			Expect(client.Calls).To(Equal(0))
57
58			result, err := instance.Get()
59			Expect(err).To(BeNil())
60			Expect(result).To(Equal(expectedData))
61			Expect(client.Calls).To(Equal(1))
62
63			result, err = instance.Get()
64			Expect(err).To(BeNil())
65			Expect(result).To(Equal(expectedData))
66			// No additional client calls expected
67			Expect(client.Calls).To(Equal(1))
68		})
69	})
70
71	Context("when the server returns an unsuccessful result", func() {
72		It("should return the same instance for multiple calls.", func() {
73			Expect(client.Calls).To(Equal(0))
74
75			client.Err = fmt.Errorf("expected error")
76			_, err := instance.Get()
77			Expect(err).To(Equal(client.Err))
78			Expect(client.Calls).To(Equal(1))
79
80			_, err = instance.Get()
81			Expect(err).To(Equal(client.Err))
82			// No additional client calls expected
83			Expect(client.Calls).To(Equal(1))
84		})
85	})
86})
87