Debian Codegraph @

pkg/endpoints/handlers/response_test.go

raw
1 /*
2 Copyright 2019 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 handlers
18
19 import (
20 "bytes"
21 "context"
22 "encoding/base64"
23 "fmt"
24 "io"
25 "net/http"
26 "reflect"
27 "testing"
28 "time"
29
30 v1 "k8s.io/api/core/v1"
31 "k8s.io/apimachinery/pkg/api/meta"
32 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
33 metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
34 "k8s.io/apimachinery/pkg/runtime"
35 "k8s.io/apimachinery/pkg/runtime/schema"
36 runtimejson "k8s.io/apimachinery/pkg/runtime/serializer/json"
37 "k8s.io/apimachinery/pkg/watch"
38 examplev1 "k8s.io/apiserver/pkg/apis/example/v1"
39 "k8s.io/apiserver/pkg/endpoints/request"
40 "k8s.io/apiserver/pkg/registry/rest"
41 clientgoscheme "k8s.io/client-go/kubernetes/scheme"
42 )
43
44 var _ runtime.CacheableObject = &mockCacheableObject{}
45
46 type mockCacheableObject struct {
47 gvk schema.GroupVersionKind
48 obj runtime.Object
49 }
50
51 // DeepCopyObject implements runtime.Object interface.
52 func (m *mockCacheableObject) DeepCopyObject() runtime.Object {
53 panic("DeepCopy unimplemented for mockCacheableObject")
54 }
55
56 // GetObjectKind implements runtime.Object interface.
57 func (m *mockCacheableObject) GetObjectKind() schema.ObjectKind {
58 return m
59 }
60
61 // GroupVersionKind implements schema.ObjectKind interface.
62 func (m *mockCacheableObject) GroupVersionKind() schema.GroupVersionKind {
63 return m.gvk
64 }
65
66 // SetGroupVersionKind implements schema.ObjectKind interface.
67 func (m *mockCacheableObject) SetGroupVersionKind(gvk schema.GroupVersionKind) {
68 m.gvk = gvk
69 }
70
71 // CacheEncode implements runtime.CacheableObject interface.
72 func (m *mockCacheableObject) CacheEncode(id runtime.Identifier, encode func(runtime.Object, io.Writer) error, w io.Writer) error {
73 return encode(m.obj.DeepCopyObject(), w)
74 }
75
76 // GetObject implements runtime.CacheableObject interface.
77 func (m *mockCacheableObject) GetObject() runtime.Object {
78 return m.obj
79 }
80
81 type mockNamer struct{}
82
83 func (*mockNamer) Namespace(_ *http.Request) (string, error) { return "", nil }
84 func (*mockNamer) Name(_ *http.Request) (string, string, error) { return "", "", nil }
85 func (*mockNamer) ObjectName(_ runtime.Object) (string, string, error) { return "", "", nil }
86
87 type mockEncoder struct {
88 obj runtime.Object
89 }
90
91 func (e *mockEncoder) Encode(obj runtime.Object, _ io.Writer) error {
92 e.obj = obj
93 return nil
94 }
95
96 func (e *mockEncoder) Identifier() runtime.Identifier {
97 return runtime.Identifier("")
98 }
99
100 func TestCacheableObject(t *testing.T) {
101 pomGVK := metav1.SchemeGroupVersion.WithKind("PartialObjectMetadata")
102 tableGVK := metav1.SchemeGroupVersion.WithKind("Table")
103
104 status := &metav1.Status{Status: "status"}
105 pod := &examplev1.Pod{
106 ObjectMeta: metav1.ObjectMeta{
107 Name: "name",
108 Namespace: "namespace",
109 },
110 }
111 podMeta := &metav1.PartialObjectMetadata{
112 ObjectMeta: metav1.ObjectMeta{
113 Name: "name",
114 Namespace: "namespace",
115 },
116 }
117 podMeta.GetObjectKind().SetGroupVersionKind(pomGVK)
118 podTable := &metav1.Table{
119 Rows: []metav1.TableRow{
120 {
121 Cells: []interface{}{pod.Name, pod.CreationTimestamp.Time.UTC().Format(time.RFC3339)},
122 },
123 },
124 }
125
126 tableConvertor := rest.NewDefaultTableConvertor(examplev1.Resource("Pod"))
127
128 testCases := []struct {
129 desc string
130 object runtime.Object
131 opts *metav1beta1.TableOptions
132 target *schema.GroupVersionKind
133
134 expectedUnwrap bool
135 expectedObj runtime.Object
136 expectedErr error
137 }{
138 {
139 desc: "metav1.Status",
140 object: status,
141 expectedObj: status,
142 expectedErr: nil,
143 },
144 {
145 desc: "cacheableObject nil convert",
146 object: &mockCacheableObject{obj: pod},
147 target: nil,
148 expectedObj: pod,
149 expectedErr: nil,
150 },
151 {
152 desc: "cacheableObject as PartialObjectMeta",
153 object: &mockCacheableObject{obj: pod},
154 target: &pomGVK,
155 expectedObj: podMeta,
156 expectedErr: nil,
157 },
158 {
159 desc: "cacheableObject as Table",
160 object: &mockCacheableObject{obj: pod},
161 opts: &metav1beta1.TableOptions{NoHeaders: true, IncludeObject: metav1.IncludeNone},
162 target: &tableGVK,
163 expectedObj: podTable,
164 expectedErr: nil,
165 },
166 }
167
168 for _, test := range testCases {
169 t.Run(test.desc, func(t *testing.T) {
170 internalEncoder := &mockEncoder{}
171 watchEncoder := newWatchEmbeddedEncoder(
172 request.WithRequestInfo(context.TODO(), &request.RequestInfo{}),
173 internalEncoder, test.target, test.opts,
174 &RequestScope{
175 Namer: &mockNamer{},
176 TableConvertor: tableConvertor,
177 },
178 )
179
180 err := watchEncoder.Encode(test.object, nil)
181 if err != test.expectedErr {
182 t.Errorf("unexpected error: %v, expected: %v", err, test.expectedErr)
183 }
184 if a, e := internalEncoder.obj, test.expectedObj; !reflect.DeepEqual(a, e) {
185 t.Errorf("unexpected result: %#v, expected: %#v", a, e)
186 }
187 })
188 }
189 }
190
191 func TestAsPartialObjectMetadataList(t *testing.T) {
192 var remainingItemCount int64 = 10
193 pods := &examplev1.PodList{
194 ListMeta: metav1.ListMeta{
195 ResourceVersion: "10",
196 Continue: "continuetoken",
197 RemainingItemCount: &remainingItemCount,
198 },
199 }
200
201 pomGVs := []schema.GroupVersion{metav1beta1.SchemeGroupVersion, metav1.SchemeGroupVersion}
202 for _, gv := range pomGVs {
203 t.Run(fmt.Sprintf("as %s PartialObjectMetadataList", gv), func(t *testing.T) {
204 list, err := asPartialObjectMetadataList(pods, gv)
205 if err != nil {
206 t.Fatalf("failed to transform object: %v", err)
207 }
208
209 var listMeta metav1.ListMeta
210 switch gv {
211 case metav1beta1.SchemeGroupVersion:
212 listMeta = list.(*metav1beta1.PartialObjectMetadataList).ListMeta
213 case metav1.SchemeGroupVersion:
214 listMeta = list.(*metav1.PartialObjectMetadataList).ListMeta
215 }
216 if !reflect.DeepEqual(pods.ListMeta, listMeta) {
217 t.Errorf("unexpected list metadata: %v, expected: %v", listMeta, pods.ListMeta)
218 }
219 })
220 }
221 }
222
223 func TestWatchEncoderIdentifier(t *testing.T) {
224 eventFields := reflect.VisibleFields(reflect.TypeOf(metav1.WatchEvent{}))
225 if len(eventFields) != 2 {
226 t.Error("New field was added to metav1.WatchEvent.")
227 t.Error(" Ensure that the following places are updated accordingly:")
228 t.Error(" - watchEncoder::doEncode method when creating outEvent")
229 t.Error(" - watchEncoder::typeIdentifier to capture all relevant fields in identifier")
230 }
231 }
232
233 func TestWatchListEncoder(t *testing.T) {
234 makePartialObjectMetadataListWithoutKind := func(rv string) *metav1.PartialObjectMetadataList {
235 return &metav1.PartialObjectMetadataList{
236 // do not set the type info to match
237 // newWatchListTransformer
238 ListMeta: metav1.ListMeta{ResourceVersion: rv},
239 }
240 }
241 makePodListWithKind := func(rv string) *v1.PodList {
242 return &v1.PodList{
243 TypeMeta: metav1.TypeMeta{
244 // set the type info so
245 // that it differs from
246 // PartialObjectMetadataList
247 Kind: "PodList",
248 },
249 ListMeta: metav1.ListMeta{
250 ResourceVersion: rv,
251 },
252 }
253 }
254 makeBookmarkEventFor := func(pod *v1.Pod) watch.Event {
255 return watch.Event{
256 Type: watch.Bookmark,
257 Object: pod,
258 }
259 }
260 makePod := func(name string) *v1.Pod {
261 return &v1.Pod{
262 ObjectMeta: metav1.ObjectMeta{
263 Name: name,
264 Namespace: "ns",
265 Annotations: map[string]string{},
266 },
267 }
268 }
269 makePodWithInitialEventsAnnotation := func(name string) *v1.Pod {
270 p := makePod(name)
271 p.Annotations[metav1.InitialEventsAnnotationKey] = "true"
272 return p
273 }
274
275 scenarios := []struct {
276 name string
277 negotiatedEncoder runtime.Serializer
278 targetGVK *schema.GroupVersionKind
279
280 actualEvent watch.Event
281 listBlueprint runtime.Object
282
283 expectedBase64ListBlueprint string
284 }{
285 {
286 name: "pass through, an obj without the annotation received",
287 actualEvent: makeBookmarkEventFor(makePod("1")),
288 negotiatedEncoder: newJSONSerializer(),
289 },
290 {
291 name: "encodes the initialEventsListBlueprint if an obj with the annotation is passed",
292 actualEvent: makeBookmarkEventFor(makePodWithInitialEventsAnnotation("1")),
293 listBlueprint: makePodListWithKind("100"),
294 expectedBase64ListBlueprint: encodeObjectToBase64String(makePodListWithKind("100"), t),
295 negotiatedEncoder: newJSONSerializer(),
296 },
297 {
298 name: "encodes the initialEventsListBlueprint as PartialObjectMetadata when requested",
299 targetGVK: &schema.GroupVersionKind{Group: "meta.k8s.io", Version: "v1", Kind: "PartialObjectMetadata"},
300 actualEvent: makeBookmarkEventFor(makePodWithInitialEventsAnnotation("2")),
301 listBlueprint: makePodListWithKind("101"),
302 expectedBase64ListBlueprint: encodeObjectToBase64String(makePartialObjectMetadataListWithoutKind("101"), t),
303 negotiatedEncoder: newJSONSerializer(),
304 },
305 }
306
307 for _, scenario := range scenarios {
308 t.Run(scenario.name, func(t *testing.T) {
309 target := newWatchListTransformer(scenario.listBlueprint, scenario.targetGVK, scenario.negotiatedEncoder)
310 transformedEvent := target.transform(scenario.actualEvent)
311
312 actualObjectMeta, err := meta.Accessor(transformedEvent.Object)
313 if err != nil {
314 t.Fatal(err)
315 }
316
317 base64ListBlueprint, ok := actualObjectMeta.GetAnnotations()[metav1.InitialEventsListBlueprintAnnotationKey]
318 if !ok && len(scenario.expectedBase64ListBlueprint) != 0 {
319 t.Fatalf("the encoded obj doesn't have %q", metav1.InitialEventsListBlueprintAnnotationKey)
320 }
321 if base64ListBlueprint != scenario.expectedBase64ListBlueprint {
322 t.Fatalf("unexpected base64ListBlueprint = %s, expected = %s", base64ListBlueprint, scenario.expectedBase64ListBlueprint)
323 }
324 })
325 }
326 }
327
328 func encodeObjectToBase64String(obj runtime.Object, t *testing.T) string {
329 e := newJSONSerializer()
330
331 var buf bytes.Buffer
332 err := e.Encode(obj, &buf)
333 if err != nil {
334 t.Fatal(err)
335 }
336 return base64.StdEncoding.EncodeToString(buf.Bytes())
337 }
338
339 func newJSONSerializer() runtime.Serializer {
340 return runtimejson.NewSerializerWithOptions(
341 runtimejson.DefaultMetaFactory,
342 clientgoscheme.Scheme,
343 clientgoscheme.Scheme,
344 runtimejson.SerializerOptions{},
345 )
346 }