forked from ironcore-dev/controller-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientutils_test.go
More file actions
892 lines (774 loc) · 27.5 KB
/
clientutils_test.go
File metadata and controls
892 lines (774 loc) · 27.5 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
// SPDX-FileCopyrightText: 2023 SAP SE or an SAP affiliate company and IronCore contributors
// SPDX-License-Identifier: Apache-2.0
package clientutils_test
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
. "github.com/ironcore-dev/controller-utils/clientutils"
mockclient "github.com/ironcore-dev/controller-utils/mock/controller-runtime/client"
mockclientutils "github.com/ironcore-dev/controller-utils/mock/controller-utils/clientutils"
"github.com/ironcore-dev/controller-utils/testdata"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/stretchr/testify/mock"
"go.uber.org/mock/gomock"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
var _ = Describe("Clientutils", func() {
const (
objectsPath = "../testdata/bases/objects.yaml"
finalizer = "my-finalizer"
)
var (
ctx context.Context
ctrl *gomock.Controller
c *mockclient.MockClient
cmGR schema.GroupResource
namespace string
cm *corev1.ConfigMap
cmKey client.ObjectKey
cmList *corev1.ConfigMapList
uPod *unstructured.Unstructured
secret *corev1.Secret
secretKey client.ObjectKey
patchProvider *mockclientutils.MockPatchProvider
)
BeforeEach(func() {
ctx = context.Background()
ctrl = gomock.NewController(GinkgoT())
c = mockclient.NewMockClient(ctrl)
cmGR = schema.GroupResource{Group: corev1.GroupName, Resource: "configmaps"}
namespace = corev1.NamespaceDefault
cm = &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: "my-cm",
},
}
cmKey = client.ObjectKeyFromObject(cm)
cmList = &corev1.ConfigMapList{
Items: []corev1.ConfigMap{*cm},
}
uPod = &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "Pod",
"metadata": map[string]interface{}{
"namespace": namespace,
"name": "my-pod",
},
},
}
secret = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: "my-secret",
},
}
secretKey = client.ObjectKeyFromObject(secret)
patchProvider = mockclientutils.NewMockPatchProvider(ctrl)
})
Describe("ReaderClient", func() {
It("should return a client that dispatches methods correctly", func() {
r := mockclient.NewMockClient(ctrl)
gomock.InOrder(
r.EXPECT().Get(ctx, cmKey, cm),
r.EXPECT().List(ctx, cmList),
c.EXPECT().Delete(ctx, cm),
)
rc := ReaderClient(r, c)
Expect(rc.Get(ctx, cmKey, cm)).To(Succeed())
Expect(rc.List(ctx, cmList)).To(Succeed())
Expect(rc.Delete(ctx, cm)).To(Succeed())
})
})
Describe("IgnoreAlreadyExists", func() {
It("should ignore already exists errors", func() {
alreadyExistsErr := IgnoreAlreadyExists(apierrors.NewAlreadyExists(cmGR, ""))
Expect(IgnoreAlreadyExists(alreadyExistsErr)).To(Succeed())
})
It("should not ignore other errors or nil", func() {
err := fmt.Errorf("some error")
Expect(IgnoreAlreadyExists(err)).To(BeIdenticalTo(err))
Expect(IgnoreAlreadyExists(nil)).To(Succeed())
})
})
Describe("CreateMultipleFromFile", func() {
It("should error if the file does not exist", func() {
_, err := CreateMultipleFromFile(ctx, c, "should-not-exist")
Expect(err).To(HaveOccurred())
})
It("should abort and return any error from creating", func() {
someErr := fmt.Errorf("some error")
c.EXPECT().Create(ctx, testdata.UnstructuredSecret()).Return(someErr)
_, err := CreateMultipleFromFile(ctx, c, objectsPath)
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should create the given objects from the file", func() {
gomock.InOrder(
c.EXPECT().Create(ctx, testdata.UnstructuredSecret()),
c.EXPECT().Create(ctx, testdata.UnstructuredConfigMap()),
)
objs, err := CreateMultipleFromFile(ctx, c, objectsPath)
Expect(err).NotTo(HaveOccurred())
Expect(objs).To(Equal(testdata.UnstructuredObjects()))
})
})
Describe("CreateMultiple", func() {
It("should abort and return any error from creating", func() {
someErr := fmt.Errorf("some error")
c.EXPECT().Create(ctx, cm).Return(someErr)
err := CreateMultiple(ctx, c, []client.Object{cm, secret})
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should create multiple objects", func() {
gomock.InOrder(
c.EXPECT().Create(ctx, cm),
c.EXPECT().Create(ctx, secret),
)
Expect(CreateMultiple(ctx, c, []client.Object{cm, secret})).To(Succeed())
})
})
Describe("GetRequestFromObject", func() {
It("should create a get request from the given object", func() {
Expect(GetRequestFromObject(cm)).To(Equal(GetRequest{
Key: cmKey,
Object: cm,
}))
})
})
Describe("GetRequestsFromObjects", func() {
It("should return nil if the requests are nil", func() {
Expect(GetRequestsFromObjects(nil)).To(BeNil())
})
It("should create get requests from the given objects", func() {
Expect(GetRequestsFromObjects([]client.Object{cm, secret})).To(Equal([]GetRequest{
{
Key: cmKey,
Object: cm,
},
{
Key: secretKey,
Object: secret,
},
}))
})
})
Describe("ObjectsFromGetRequests", func() {
It("should extract the objects from the get requests", func() {
Expect(ObjectsFromGetRequests([]GetRequest{
{
Key: cmKey,
Object: cm,
},
{
Key: secretKey,
Object: secret,
},
})).To(Equal([]client.Object{cm, secret}))
})
})
Context("GetRequestSet", func() {
Describe("NewGetRequestSet", func() {
It("should return a new get request set with the given items", func() {
s := NewGetRequestSet(GetRequestFromObject(cm), GetRequestFromObject(uPod))
Expect(s.Has(GetRequestFromObject(cm))).To(BeTrue())
Expect(s.Has(GetRequestFromObject(uPod))).To(BeTrue())
Expect(s.Len()).To(Equal(2))
})
})
Describe("Insert", func() {
It("should insert the given items into the set, deduping if necessary", func() {
s := NewGetRequestSet()
s.Insert(GetRequestFromObject(cm))
s.Insert(GetRequestFromObject(cm))
s.Insert(GetRequestFromObject(uPod))
s.Insert(GetRequestFromObject(uPod))
Expect(s.Has(GetRequestFromObject(cm))).To(BeTrue())
Expect(s.Has(GetRequestFromObject(uPod))).To(BeTrue())
Expect(s.Len()).To(Equal(2))
})
It("should panic if the object is typed but not a pointer to a struct", func() {
type BadConfigMap struct {
*corev1.ConfigMap
}
s := NewGetRequestSet()
Expect(func() {
s.Insert(GetRequestFromObject(BadConfigMap{cm}))
}).To(Panic())
})
It("should panic if the object is typed and a pointer but not to a struct", func() {
type BadObject struct {
client.Object
}
s := NewGetRequestSet()
Expect(func() {
s.Insert(GetRequestFromObject(&BadObject{client.Object(nil)}))
}).To(Panic())
})
})
Describe("Has", func() {
It("should determine whether the given item is present in the set", func() {
s := NewGetRequestSet(GetRequestFromObject(cm))
Expect(s.Has(GetRequestFromObject(cm))).To(BeTrue())
Expect(s.Has(GetRequestFromObject(uPod))).To(BeFalse())
})
})
Describe("Delete", func() {
It("should delete the item so it's not present anymore", func() {
s := NewGetRequestSet(GetRequestFromObject(cm))
Expect(s.Has(GetRequestFromObject(cm))).To(BeTrue())
Expect(s.Has(GetRequestFromObject(uPod))).To(BeFalse())
s.Delete(GetRequestFromObject(cm))
s.Delete(GetRequestFromObject(uPod))
Expect(s.Has(GetRequestFromObject(cm))).To(BeFalse())
Expect(s.Has(GetRequestFromObject(uPod))).To(BeFalse())
})
})
Describe("Iterate", func() {
It("should iterate through the entries in the set, stopping if requested (typed)", func() {
s := NewGetRequestSet(GetRequestFromObject(cm), GetRequestFromObject(secret))
var items []GetRequest
s.Iterate(func(request GetRequest) (cont bool) {
items = append(items, request)
return false
})
Expect(items).To(SatisfyAny(
Equal([]GetRequest{GetRequestFromObject(cm)}),
Equal([]GetRequest{GetRequestFromObject(secret)}),
))
})
It("should iterate through the entries in the set, stopping if requested (unstructured)", func() {
s := NewGetRequestSet(GetRequestFromObject(testdata.UnstructuredSecret()), GetRequestFromObject(testdata.UnstructuredConfigMap()))
var items []GetRequest
s.Iterate(func(request GetRequest) (cont bool) {
items = append(items, request)
return false
})
Expect(items).To(SatisfyAny(
Equal([]GetRequest{GetRequestFromObject(testdata.UnstructuredSecret())}),
Equal([]GetRequest{GetRequestFromObject(testdata.UnstructuredConfigMap())}),
))
})
It("should iterate through all elements if no stop is requested", func() {
s := NewGetRequestSet(GetRequestFromObject(cm), GetRequestFromObject(secret))
var items []GetRequest
s.Iterate(func(request GetRequest) (cont bool) {
items = append(items, request)
return true
})
Expect(items).To(ConsistOf(GetRequestFromObject(cm), GetRequestFromObject(secret)))
})
})
Describe("List", func() {
It("should contain all entries as a list", func() {
s := NewGetRequestSet(GetRequestFromObject(cm), GetRequestFromObject(uPod))
Expect(s.List()).To(ConsistOf(GetRequestFromObject(cm), GetRequestFromObject(uPod)))
})
})
})
Describe("GetMultiple", func() {
It("should abort and return any error from getting", func() {
someErr := fmt.Errorf("some error")
c.EXPECT().Get(ctx, cmKey, cm).Return(someErr)
err := GetMultiple(ctx, c, []GetRequest{GetRequestFromObject(cm), GetRequestFromObject(secret)})
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should get multiple referenced objects", func() {
gomock.InOrder(
c.EXPECT().Get(ctx, cmKey, cm),
c.EXPECT().Get(ctx, secretKey, secret),
)
Expect(GetMultiple(ctx, c, []GetRequest{
{
Key: cmKey,
Object: cm,
},
{
Key: secretKey,
Object: secret,
},
})).To(Succeed())
})
})
Describe("GetMultipleFromFile", func() {
It("should error if the file does not exist", func() {
_, err := GetMultipleFromFile(ctx, c, "should-not-exist")
Expect(err).To(HaveOccurred())
})
It("should abort and return any error from getting", func() {
someErr := fmt.Errorf("some error")
c.EXPECT().Get(ctx, client.ObjectKeyFromObject(testdata.UnstructuredSecret()), testdata.UnstructuredSecret()).Return(someErr)
_, err := GetMultipleFromFile(ctx, c, objectsPath)
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should get multiple referenced objects from file", func() {
gomock.InOrder(
c.EXPECT().Get(ctx, testdata.SecretKey(), testdata.UnstructuredSecret()),
c.EXPECT().Get(ctx, testdata.ConfigMapKey(), testdata.UnstructuredConfigMap()),
)
objs, err := GetMultipleFromFile(ctx, c, objectsPath)
Expect(err).NotTo(HaveOccurred())
Expect(objs).To(Equal(testdata.UnstructuredObjects()))
})
})
Describe("ApplyAll", func() {
It("should return an apply patch for any object", func() {
Expect(ApplyAll.PatchFor(cm).Type()).To(Equal(types.ApplyPatchType))
Expect(ApplyAll.PatchFor(secret).Type()).To(Equal(types.ApplyPatchType))
Expect(ApplyAll.PatchFor(uPod).Type()).To(Equal(types.ApplyPatchType))
})
})
Describe("PatchRequestFromObjectAndProvider", func() {
It("should create a patch request from the given object and provider", func() {
patchProvider.EXPECT().PatchFor(cm).Return(ApplyAll.PatchFor(cm))
Expect(PatchRequestFromObjectAndProvider(cm, patchProvider)).To(Equal(PatchRequest{
Object: cm,
Patch: ApplyAll.PatchFor(cm),
}))
})
})
Describe("PatchRequestsFromObjectsAndProvider", func() {
It("should return nil if the objects are nil", func() {
Expect(PatchRequestsFromObjectsAndProvider(nil, patchProvider)).To(BeNil())
})
It("should create patch requests from the given objects and provider", func() {
gomock.InOrder(
patchProvider.EXPECT().PatchFor(cm).Return(ApplyAll.PatchFor(cm)),
patchProvider.EXPECT().PatchFor(secret).Return(ApplyAll.PatchFor(secret)),
)
Expect(PatchRequestsFromObjectsAndProvider([]client.Object{cm, secret}, patchProvider)).To(Equal(
[]PatchRequest{
{
Object: cm,
Patch: ApplyAll.PatchFor(cm),
},
{
Object: secret,
Patch: ApplyAll.PatchFor(secret),
},
},
))
})
})
Describe("ObjectsFromPatchRequests", func() {
It("should return nil if the requests are nil", func() {
Expect(ObjectsFromPatchRequests(nil)).To(BeNil())
})
It("should retrieve all objects from the patch requests", func() {
reqs := []PatchRequest{
{
Object: cm,
Patch: ApplyAll.PatchFor(cm),
},
{
Object: secret,
Patch: ApplyAll.PatchFor(secret),
},
}
Expect(ObjectsFromPatchRequests(reqs)).To(Equal([]client.Object{cm, secret}))
})
})
Describe("PatchMultiple", func() {
It("should abort and return any error from patching", func() {
reqs := []PatchRequest{
{
Object: cm,
Patch: ApplyAll.PatchFor(cm),
},
{
Object: secret,
Patch: ApplyAll.PatchFor(secret),
},
}
someErr := fmt.Errorf("some error")
c.EXPECT().Patch(ctx, cm, ApplyAll.PatchFor(cm)).Return(someErr)
err := PatchMultiple(ctx, c, reqs)
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should patch multiple objects", func() {
reqs := []PatchRequest{
{
Object: cm,
Patch: ApplyAll.PatchFor(cm),
},
{
Object: secret,
Patch: ApplyAll.PatchFor(secret),
},
}
gomock.InOrder(
c.EXPECT().Patch(ctx, cm, ApplyAll.PatchFor(cm)),
c.EXPECT().Patch(ctx, secret, ApplyAll.PatchFor(secret)),
)
Expect(PatchMultiple(ctx, c, reqs)).To(Succeed())
})
})
Describe("PatchMultipleFromFile", func() {
It("should error if the file does not exist", func() {
_, err := PatchMultipleFromFile(ctx, c, "should-not-exist", patchProvider)
Expect(err).To(HaveOccurred())
})
It("should abort and return any error from patching", func() {
someErr := fmt.Errorf("some error")
gomock.InOrder(
patchProvider.EXPECT().PatchFor(testdata.UnstructuredSecret()).Return(ApplyAll.PatchFor(testdata.UnstructuredSecret())),
patchProvider.EXPECT().PatchFor(testdata.UnstructuredConfigMap()).Return(ApplyAll.PatchFor(testdata.UnstructuredConfigMap())),
c.EXPECT().Patch(ctx, testdata.UnstructuredSecret(), ApplyAll.PatchFor(testdata.UnstructuredSecret())).Return(someErr),
)
_, err := PatchMultipleFromFile(ctx, c, objectsPath, patchProvider)
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should patch multiple objects from file", func() {
gomock.InOrder(
patchProvider.EXPECT().PatchFor(testdata.UnstructuredSecret()).Return(ApplyAll.PatchFor(testdata.UnstructuredSecret())),
patchProvider.EXPECT().PatchFor(testdata.UnstructuredConfigMap()).Return(ApplyAll.PatchFor(testdata.UnstructuredConfigMap())),
c.EXPECT().Patch(ctx, testdata.UnstructuredSecret(), ApplyAll.PatchFor(testdata.UnstructuredSecret())),
c.EXPECT().Patch(ctx, testdata.UnstructuredConfigMap(), ApplyAll.PatchFor(testdata.UnstructuredConfigMap())),
)
objs, err := PatchMultipleFromFile(ctx, c, objectsPath, patchProvider)
Expect(err).NotTo(HaveOccurred())
Expect(objs).To(Equal([]unstructured.Unstructured{*testdata.UnstructuredSecret(), *testdata.UnstructuredConfigMap()}))
})
})
Describe("DeleteMultiple", func() {
It("should abort and return any error from deleting", func() {
someErr := fmt.Errorf("some error")
c.EXPECT().Delete(ctx, cm).Return(someErr)
err := DeleteMultiple(ctx, c, []client.Object{cm, secret})
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should delete multiple objects", func() {
gomock.InOrder(
c.EXPECT().Delete(ctx, cm),
c.EXPECT().Delete(ctx, secret),
)
Expect(DeleteMultiple(ctx, c, []client.Object{cm, secret})).To(Succeed())
})
})
Describe("DeleteMultipleFromFile", func() {
It("should error if the file does not exist", func() {
Expect(DeleteMultipleFromFile(ctx, c, "should-not-exist")).To(HaveOccurred())
})
It("should abort and return any error from deleting", func() {
someErr := fmt.Errorf("some error")
c.EXPECT().Delete(ctx, testdata.UnstructuredSecret()).Return(someErr)
err := DeleteMultipleFromFile(ctx, c, objectsPath)
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, someErr)).To(BeTrue())
})
It("should patch multiple objects from file", func() {
gomock.InOrder(
c.EXPECT().Delete(ctx, testdata.UnstructuredSecret()),
c.EXPECT().Delete(ctx, testdata.UnstructuredConfigMap()),
)
Expect(DeleteMultipleFromFile(ctx, c, objectsPath)).To(Succeed())
})
})
Describe("ListAndFilter", func() {
It("should list and filter the objects", func() {
cm1 := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: corev1.NamespaceDefault,
Name: "foo",
},
}
cm2 := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: corev1.NamespaceDefault,
Name: "bar",
},
}
cm3 := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: corev1.NamespaceDefault,
Name: "baz",
},
}
list := &corev1.ConfigMapList{}
c.EXPECT().List(ctx, list).SetArg(1, corev1.ConfigMapList{
Items: []corev1.ConfigMap{cm1, cm2, cm3},
})
Expect(ListAndFilter(ctx, c, list, func(obj client.Object) (bool, error) {
return strings.HasPrefix(obj.(*corev1.ConfigMap).Name, "b"), nil
})).To(Succeed())
Expect(list.Items).To(Equal([]corev1.ConfigMap{cm2, cm3}))
})
})
Describe("ListAndFilterControlledBy", func() {
It("should list the objects controlled by an owner", func() {
owner := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "owner",
UID: types.UID("owner-uuid"),
},
}
cm1 := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "n1",
},
}
Expect(controllerutil.SetControllerReference(&owner, &cm1, scheme.Scheme)).To(Succeed())
cm2 := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "n2",
},
}
cm3 := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "n3",
},
}
Expect(controllerutil.SetControllerReference(&owner, &cm3, scheme.Scheme)).To(Succeed())
list := &corev1.ConfigMapList{}
gomock.InOrder(
c.EXPECT().Scheme().Return(scheme.Scheme),
c.EXPECT().List(ctx, list).SetArg(1, corev1.ConfigMapList{
Items: []corev1.ConfigMap{cm1, cm2, cm3},
}),
)
Expect(ListAndFilterControlledBy(ctx, c, &owner, list)).To(Succeed())
Expect(list.Items).To(Equal([]corev1.ConfigMap{cm1, cm3}))
})
})
Describe("IsOlderThan", func() {
It("should return true if an object is older than another", func() {
cm1 := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
CreationTimestamp: metav1.Unix(100, 0),
},
}
cm2 := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
CreationTimestamp: metav1.Unix(0, 0),
},
}
Expect(IsOlderThan(cm2)(cm1)).To(BeFalse(), "cm1 should not be older than cm1")
Expect(IsOlderThan(cm1)(cm2)).To(BeTrue(), "cm2 should be older than cm1")
Expect(IsOlderThan(cm1)(cm1)).To(BeFalse(), "cm1 should not be older than itself")
})
})
Describe("CreateOrUseAndPatch", func() {
var (
cm1, cm2, cm3 corev1.ConfigMap
)
BeforeEach(func() {
cm1 = corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "n1",
},
}
cm2 = corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
CreationTimestamp: metav1.Unix(100, 0),
Namespace: "foo",
Name: "n2",
},
}
cm3 = corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "n3",
},
}
})
It("should use an object if it matches and patch it when it's mutated", func() {
annotations := map[string]string{"foo": "bar"}
withoutAnnotations := &corev1.ConfigMap{}
withAnnotations := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Annotations: annotations}}
expectedPatchData, err := client.MergeFrom(withoutAnnotations).Data(withAnnotations)
Expect(err).NotTo(HaveOccurred())
c.EXPECT().Patch(ctx, gomock.AssignableToTypeOf(&corev1.ConfigMap{}), gomock.AssignableToTypeOf(reflect.TypeOf((*client.Patch)(nil)).Elem())).
Do(func(_ context.Context, cm *corev1.ConfigMap, patch client.Patch, opts ...client.PatchOption) {
Expect(patch.Data(cm)).To(Equal(expectedPatchData))
cm.Annotations = annotations
})
cm := &corev1.ConfigMap{}
res, other, err := CreateOrUseAndPatch(ctx, c, []client.Object{&cm1, &cm2, &cm3}, cm, func() (bool, error) {
return cm.Name == "n3", nil
}, IsOlderThan(cm), func() error {
cm.Annotations = annotations
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(other).To(Equal([]client.Object{&cm1, &cm2}))
Expect(res).To(Equal(controllerutil.OperationResultUpdated))
Expect(cm).To(Equal(&corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "foo",
Name: "n3",
Annotations: annotations,
},
}))
})
It("should use an object without updating it if it's mutation semantically equals its original", func() {
cm := &corev1.ConfigMap{}
res, other, err := CreateOrUseAndPatch(ctx, c, []client.Object{&cm1, &cm2, &cm3}, cm, func() (bool, error) {
return cm.Name == "n3", nil
}, IsOlderThan(cm), nil)
Expect(err).NotTo(HaveOccurred())
Expect(other).To(Equal([]client.Object{&cm1, &cm2}))
Expect(res).To(Equal(controllerutil.OperationResultNone))
Expect(cm).To(Equal(&cm3))
})
It("should use the older object when multiple objects match", func() {
cm := &corev1.ConfigMap{}
res, other, err := CreateOrUseAndPatch(ctx, c, []client.Object{&cm1, &cm2, &cm3}, cm, func() (bool, error) {
return cm.Name == "n2" || cm.Name == "n3", nil
}, IsOlderThan(cm), nil)
Expect(err).NotTo(HaveOccurred())
Expect(other).To(Equal([]client.Object{&cm1, &cm2}))
Expect(res).To(Equal(controllerutil.OperationResultNone))
Expect(cm).To(Equal(&cm3))
})
It("should create a new object if none matches", func() {
cm := &corev1.ConfigMap{}
c.EXPECT().Create(ctx, cm)
res, other, err := CreateOrUseAndPatch(ctx, c, []client.Object{&cm1, &cm2, &cm3}, cm, func() (bool, error) {
return false, nil
}, IsOlderThan(cm), func() error {
cm.Name = "n4"
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(other).To(Equal([]client.Object{&cm1, &cm2, &cm3}))
Expect(res).To(Equal(controllerutil.OperationResultCreated))
Expect(cm).To(Equal(&corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "n4",
},
}))
})
})
Describe("DeleteIfExists", func() {
It("should delete the existing object and return true", func() {
c.EXPECT().Delete(ctx, cm)
existed, err := DeleteIfExists(ctx, c, cm)
Expect(err).NotTo(HaveOccurred())
Expect(existed).To(BeTrue(), "object should have existed")
})
It("should catch the not-found error when deleting and return false", func() {
c.EXPECT().Delete(ctx, cm).Return(apierrors.NewNotFound(schema.GroupResource{}, ""))
existed, err := DeleteIfExists(ctx, c, cm)
Expect(err).NotTo(HaveOccurred())
Expect(existed).To(BeFalse(), "object should not have")
})
It("should forward any unknown errors", func() {
expectedErr := fmt.Errorf("custom")
c.EXPECT().Delete(ctx, cm).Return(expectedErr)
_, err := DeleteIfExists(ctx, c, cm)
Expect(err).To(Equal(expectedErr))
})
})
Describe("DeleteMultipleIfExist", func() {
It("should delete the multiple objects and return the ones that existed", func() {
gomock.InOrder(
c.EXPECT().Delete(ctx, cm),
c.EXPECT().Delete(ctx, secret).Return(apierrors.NewNotFound(schema.GroupResource{}, "")),
)
existed, err := DeleteMultipleIfExist(ctx, c, []client.Object{cm, secret})
Expect(err).NotTo(HaveOccurred())
Expect(existed).To(Equal([]client.Object{cm}))
})
It("should forward any unknown errors but still return the objects that existed", func() {
expectedErr := fmt.Errorf("custom error")
gomock.InOrder(
c.EXPECT().Delete(ctx, cm),
c.EXPECT().Delete(ctx, secret).Return(expectedErr),
)
existed, err := DeleteMultipleIfExist(ctx, c, []client.Object{cm, secret})
Expect(err).To(SatisfyAll(
HaveOccurred(),
WithTransform(func(err error) bool {
return errors.Is(err, expectedErr)
}, BeTrue()),
))
Expect(existed).To(Equal([]client.Object{cm}))
})
})
Context("Finalizer utilities", func() {
var (
addFinalizerPatchData []byte
removeFinalizerPatchData []byte
cmWithFinalizer *corev1.ConfigMap
)
BeforeEach(func() {
cmWithFinalizer = cm.DeepCopy()
cmWithFinalizer.Finalizers = []string{finalizer}
var err error
addFinalizerPatchData, err = client.MergeFrom(cm).Data(cmWithFinalizer)
Expect(err).NotTo(HaveOccurred())
removeFinalizerPatchData, err = client.MergeFrom(cmWithFinalizer).Data(cm)
Expect(err).NotTo(HaveOccurred())
})
Describe("PatchAddFinalizer", func() {
It("should issue a patch adding the finalizer", func() {
c.EXPECT().Patch(ctx, cm, mock.MatchedBy(func(p client.Patch) bool {
return Expect(p.Data(cm)).To(Equal(addFinalizerPatchData))
}))
Expect(PatchAddFinalizer(ctx, c, cm, finalizer)).To(Succeed())
})
})
Describe("PatchRemoveFinalizer", func() {
It("should issue a patch removing the finalizer", func() {
c.EXPECT().Patch(ctx, cmWithFinalizer, mock.MatchedBy(func(p client.Patch) bool {
return Expect(p.Data(cm)).To(Equal(removeFinalizerPatchData))
}))
Expect(PatchRemoveFinalizer(ctx, c, cmWithFinalizer, finalizer)).To(Succeed())
})
})
Describe("PatchEnsureFinalizer", func() {
It("should add the finalizer if it is not present and report that it was modified", func() {
c.EXPECT().Patch(ctx, cm, mock.MatchedBy(func(p client.Patch) bool {
return Expect(p.Data(cm)).To(Equal(addFinalizerPatchData))
}))
modified, err := PatchEnsureFinalizer(ctx, c, cm, finalizer)
Expect(err).NotTo(HaveOccurred())
Expect(modified).To(BeTrue(), "cm should be modified: %v", cm)
})
It("should not add the finalizer if it is already present and report that it was not modified", func() {
modified, err := PatchEnsureFinalizer(ctx, c, cmWithFinalizer, finalizer)
Expect(err).NotTo(HaveOccurred())
Expect(modified).To(BeFalse(), "cm should not be modified")
})
})
Describe("PatchEnsureNoFinalizer", func() {
It("should remove the finalizer if it is present and report that it was modified", func() {
c.EXPECT().Patch(ctx, cmWithFinalizer, mock.MatchedBy(func(p client.Patch) bool {
return Expect(p.Data(cmWithFinalizer)).To(Equal(removeFinalizerPatchData))
}))
modified, err := PatchEnsureNoFinalizer(ctx, c, cmWithFinalizer, finalizer)
Expect(err).NotTo(HaveOccurred())
Expect(modified).To(BeTrue(), "cm should be modified: %v", cm)
})
It("should not remove the finalizer if it is already not present and report that it was not modified", func() {
modified, err := PatchEnsureNoFinalizer(ctx, c, cm, finalizer)
Expect(err).NotTo(HaveOccurred())
Expect(modified).To(BeFalse(), "cm should not be modified")
})
})
})
})