forked from ericchiang/k8s
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch_test.go
109 lines (94 loc) · 2.58 KB
/
watch_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package k8s_test
import (
"context"
"reflect"
"testing"
"github.com/ericchiang/k8s"
corev1 "github.com/ericchiang/k8s/apis/core/v1"
metav1 "github.com/ericchiang/k8s/apis/meta/v1"
)
// configMapJSON is used to test the JSON serialization watch.
type configMapJSON struct {
Metadata *metav1.ObjectMeta `json:"metadata"`
Data map[string]string `json:"data"`
}
func (c *configMapJSON) GetMetadata() *metav1.ObjectMeta {
return c.Metadata
}
func init() {
k8s.Register("", "v1", "configmaps", true, &configMapJSON{})
}
func testWatch(t *testing.T, client *k8s.Client, namespace string, newCM func() k8s.Resource, update func(cm k8s.Resource)) {
w, err := client.Watch(context.TODO(), namespace, newCM())
if err != nil {
t.Errorf("watch configmaps: %v", err)
}
defer w.Close()
cm := newCM()
want := func(eventType string) {
got := newCM()
eT, err := w.Next(got)
if err != nil {
t.Errorf("decode watch event: %v", err)
return
}
if eT != eventType {
t.Errorf("expected event type %q got %q", eventType, eT)
}
cm.GetMetadata().ResourceVersion = k8s.String("")
got.GetMetadata().ResourceVersion = k8s.String("")
if !reflect.DeepEqual(got, cm) {
t.Errorf("configmaps didn't match")
t.Errorf("want: %#v", cm)
t.Errorf(" got: %#v", got)
}
}
if err := client.Create(context.TODO(), cm); err != nil {
t.Errorf("create configmap: %v", err)
return
}
want(k8s.EventAdded)
update(cm)
if err := client.Update(context.TODO(), cm); err != nil {
t.Errorf("update configmap: %v", err)
return
}
want(k8s.EventModified)
if err := client.Delete(context.TODO(), cm); err != nil {
t.Errorf("Delete configmap: %v", err)
return
}
want(k8s.EventDeleted)
}
func TestWatchConfigMapJSON(t *testing.T) {
withNamespace(t, func(client *k8s.Client, namespace string) {
newCM := func() k8s.Resource {
return &configMapJSON{
Metadata: &metav1.ObjectMeta{
Name: k8s.String("my-configmap"),
Namespace: &namespace,
},
}
}
updateCM := func(cm k8s.Resource) {
(cm.(*configMapJSON)).Data = map[string]string{"hello": "world"}
}
testWatch(t, client, namespace, newCM, updateCM)
})
}
func TestWatchConfigMapProto(t *testing.T) {
withNamespace(t, func(client *k8s.Client, namespace string) {
newCM := func() k8s.Resource {
return &corev1.ConfigMap{
Metadata: &metav1.ObjectMeta{
Name: k8s.String("my-configmap"),
Namespace: &namespace,
},
}
}
updateCM := func(cm k8s.Resource) {
(cm.(*corev1.ConfigMap)).Data = map[string]string{"hello": "world"}
}
testWatch(t, client, namespace, newCM, updateCM)
})
}