-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathclient_test.go
4037 lines (3424 loc) · 143 KB
/
client_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
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 client_test
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"sync/atomic"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
appsv1 "k8s.io/api/apps/v1"
authenticationv1 "k8s.io/api/authentication/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
certificatesv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
kscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/examples/crd/pkg"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func deleteDeployment(ctx context.Context, dep *appsv1.Deployment, ns string) {
_, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
if err == nil {
err = clientset.AppsV1().Deployments(ns).Delete(ctx, dep.Name, metav1.DeleteOptions{})
Expect(err).NotTo(HaveOccurred())
}
}
func deleteNamespace(ctx context.Context, ns *corev1.Namespace) {
ns, err := clientset.CoreV1().Namespaces().Get(ctx, ns.Name, metav1.GetOptions{})
if err != nil {
return
}
err = clientset.CoreV1().Namespaces().Delete(ctx, ns.Name, metav1.DeleteOptions{})
Expect(err).NotTo(HaveOccurred())
// finalize if necessary
pos := -1
finalizers := ns.Spec.Finalizers
for i, fin := range finalizers {
if fin == "kubernetes" {
pos = i
break
}
}
if pos == -1 {
// no need to finalize
return
}
// re-get in order to finalize
ns, err = clientset.CoreV1().Namespaces().Get(ctx, ns.Name, metav1.GetOptions{})
if err != nil {
return
}
ns.Spec.Finalizers = append(finalizers[:pos], finalizers[pos+1:]...)
_, err = clientset.CoreV1().Namespaces().Finalize(ctx, ns, metav1.UpdateOptions{})
Expect(err).NotTo(HaveOccurred())
WAIT_LOOP:
for i := 0; i < 10; i++ {
ns, err = clientset.CoreV1().Namespaces().Get(ctx, ns.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
// success!
return
}
select {
case <-ctx.Done():
break WAIT_LOOP
// failed to delete in time, see failure below
case <-time.After(100 * time.Millisecond):
// do nothing, try again
}
}
Fail(fmt.Sprintf("timed out waiting for namespace %q to be deleted", ns.Name))
}
type mockPatchOption struct {
applied bool
}
func (o *mockPatchOption) ApplyToPatch(_ *client.PatchOptions) {
o.applied = true
}
// metaOnlyFromObj returns PartialObjectMetadata from a concrete Go struct that
// returns a concrete *metav1.ObjectMeta from GetObjectMeta (yes, that plays a
// bit fast and loose, but the only other options are serializing and then
// deserializing, or manually calling all the accessor funcs, which are both a bit annoying).
func metaOnlyFromObj(obj interface {
runtime.Object
metav1.ObjectMetaAccessor
}, scheme *runtime.Scheme) *metav1.PartialObjectMetadata {
metaObj := metav1.PartialObjectMetadata{}
obj.GetObjectMeta().(*metav1.ObjectMeta).DeepCopyInto(&metaObj.ObjectMeta)
kinds, _, err := scheme.ObjectKinds(obj)
if err != nil {
panic(err)
}
metaObj.SetGroupVersionKind(kinds[0])
return &metaObj
}
var _ = Describe("Client", func() {
var scheme *runtime.Scheme
var depGvk schema.GroupVersionKind
var dep *appsv1.Deployment
var pod *corev1.Pod
var node *corev1.Node
var serviceAccount *corev1.ServiceAccount
var csr *certificatesv1.CertificateSigningRequest
var count uint64 = 0
var replicaCount int32 = 2
var ns = "default"
var errNotCached *cache.ErrResourceNotCached
ctx := context.TODO()
BeforeEach(func() {
atomic.AddUint64(&count, 1)
dep = &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("deployment-name-%v", count), Namespace: ns, Labels: map[string]string{"app": fmt.Sprintf("bar-%v", count)}},
Spec: appsv1.DeploymentSpec{
Replicas: &replicaCount,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{"foo": "bar"},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"foo": "bar"}},
Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx"}}},
},
},
}
depGvk = schema.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
}
// Pod is invalid without a container field in the PodSpec
pod = &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("pod-%v", count), Namespace: ns},
Spec: corev1.PodSpec{},
}
node = &corev1.Node{
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("node-name-%v", count)},
Spec: corev1.NodeSpec{},
}
serviceAccount = &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("sa-%v", count), Namespace: ns}}
csr = &certificatesv1.CertificateSigningRequest{
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("csr-%v", count)},
Spec: certificatesv1.CertificateSigningRequestSpec{
SignerName: "org.io/my-signer",
Request: []byte(`-----BEGIN CERTIFICATE REQUEST-----
MIIChzCCAW8CAQAwQjELMAkGA1UEBhMCWFgxFTATBgNVBAcMDERlZmF1bHQgQ2l0
eTEcMBoGA1UECgwTRGVmYXVsdCBDb21wYW55IEx0ZDCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBANe06dLX/bDNm6mVEnKdJexcJM6WKMFSt5o6BEdD1+Ki
WyUcvfNgIBbwAZjkF9U1r7+KuDcc6XYFnb6ky1wPo4C+XwcIIx7Nnbf8IdWJukPb
2BCsqO4NCsG6kKFavmH9J3q//nwKUvlQE+AJ2MPuOAZTwZ4KskghiGuS8hyk6/PZ
XH9QhV7Jma43bDzQozd2C7OujRBhLsuP94KSu839RRFWd9ms3XHgTxLxb7nxwZDx
9l7/ZVAObJoQYlHENqs12NCVP4gpJfbcY8/rd+IG4ftcZEmpeO4kKO+d2TpRKQqw
bjCMoAdD5Y43iLTtyql4qRnbMe3nxYG2+1inEryuV/cCAwEAAaAAMA0GCSqGSIb3
DQEBCwUAA4IBAQDH5hDByRN7wERQtC/o6uc8Y+yhjq9YcBJjjbnD6Vwru5pOdWtx
qfKkkXI5KNOdEhWzLnJyOcWHjj8UoHqI3AjxGC7dTM95eGjxQGUpsUOX8JSd4MiZ
cct4g4BKBj02AGqZLiEgN+PLCYAmEaYU7oZc4OAh6WzMrljNRsj66awMQpw8O1eY
YuBa8vwz8ko8vn/pn7IrFu8cZ+EA3rluJ+budX/QrEGi1hijg27q7/Qr0wNI9f1v
086mLKdqaBTkblXWEvF3WP4CcLNyrSNi4eu+G0fcAgGp1F/Nqh0MuWKSOLprv5Om
U5wwSivyi7vmegHKmblOzNVKA5qPO8zWzqBC
-----END CERTIFICATE REQUEST-----`),
Usages: []certificatesv1.KeyUsage{certificatesv1.UsageClientAuth},
},
}
scheme = kscheme.Scheme
})
var delOptions *metav1.DeleteOptions
AfterEach(func() {
// Cleanup
var zero int64 = 0
policy := metav1.DeletePropagationForeground
delOptions = &metav1.DeleteOptions{
GracePeriodSeconds: &zero,
PropagationPolicy: &policy,
}
deleteDeployment(ctx, dep, ns)
_, err := clientset.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{})
if err == nil {
err = clientset.CoreV1().Nodes().Delete(ctx, node.Name, *delOptions)
Expect(err).NotTo(HaveOccurred())
}
err = clientset.CoreV1().ServiceAccounts(ns).Delete(ctx, serviceAccount.Name, *delOptions)
Expect(client.IgnoreNotFound(err)).NotTo(HaveOccurred())
err = clientset.CertificatesV1().CertificateSigningRequests().Delete(ctx, csr.Name, *delOptions)
Expect(client.IgnoreNotFound(err)).NotTo(HaveOccurred())
})
Describe("WarningHandler", func() {
It("should log warnings with config.WarningHandler, if one is defined", func() {
cache := &fakeReader{}
testCfg := rest.CopyConfig(cfg)
var testLog bytes.Buffer
testCfg.WarningHandler = rest.NewWarningWriter(&testLog, rest.WarningWriterOptions{})
cl, err := client.New(testCfg, client.Options{Cache: &client.CacheOptions{Reader: cache, DisableFor: []client.Object{&corev1.Namespace{}}}})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "wh-defined"}}
tns, err = clientset.CoreV1().Namespaces().Create(ctx, tns, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(tns).NotTo(BeNil())
defer deleteNamespace(ctx, tns)
toCreate := &pkg.ChaosPod{
ObjectMeta: metav1.ObjectMeta{
Name: "example",
Namespace: tns.Name,
},
// The ChaosPod CRD does not define Status, so the field is unknown to the API server,
// but field validation is not strict by default, so the API server returns a warning,
// and we need a warning to check whether suppression works.
Status: pkg.ChaosPodStatus{},
}
err = cl.Create(ctx, toCreate)
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
scannerTestLog := bufio.NewScanner(&testLog)
for scannerTestLog.Scan() {
line := scannerTestLog.Text()
if strings.Contains(
line,
"unknown field \"status\"",
) {
return
}
}
defer Fail("expected to find one API server warning logged the config.WarningHandler")
scanner := bufio.NewScanner(&log)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(
line,
"unknown field \"status\"",
) {
defer Fail("expected to find zero API server warnings in the client log")
break
}
}
})
})
Describe("New", func() {
It("should return a new Client", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
})
It("should fail if the config is nil", func() {
cl, err := client.New(nil, client.Options{})
Expect(err).To(HaveOccurred())
Expect(cl).To(BeNil())
})
It("should use the provided Scheme if provided", func() {
cl, err := client.New(cfg, client.Options{Scheme: scheme})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(cl.Scheme()).ToNot(BeNil())
Expect(cl.Scheme()).To(Equal(scheme))
})
It("should default the Scheme if not provided", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(cl.Scheme()).ToNot(BeNil())
Expect(cl.Scheme()).To(Equal(kscheme.Scheme))
})
It("should use the provided Mapper if provided", func() {
mapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{})
cl, err := client.New(cfg, client.Options{Mapper: mapper})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(cl.RESTMapper()).ToNot(BeNil())
Expect(cl.RESTMapper()).To(Equal(mapper))
})
It("should create a Mapper if not provided", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(cl.RESTMapper()).ToNot(BeNil())
})
It("should use the provided reader cache if provided, on get and list", func() {
cache := &fakeReader{}
cl, err := client.New(cfg, client.Options{Cache: &client.CacheOptions{Reader: cache}})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(cl.Get(ctx, client.ObjectKey{Name: "test"}, &appsv1.Deployment{})).To(Succeed())
Expect(cl.List(ctx, &appsv1.DeploymentList{})).To(Succeed())
Expect(cache.Called).To(Equal(2))
})
It("should propagate ErrResourceNotCached errors", func() {
c := &fakeUncachedReader{}
cl, err := client.New(cfg, client.Options{Cache: &client.CacheOptions{Reader: c}})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(errors.As(cl.Get(ctx, client.ObjectKey{Name: "test"}, &appsv1.Deployment{}), &errNotCached)).To(BeTrue())
Expect(errors.As(cl.List(ctx, &appsv1.DeploymentList{}), &errNotCached)).To(BeTrue())
Expect(c.Called).To(Equal(2))
})
It("should not use the provided reader cache if provided, on get and list for uncached GVKs", func() {
cache := &fakeReader{}
cl, err := client.New(cfg, client.Options{Cache: &client.CacheOptions{Reader: cache, DisableFor: []client.Object{&corev1.Namespace{}}}})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
Expect(cl.Get(ctx, client.ObjectKey{Name: "default"}, &corev1.Namespace{})).To(Succeed())
Expect(cl.List(ctx, &corev1.NamespaceList{})).To(Succeed())
Expect(cache.Called).To(Equal(0))
})
})
Describe("Create", func() {
Context("with structured objects", func() {
It("should create a new object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the object")
err = cl.Create(context.TODO(), dep)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
By("writing the result back to the go struct")
Expect(dep).To(Equal(actual))
})
It("should create a new object non-namespace object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the object")
err = cl.Create(context.TODO(), node)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
By("writing the result back to the go struct")
Expect(node).To(Equal(actual))
})
It("should fail if the object already exists", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
old := dep.DeepCopy()
By("creating the object")
err = cl.Create(context.TODO(), dep)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
By("creating the object a second time")
err = cl.Create(context.TODO(), old)
Expect(err).To(HaveOccurred())
Expect(apierrors.IsAlreadyExists(err)).To(BeTrue())
})
It("should fail if the object does not pass server-side validation", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the pod, since required field Containers is empty")
err = cl.Create(context.TODO(), pod)
Expect(err).To(HaveOccurred())
// TODO(seans): Add test to validate the returned error. Problems currently with
// different returned error locally versus travis.
})
It("should fail if the object cannot be mapped to a GVK", func() {
By("creating client with empty Scheme")
emptyScheme := runtime.NewScheme()
cl, err := client.New(cfg, client.Options{Scheme: emptyScheme})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the object fails")
err = cl.Create(context.TODO(), dep)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("no kind is registered for the type"))
})
PIt("should fail if the GVK cannot be mapped to a Resource", func() {
// TODO(seans3): implement these
// Example: ListOptions
})
Context("with the DryRun option", func() {
It("should not create a new object, global option", func() {
cl, err := client.New(cfg, client.Options{DryRun: ptr.To(true)})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the object (with DryRun)")
err = cl.Create(context.TODO(), dep)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).To(HaveOccurred())
Expect(apierrors.IsNotFound(err)).To(BeTrue())
Expect(actual).To(Equal(&appsv1.Deployment{}))
})
It("should not create a new object, inline option", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the object (with DryRun)")
err = cl.Create(context.TODO(), dep, client.DryRunAll)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).To(HaveOccurred())
Expect(apierrors.IsNotFound(err)).To(BeTrue())
Expect(actual).To(Equal(&appsv1.Deployment{}))
})
})
})
Context("with unstructured objects", func() {
It("should create a new object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("encoding the deployment as unstructured")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(dep, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
})
By("creating the object")
err = cl.Create(context.TODO(), u)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
})
It("should create a new non-namespace object ", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("encoding the deployment as unstructured")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(node, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Kind: "Node",
Version: "v1",
})
By("creating the object")
err = cl.Create(context.TODO(), node)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
au := &unstructured.Unstructured{}
Expect(scheme.Convert(actual, au, nil)).To(Succeed())
Expect(scheme.Convert(node, u, nil)).To(Succeed())
By("writing the result back to the go struct")
Expect(u).To(Equal(au))
})
It("should fail if the object already exists", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
old := dep.DeepCopy()
By("creating the object")
err = cl.Create(context.TODO(), dep)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
By("encoding the deployment as unstructured")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(old, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
})
By("creating the object a second time")
err = cl.Create(context.TODO(), u)
Expect(err).To(HaveOccurred())
Expect(apierrors.IsAlreadyExists(err)).To(BeTrue())
})
It("should fail if the object does not pass server-side validation", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("creating the pod, since required field Containers is empty")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(pod, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "Pod",
})
err = cl.Create(context.TODO(), u)
Expect(err).To(HaveOccurred())
// TODO(seans): Add test to validate the returned error. Problems currently with
// different returned error locally versus travis.
})
})
Context("with metadata objects", func() {
It("should fail with an error", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
obj := metaOnlyFromObj(dep, scheme)
Expect(cl.Create(context.TODO(), obj)).NotTo(Succeed())
})
})
Context("with the DryRun option", func() {
It("should not create a new object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("encoding the deployment as unstructured")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(dep, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
})
By("creating the object")
err = cl.Create(context.TODO(), u, client.DryRunAll)
Expect(err).NotTo(HaveOccurred())
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).To(HaveOccurred())
Expect(apierrors.IsNotFound(err)).To(BeTrue())
Expect(actual).To(Equal(&appsv1.Deployment{}))
})
})
})
Describe("Update", func() {
Context("with structured objects", func() {
It("should update an existing object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("initially creating a Deployment")
dep, err := clientset.AppsV1().Deployments(ns).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the Deployment")
dep.Annotations = map[string]string{"foo": "bar"}
err = cl.Update(context.TODO(), dep)
Expect(err).NotTo(HaveOccurred())
By("validating updated Deployment has new annotation")
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
Expect(actual.Annotations["foo"]).To(Equal("bar"))
})
It("should update and preserve type information", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("initially creating a Deployment")
dep, err := clientset.AppsV1().Deployments(ns).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the Deployment")
dep.SetGroupVersionKind(depGvk)
err = cl.Update(context.TODO(), dep)
Expect(err).NotTo(HaveOccurred())
By("validating updated Deployment has type information")
Expect(dep.GroupVersionKind()).To(Equal(depGvk))
})
It("should update an existing object non-namespace object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
node, err := clientset.CoreV1().Nodes().Create(ctx, node, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the object")
node.Annotations = map[string]string{"foo": "bar"}
err = cl.Update(context.TODO(), node)
Expect(err).NotTo(HaveOccurred())
By("validate updated Node had new annotation")
actual, err := clientset.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
Expect(actual.Annotations["foo"]).To(Equal("bar"))
})
It("should fail if the object does not exist", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("updating non-existent object")
err = cl.Update(context.TODO(), dep)
Expect(err).To(HaveOccurred())
})
PIt("should fail if the object does not pass server-side validation", func() {
})
PIt("should fail if the object doesn't have meta", func() {
})
It("should fail if the object cannot be mapped to a GVK", func() {
By("creating client with empty Scheme")
emptyScheme := runtime.NewScheme()
cl, err := client.New(cfg, client.Options{Scheme: emptyScheme})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("initially creating a Deployment")
dep, err := clientset.AppsV1().Deployments(ns).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the Deployment")
dep.Annotations = map[string]string{"foo": "bar"}
err = cl.Update(context.TODO(), dep)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("no kind is registered for the type"))
})
PIt("should fail if the GVK cannot be mapped to a Resource", func() {
})
})
Context("with unstructured objects", func() {
It("should update an existing object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("initially creating a Deployment")
dep, err := clientset.AppsV1().Deployments(ns).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the Deployment")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(dep, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
})
u.SetAnnotations(map[string]string{"foo": "bar"})
err = cl.Update(context.TODO(), u)
Expect(err).NotTo(HaveOccurred())
By("validating updated Deployment has new annotation")
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
Expect(actual.Annotations["foo"]).To(Equal("bar"))
})
It("should update and preserve type information", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("initially creating a Deployment")
dep, err := clientset.AppsV1().Deployments(ns).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the Deployment")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(dep, u, nil)).To(Succeed())
u.SetGroupVersionKind(depGvk)
u.SetAnnotations(map[string]string{"foo": "bar"})
err = cl.Update(context.TODO(), u)
Expect(err).NotTo(HaveOccurred())
By("validating updated Deployment has type information")
Expect(u.GroupVersionKind()).To(Equal(depGvk))
})
It("should update an existing object non-namespace object from a go struct", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
node, err := clientset.CoreV1().Nodes().Create(ctx, node, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("updating the object")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(node, u, nil)).To(Succeed())
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "",
Kind: "Node",
Version: "v1",
})
u.SetAnnotations(map[string]string{"foo": "bar"})
err = cl.Update(context.TODO(), u)
Expect(err).NotTo(HaveOccurred())
By("validate updated Node had new annotation")
actual, err := clientset.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
Expect(actual.Annotations["foo"]).To(Equal("bar"))
})
It("should fail if the object does not exist", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("updating non-existent object")
u := &unstructured.Unstructured{}
Expect(scheme.Convert(dep, u, nil)).To(Succeed())
u.SetGroupVersionKind(depGvk)
err = cl.Update(context.TODO(), dep)
Expect(err).To(HaveOccurred())
})
})
Context("with metadata objects", func() {
It("should fail with an error", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
obj := metaOnlyFromObj(dep, scheme)
Expect(cl.Update(context.TODO(), obj)).NotTo(Succeed())
})
})
})
Describe("Patch", func() {
Context("Metadata Client", func() {
It("should merge patch with options", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("initially creating a Deployment")
dep, err := clientset.AppsV1().Deployments(ns).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
metadata := metaOnlyFromObj(dep, scheme)
if metadata.Labels == nil {
metadata.Labels = make(map[string]string)
}
metadata.Labels["foo"] = "bar"
testOption := &mockPatchOption{}
Expect(cl.Patch(context.TODO(), metadata, client.Merge, testOption)).To(Succeed())
By("validating that patched metadata has new labels")
actual, err := clientset.AppsV1().Deployments(ns).Get(ctx, dep.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(actual).NotTo(BeNil())
Expect(actual.Labels["foo"]).To(Equal("bar"))
By("validating patch options were applied")
Expect(testOption.applied).To(BeTrue())
})
})
})
Describe("SubResourceClient", func() {
Context("with structured objects", func() {
It("should be able to read the Scale subresource", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("Creating a deployment")
dep, err := clientset.AppsV1().Deployments(dep.Namespace).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("reading the scale subresource")
scale := &autoscalingv1.Scale{}
err = cl.SubResource("scale").Get(ctx, dep, scale, &client.SubResourceGetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(scale.Spec.Replicas).To(Equal(*dep.Spec.Replicas))
})
It("should be able to create ServiceAccount tokens", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("Creating the serviceAccount")
_, err = clientset.CoreV1().ServiceAccounts(serviceAccount.Namespace).Create(ctx, serviceAccount, metav1.CreateOptions{})
Expect((err)).NotTo(HaveOccurred())
token := &authenticationv1.TokenRequest{}
err = cl.SubResource("token").Create(ctx, serviceAccount, token, &client.SubResourceCreateOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(token.Status.Token).NotTo(Equal(""))
})
It("should be able to create Pod evictions", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
// Make the pod valid
pod.Spec.Containers = []corev1.Container{{Name: "foo", Image: "busybox"}}
By("Creating the pod")
pod, err = clientset.CoreV1().Pods(pod.Namespace).Create(ctx, pod, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Creating the eviction")
eviction := &policyv1.Eviction{
DeleteOptions: &metav1.DeleteOptions{GracePeriodSeconds: ptr.To(int64(0))},
}
err = cl.SubResource("eviction").Create(ctx, pod, eviction, &client.SubResourceCreateOptions{})
Expect((err)).NotTo(HaveOccurred())
By("Asserting the pod is gone")
_, err = clientset.CoreV1().Pods(pod.Namespace).Get(ctx, pod.Name, metav1.GetOptions{})
Expect(apierrors.IsNotFound(err)).To(BeTrue())
})
It("should be able to create Pod bindings", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
// Make the pod valid
pod.Spec.Containers = []corev1.Container{{Name: "foo", Image: "busybox"}}
By("Creating the pod")
pod, err = clientset.CoreV1().Pods(pod.Namespace).Create(ctx, pod, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Creating the binding")
binding := &corev1.Binding{
Target: corev1.ObjectReference{Name: node.Name},
}
err = cl.SubResource("binding").Create(ctx, pod, binding, &client.SubResourceCreateOptions{})
Expect((err)).NotTo(HaveOccurred())
By("Asserting the pod is bound")
pod, err = clientset.CoreV1().Pods(pod.Namespace).Get(ctx, pod.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(pod.Spec.NodeName).To(Equal(node.Name))
})
It("should be able to approve CSRs", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("Creating the CSR")
csr, err := clientset.CertificatesV1().CertificateSigningRequests().Create(ctx, csr, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Approving the CSR")
csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1.CertificateSigningRequestCondition{
Type: certificatesv1.CertificateApproved,
Status: corev1.ConditionTrue,
})
err = cl.SubResource("approval").Update(ctx, csr, &client.SubResourceUpdateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Asserting the CSR is approved")
csr, err = clientset.CertificatesV1().CertificateSigningRequests().Get(ctx, csr.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(csr.Status.Conditions[0].Type).To(Equal(certificatesv1.CertificateApproved))
Expect(csr.Status.Conditions[0].Status).To(Equal(corev1.ConditionTrue))
})
It("should be able to approve CSRs using Patch", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("Creating the CSR")
csr, err := clientset.CertificatesV1().CertificateSigningRequests().Create(ctx, csr, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())
By("Approving the CSR")
patch := client.MergeFrom(csr.DeepCopy())
csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1.CertificateSigningRequestCondition{
Type: certificatesv1.CertificateApproved,
Status: corev1.ConditionTrue,
})
err = cl.SubResource("approval").Patch(ctx, csr, patch, &client.SubResourcePatchOptions{})
Expect(err).NotTo(HaveOccurred())
By("Asserting the CSR is approved")
csr, err = clientset.CertificatesV1().CertificateSigningRequests().Get(ctx, csr.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
Expect(csr.Status.Conditions[0].Type).To(Equal(certificatesv1.CertificateApproved))
Expect(csr.Status.Conditions[0].Status).To(Equal(corev1.ConditionTrue))
})
It("should be able to update the scale subresource", func() {
cl, err := client.New(cfg, client.Options{})
Expect(err).NotTo(HaveOccurred())
Expect(cl).NotTo(BeNil())
By("Creating a deployment")
dep, err := clientset.AppsV1().Deployments(dep.Namespace).Create(ctx, dep, metav1.CreateOptions{})
Expect(err).NotTo(HaveOccurred())