File: dryrun_test.go

package info (click to toggle)
golang-k8s-apiserver 0.33.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,660 kB
  • sloc: sh: 236; makefile: 5
file content (309 lines) | stat: -rw-r--r-- 10,274 bytes parent folder | download
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package registry

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
	"testing"

	"k8s.io/apimachinery/pkg/api/apitesting"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	examplev1 "k8s.io/apiserver/pkg/apis/example/v1"
	"k8s.io/apiserver/pkg/registry/rest"
	"k8s.io/apiserver/pkg/storage"
	etcd3testing "k8s.io/apiserver/pkg/storage/etcd3/testing"
	"k8s.io/apiserver/pkg/storage/storagebackend/factory"
)

func NewDryRunnableTestStorage(t *testing.T) (DryRunnableStorage, func()) {
	server, sc := etcd3testing.NewUnsecuredEtcd3TestClientServer(t)
	sc.Codec = apitesting.TestStorageCodec(codecs, examplev1.SchemeGroupVersion)
	s, destroy, err := factory.Create(*sc.ForResource(schema.GroupResource{Resource: "pods"}), nil, nil, "")
	if err != nil {
		t.Fatalf("Error creating storage: %v", err)
	}
	return DryRunnableStorage{Storage: s, Codec: sc.Codec}, func() {
		destroy()
		server.Terminate(t)
	}
}

func UnstructuredOrDie(j string) *unstructured.Unstructured {
	m := map[string]interface{}{}
	err := json.Unmarshal([]byte(j), &m)
	if err != nil {
		panic(fmt.Errorf("Failed to unmarshal into Unstructured: %v", err))
	}
	return &unstructured.Unstructured{Object: m}
}

func TestDryRunCreateDoesntCreate(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, true)
	if err != nil {
		t.Fatalf("Failed to create new dry-run object: %v", err)
	}

	err = s.Get(context.Background(), "key", storage.GetOptions{}, out)
	if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyNotFound {
		t.Errorf("Expected key to be not found, error: %v", err)
	}
}

func TestDryRunCreateReturnsObject(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, true)
	if err != nil {
		t.Fatalf("Failed to create new dry-run object: %v", err)
	}

	if !reflect.DeepEqual(obj, out) {
		t.Errorf("Returned object different from input object:\nExpected: %v\nGot: %v", obj, out)
	}
}

func TestDryRunCreateExistingObjectFails(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	err = s.Create(context.Background(), "key", obj, out, 0, true)
	if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyExists {
		t.Errorf("Expected KeyExists error: %v", err)
	}

}

func TestDryRunUpdateMissingObjectFails(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)

	updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) {
		return input, nil, errors.New("UpdateFunction shouldn't be called")
	}

	err := s.GuaranteedUpdate(context.Background(), "key", obj, false, nil, updateFunc, true, nil)
	if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyNotFound {
		t.Errorf("Expected key to be not found, error: %v", err)
	}
}

func TestDryRunUpdatePreconditions(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod", "metadata": {"uid": "my-uid"}}`)
	out := UnstructuredOrDie(`{}`)
	err := s.Create(context.Background(), "key", obj, out, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) {
		u, ok := input.(*unstructured.Unstructured)
		if !ok {
			return input, nil, errors.New("Input object is not unstructured")
		}
		unstructured.SetNestedField(u.Object, "value", "field")
		return u, nil, nil
	}
	wrongID := types.UID("wrong-uid")
	myID := types.UID("my-uid")
	err = s.GuaranteedUpdate(context.Background(), "key", obj, false, &storage.Preconditions{UID: &wrongID}, updateFunc, true, nil)
	if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeInvalidObj {
		t.Errorf("Expected invalid object, error: %v", err)
	}

	err = s.GuaranteedUpdate(context.Background(), "key", obj, false, &storage.Preconditions{UID: &myID}, updateFunc, true, nil)
	if err != nil {
		t.Fatalf("Failed to update with valid precondition: %v", err)
	}
}

