Debian Codegraph @

rest/watch/encoder_test.go

raw
1 /*
2 Copyright 2014 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 watch
18
19 import (
20 "bytes"
21 "io"
22 "testing"
23
24 v1 "k8s.io/api/core/v1"
25 apiequality "k8s.io/apimachinery/pkg/api/equality"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/runtime"
28 runtimejson "k8s.io/apimachinery/pkg/runtime/serializer/json"
29 "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
30 "k8s.io/apimachinery/pkg/watch"
31 "k8s.io/client-go/kubernetes/scheme"
32 )
33
34 // getEncoder mimics how k8s.io/client-go/rest.createSerializers creates a encoder
35 func getEncoder() runtime.Encoder {
36 jsonSerializer := runtimejson.NewSerializerWithOptions(runtimejson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, runtimejson.SerializerOptions{})
37 directCodecFactory := scheme.Codecs.WithoutConversion()
38 return directCodecFactory.EncoderForVersion(jsonSerializer, v1.SchemeGroupVersion)
39 }
40
41 func TestEncodeDecodeRoundTrip(t *testing.T) {
42 testCases := []struct {
43 Type watch.EventType
44 Object runtime.Object
45 }{
46 {
47 watch.Added,
48 &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}},
49 },
50 {
51 watch.Modified,
52 &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}},
53 },
54 {
55 watch.Deleted,
56 &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}},
57 },
58 {
59 watch.Bookmark,
60 &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}},
61 },
62 }
63 for i, testCase := range testCases {
64 buf := &bytes.Buffer{}
65
66 encoder := NewEncoder(streaming.NewEncoder(buf, getEncoder()), getEncoder())
67 if err := encoder.Encode(&watch.Event{Type: testCase.Type, Object: testCase.Object}); err != nil {
68 t.Errorf("%d: unexpected error: %v", i, err)
69 continue
70 }
71
72 rc := io.NopCloser(buf)
73 decoder := NewDecoder(streaming.NewDecoder(rc, getDecoder()), getDecoder())
74 event, obj, err := decoder.Decode()
75 if err != nil {
76 t.Errorf("%d: unexpected error: %v", i, err)
77 continue
78 }
79 if !apiequality.Semantic.DeepDerivative(testCase.Object, obj) {
80 t.Errorf("%d: expected %#v, got %#v", i, testCase.Object, obj)
81 }
82 if event != testCase.Type {
83 t.Errorf("%d: unexpected type: %#v", i, event)
84 }
85 }
86 }