func TestDryRunUpdateDoesntUpdate(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	created := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, created, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) {
		u, ok := input.(*unstructured.Unstructured)
		if !ok {
			return input, nil, errors.New("Input object is not unstructured")
		}
		unstructured.SetNestedField(u.Object, "value", "field")
		return u, nil, nil
	}

	err = s.GuaranteedUpdate(context.Background(), "key", obj, false, nil, updateFunc, true, nil)
	if err != nil {
		t.Fatalf("Failed to dry-run update: %v", err)
	}
	out := UnstructuredOrDie(`{}`)
	err = s.Get(context.Background(), "key", storage.GetOptions{}, out)
	if err != nil {
		t.Fatalf("Failed to get storage: %v", err)
	}
	if !reflect.DeepEqual(created, out) {
		t.Fatalf("Returned object %q different from expected %q", created, out)
	}
}

func TestDryRunUpdateReturnsObject(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	updateFunc := func(input runtime.Object, res storage.ResponseMeta) (output runtime.Object, ttl *uint64, err error) {
		u, ok := input.(*unstructured.Unstructured)
		if !ok {
			return input, nil, errors.New("Input object is not unstructured")
		}
		unstructured.SetNestedField(u.Object, "value", "field")
		return u, nil, nil
	}

	err = s.GuaranteedUpdate(context.Background(), "key", obj, false, nil, updateFunc, true, nil)
	if err != nil {
		t.Fatalf("Failed to dry-run update: %v", err)
	}
	out = UnstructuredOrDie(`{"field": "value", "kind": "Pod", "metadata": {"resourceVersion": "2"}}`)
	if !reflect.DeepEqual(obj, out) {
		t.Fatalf("Returned object %#v different from expected %#v", obj, out)
	}
}

func TestDryRunDeleteDoesntDelete(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	err = s.Delete(context.Background(), "key", out, nil, rest.ValidateAllObjectFunc, true, nil, storage.DeleteOptions{})
	if err != nil {
		t.Fatalf("Failed to dry-run delete the object: %v", err)
	}

	err = s.Get(context.Background(), "key", storage.GetOptions{}, out)
	if err != nil {
		t.Fatalf("Failed to retrieve dry-run deleted object: %v", err)
	}
}

func TestDryRunDeleteMissingObjectFails(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	out := UnstructuredOrDie(`{}`)
	err := s.Delete(context.Background(), "key", out, nil, rest.ValidateAllObjectFunc, true, nil, storage.DeleteOptions{})
	if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeKeyNotFound {
		t.Errorf("Expected key to be not found, error: %v", err)
	}
}

func TestDryRunDeleteReturnsObject(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod"}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	out = UnstructuredOrDie(`{}`)
	expected := UnstructuredOrDie(`{"kind": "Pod", "metadata": {"resourceVersion": "2"}}`)
	err = s.Delete(context.Background(), "key", out, nil, rest.ValidateAllObjectFunc, true, nil, storage.DeleteOptions{})
	if err != nil {
		t.Fatalf("Failed to delete with valid precondition: %v", err)
	}
	if !reflect.DeepEqual(expected, out) {
		t.Fatalf("Returned object %q doesn't match expected: %q", out, expected)
	}
}

func TestDryRunDeletePreconditions(t *testing.T) {
	s, destroy := NewDryRunnableTestStorage(t)
	defer destroy()

	obj := UnstructuredOrDie(`{"kind": "Pod", "metadata": {"uid": "my-uid"}}`)
	out := UnstructuredOrDie(`{}`)

	err := s.Create(context.Background(), "key", obj, out, 0, false)
	if err != nil {
		t.Fatalf("Failed to create new object: %v", err)
	}

	wrongID := types.UID("wrong-uid")
	myID := types.UID("my-uid")
	err = s.Delete(context.Background(), "key", out, &storage.Preconditions{UID: &wrongID}, rest.ValidateAllObjectFunc, true, nil, storage.DeleteOptions{})
	if e, ok := err.(*storage.StorageError); !ok || e.Code != storage.ErrCodeInvalidObj {
		t.Errorf("Expected invalid object, error: %v", err)
	}

	err = s.Delete(context.Background(), "key", out, &storage.Preconditions{UID: &myID}, rest.ValidateAllObjectFunc, true, nil, storage.DeleteOptions{})
	if err != nil {
		t.Fatalf("Failed to delete with valid precondition: %v", err)
	}
}