-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathhostedcontrolplane_test.go
More file actions
1055 lines (991 loc) · 31.3 KB
/
hostedcontrolplane_test.go
File metadata and controls
1055 lines (991 loc) · 31.3 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
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
package hostedcontrolplane
import (
"context"
"fmt"
"reflect"
"testing"
"time"
"github.com/go-logr/logr"
routev1 "github.com/openshift/api/route/v1"
avov1alpha2 "github.com/openshift/aws-vpce-operator/api/v1alpha2"
hypershiftv1beta1 "github.com/openshift/hypershift/api/hypershift/v1beta1"
"github.com/openshift/route-monitor-operator/api/v1alpha1"
"github.com/openshift/route-monitor-operator/config"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/log"
)
func Test_buildMetadataForUpdate(t *testing.T) {
// Test-specific definitions
var (
hcp = hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
},
}
deletionGracePeriod = int64(0)
meta = metav1.ObjectMeta{
Name: "actual",
Namespace: "actualNS",
ResourceVersion: "0123456789",
Generation: int64(1234),
CreationTimestamp: metav1.Now(),
DeletionTimestamp: &metav1.Time{Time: time.Now()},
DeletionGracePeriodSeconds: &deletionGracePeriod,
}
)
type args struct {
expected metav1.ObjectMeta
actual metav1.ObjectMeta
}
// Testing
tests := []struct {
name string
args args
want metav1.ObjectMeta
}{
// Cases
{
name: "on-cluster object's labels differ from expected",
args: args{
actual: metav1.ObjectMeta{
Name: "actual",
Labels: map[string]string{"incorrect-label": "true"},
},
expected: metav1.ObjectMeta{
Name: "expected",
Labels: map[string]string{"correct-label": "true"},
},
},
want: metav1.ObjectMeta{
Name: "actual",
Labels: map[string]string{"correct-label": "true"},
},
},
{
name: "on-cluster object's OwnerReferences differ from expected",
args: args{
actual: metav1.ObjectMeta{
Name: "actual",
OwnerReferences: []metav1.OwnerReference{},
},
expected: metav1.ObjectMeta{
Name: "expected",
OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(&hcp, hcp.GroupVersionKind())},
},
},
want: metav1.ObjectMeta{
Name: "actual",
OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(&hcp, hcp.GroupVersionKind())},
},
},
{
name: "other fields in on-cluster object's metadata remains unchanged",
args: args{
actual: meta,
expected: metav1.ObjectMeta{
Name: "expected",
Namespace: "otherNS",
ResourceVersion: "9876543210",
Generation: int64(9876),
},
},
want: meta,
},
}
// Execution
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := buildMetadataForUpdate(tt.args.expected, tt.args.actual); !reflect.DeepEqual(got, tt.want) {
t.Errorf("buildMetadataForUpdate() = %#v, want %#v", got, tt.want)
}
})
}
}
func TestHostedControlPlaneReconciler_buildInternalMonitoringRoute(t *testing.T) {
// Test-specific definitions
var (
hcp = hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "test",
},
}
)
type args struct {
hostedcontrolplane *hypershiftv1beta1.HostedControlPlane
}
// Testing
tests := []struct {
name string
args args
eval func(route routev1.Route) (passed bool, reason string)
}{
// Cases
{
name: "route is created with watch label",
args: args{
hostedcontrolplane: &hcp,
},
eval: func(route routev1.Route) (bool, string) {
value, found := route.Labels[watchResourceLabel]
if !found {
return false, "watchResourceLabel key not found"
}
if value != "true" {
return false, "watchResourceLabel value is not correct"
}
return true, ""
},
},
{
name: "route's .spec.host field is formulated properly",
args: args{
hostedcontrolplane: &hcp,
},
eval: func(route routev1.Route) (bool, string) {
expectedHost := "kube-apiserver.test.svc.cluster.local"
if route.Spec.Host != expectedHost {
return false, fmt.Sprintf("host field was set incorrectly: expected '%s', got '%s'", expectedHost, route.Spec.Host)
}
return true, ""
},
},
{
name: "route's OwnerReference is set to the provided hostedcontrolplane",
args: args{
hostedcontrolplane: &hcp,
},
eval: func(route routev1.Route) (bool, string) {
if len(route.OwnerReferences) != 1 {
return false, fmt.Sprintf("incorrect number of ownerReferences: expected 1, got %d", len(route.OwnerReferences))
}
if reflect.DeepEqual(route.OwnerReferences[0], buildOwnerReferences(&hcp)) {
return false, "ownerref for route is incorrect"
}
return true, ""
},
},
}
// Execution
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := newTestReconciler(t)
route := r.buildInternalMonitoringRoute(tt.args.hostedcontrolplane)
passed, reason := tt.eval(route)
if !passed {
t.Errorf("HostedControlPlaneReconciler.buildInternalMonitoringRoute() resulting route = %#v, failed due to %s", route, reason)
}
})
}
}
func TestHostedControlPlaneReconciler_buildInternalMonitoringRouteMonitor(t *testing.T) {
// Test-specific definitions
var (
route = routev1.Route{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "test",
},
}
hcp = hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "test",
},
}
)
type args struct {
route routev1.Route
hostedcontrolplane *hypershiftv1beta1.HostedControlPlane
apiServerPort int64
}
// Testing
tests := []struct {
name string
args args
eval func(routemonitor v1alpha1.RouteMonitor) (passed bool, reason string)
}{
// Cases
{
name: "routemonitor is created with watch label",
args: args{
route: route,
hostedcontrolplane: &hcp,
apiServerPort: 6443,
},
eval: func(routemonitor v1alpha1.RouteMonitor) (passed bool, reason string) {
value, found := routemonitor.Labels[watchResourceLabel]
if !found {
return false, "watchResourceLabel key not found"
}
if value != "true" {
return false, "watchResourceLabel value is not correct"
}
return true, ""
},
},
{
name: "provided apiserver port is reflected in routemonitor's .spec",
args: args{
route: route,
hostedcontrolplane: &hcp,
apiServerPort: 9876,
},
eval: func(routemonitor v1alpha1.RouteMonitor) (passed bool, reason string) {
if routemonitor.Spec.Route.Port != 9876 {
return false, ".spec.route.port does not match the provided value '443'"
}
return true, ""
},
},
{
name: "routemonitor's ownerrefs are set correctly",
args: args{
route: route,
hostedcontrolplane: &hcp,
apiServerPort: 6443,
},
eval: func(routemonitor v1alpha1.RouteMonitor) (passed bool, reason string) {
if len(routemonitor.OwnerReferences) != 1 {
return false, fmt.Sprintf("incorrect number of ownerrefs: expected 1, got %d", len(route.OwnerReferences))
}
if reflect.DeepEqual(routemonitor.OwnerReferences[0], buildOwnerReferences(&hcp)) {
return false, "ownerref for routemonitor is incorrect"
}
return true, ""
},
},
}
// Execution
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := newTestReconciler(t)
routemonitor := r.buildInternalMonitoringRouteMonitor(tt.args.route, tt.args.hostedcontrolplane, tt.args.apiServerPort)
passed, reason := tt.eval(routemonitor)
if !passed {
t.Errorf("HostedControlPlaneReconciler.buildInternalMonitoringRouteMonitor() resulting routemonitor = %#v, failed due to = %s", routemonitor, reason)
}
})
}
}
func TestHostedControlPlaneReconciler_buildOwnerReferences(t *testing.T) {
// Test-specific definitions
var (
hcp = hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "test",
},
}
)
type args struct {
hostedcontrolplane *hypershiftv1beta1.HostedControlPlane
}
// Testing
tests := []struct {
name string
args args
eval func([]metav1.OwnerReference) (passed bool, reason string)
}{
// Cases
{
name: "exactly one ownerref is returned",
args: args{
hostedcontrolplane: &hcp,
},
eval: func(ownerrefs []metav1.OwnerReference) (passed bool, reason string) {
if len(ownerrefs) != 1 {
return false, fmt.Sprintf("incorrect number of ownerrefs returned: expected 1, got %d", len(ownerrefs))
}
return true, ""
},
},
{
name: "ownerref lists hcp as controller",
args: args{
hostedcontrolplane: &hcp,
},
eval: func(ownerrefs []metav1.OwnerReference) (passed bool, reason string) {
ownerref := ownerrefs[0]
if !*ownerref.Controller {
return false, "ownerref doesn't set hcp as controller"
}
return true, ""
},
},
}
// Execution
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ownerrefs := buildOwnerReferences(tt.args.hostedcontrolplane)
passed, reason := tt.eval(ownerrefs)
if !passed {
t.Errorf("HostedControlPlaneReconciler.buildOwnerReferences() = %#v, failed due to = %s", ownerrefs, reason)
}
})
}
}
// Left as a placeholder for future testing.
// Currently, this function simply calls deleteInternalMonitoringObjects and wraps any error returned,
// so testing it doesn't actually provide any value at this point.
func TestHostedControlPlaneReconciler_finalizeHostedControlPlane(t *testing.T) {
type args struct {
ctx context.Context
log logr.Logger
hostedcontrolplane *hypershiftv1beta1.HostedControlPlane
}
tests := []struct {
name string
args args
wantErr bool
}{
// TODO: Add test cases if/when the function requires it
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := newTestReconciler(t)
if err := r.finalizeHostedControlPlane(tt.args.ctx, tt.args.log, tt.args.hostedcontrolplane); (err != nil) != tt.wantErr {
t.Errorf("HostedControlPlaneReconciler.finalizeHostedControlPlane() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestHostedControlPlaneReconciler_deployInternalMonitoringObjects(t *testing.T) {
// cspell:ignore objs
// Test-specific definitions
var (
ctx = context.TODO()
log = log.FromContext(ctx)
hcp = hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "test",
},
}
svc = corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kube-apiserver",
Namespace: "test",
},
}
route = routev1.Route{
ObjectMeta: metav1.ObjectMeta{
// Route name should align with the expected value for an HCP based on
// what's configured in the buildInternalMonitoringRoute() function
Name: "test-kube-apiserver-monitoring",
Namespace: "test",
},
}
routemonitor = v1alpha1.RouteMonitor{
ObjectMeta: metav1.ObjectMeta{
Name: route.Name,
Namespace: route.Namespace,
},
}
)
type args struct {
ctx context.Context
log logr.Logger
hostedcontrolplane *hypershiftv1beta1.HostedControlPlane
}
// Testing
tests := []struct {
name string
args args
objs []client.Object
eval func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string)
}{
// Cases
// NOTE: we aren't testing the actual configuration of the route & routemonitor objects
// in these tests, since those object definitions are generated by other functions.
// Instead, we're focused on testing the *deployment* logic (ie - when something is created vs updated, etc)
{
name: "Error is returned when kube-apiserver service does not exist",
args: args{
ctx: ctx,
log: log,
hostedcontrolplane: &hcp,
},
objs: []client.Object{},
eval: func(err error, _ *HostedControlPlaneReconciler) (passed bool, reason string) {
if err == nil {
return false, "expected error due to missing kube-apiserver service, got none"
}
return true, ""
},
},
{
name: "No error is returned and both route & routemonitor are created when neither exists",
args: args{
ctx: ctx,
log: log,
hostedcontrolplane: &hcp,
},
objs: []client.Object{
&svc,
},
eval: func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
// Evaluate returned error
if err != nil {
return false, fmt.Sprintf("unexpected error returned: %v", err)
}
// Check that route & routemonitor objects were created, as expected
routes := routev1.RouteList{}
err = r.List(context.TODO(), &routes)
if err != nil {
return false, fmt.Sprintf("failed to retrieve routes from test client: %v", err)
}
if len(routes.Items) != 1 {
return false, fmt.Sprintf("unexpected number of routes found: expected 1, got %d. Routes: %#v", len(routes.Items), routes)
}
routemonitors := v1alpha1.RouteMonitorList{}
err = r.List(context.TODO(), &routemonitors)
if err != nil {
return false, fmt.Sprintf("failed to retrieve routemonitors from test client: %v", err)
}
if len(routemonitors.Items) != 1 {
return false, fmt.Sprintf("unexpected number of routemonitors found: expected 1, got %d. Routemonitors: %#v", len(routemonitors.Items), routemonitors)
}
return true, ""
},
},
{
name: "The route is updated when it already exists",
args: args{
ctx: ctx,
log: log,
hostedcontrolplane: &hcp,
},
objs: []client.Object{
&svc,
// Define a route w/ a bad label
// In general, we shouldn't test object configuration here, since that's defined elsewhere as
// noted above, but it's useful in this case to know that an unwanted label is expected to be
// removed, that way we know if the route is actually being updated by the function as expected.
&routev1.Route{
ObjectMeta: metav1.ObjectMeta{
Name: route.Name,
Namespace: route.Namespace,
Labels: map[string]string{"labelWeExpectToBeRemoved": "true"},
},
},
},
eval: func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
// Evaluate returned error to ensure function did not unexpectedly fail
if err != nil {
return false, fmt.Sprintf("unexpected error returned: %v", err)
}
// Check that route was updated as expected
result := routev1.Route{}
err = r.Get(context.TODO(), types.NamespacedName{Name: route.Name, Namespace: route.Namespace}, &result)
if err != nil {
return false, fmt.Sprintf("failed to retrieve route from test client: %v", err)
}
_, found := result.Labels["labelWeExpectToBeRemoved"]
if found {
return false, fmt.Sprintf("route was not updated; expected labels to not contain key 'labelWeExpectToBeRemoved', route has the following labels: %#v", route.Labels)
}
return true, ""
},
},
{
name: "The routemonitor is updated when it already exists",
args: args{
ctx: ctx,
log: log,
hostedcontrolplane: &hcp,
},
objs: []client.Object{
&svc,
// Define a route w/ a bad label
// In general, we shouldn't test object configuration here, since that's defined elsewhere as
// noted above, but it's useful in this case to know that an unwanted label is expected to be
// removed, that way we know if the route is actually being updated by the function as expected.
&v1alpha1.RouteMonitor{
ObjectMeta: metav1.ObjectMeta{
Name: routemonitor.Name,
Namespace: routemonitor.Namespace,
Labels: map[string]string{"labelWeExpectToBeRemoved": "true"},
},
},
},
eval: func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
// Evaluate returned error to ensure function did not unexpectedly fail
if err != nil {
return false, fmt.Sprintf("unexpected error returned: %v", err)
}
// Check that route was updated as expected
result := v1alpha1.RouteMonitor{}
err = r.Get(context.TODO(), types.NamespacedName{Name: routemonitor.Name, Namespace: routemonitor.Namespace}, &result)
if err != nil {
return false, fmt.Sprintf("failed to retrieve route from test client: %v", err)
}
_, found := result.Labels["labelWeExpectToBeRemoved"]
if found {
return false, fmt.Sprintf("route was not updated; expected labels to not contain key 'labelWeExpectToBeRemoved', route has the following labels: %#v", route.Labels)
}
return true, ""
},
},
}
// Execution
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := newTestReconciler(t, tt.objs...)
err := r.deployInternalMonitoringObjects(tt.args.ctx, tt.args.log, tt.args.hostedcontrolplane)
passed, reason := tt.eval(err, r)
if !passed {
t.Errorf("HostedControlPlaneReconciler.deployInternalMonitoringObjects() did not pass due to = %s", reason)
}
})
}
}
func TestHostedControlPlaneReconciler_deleteInternalMonitoringObjects(t *testing.T) {
// Test-specific definitions
var (
ctx = context.TODO()
log = log.FromContext(ctx)
hcp = hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "test",
},
}
route = routev1.Route{
ObjectMeta: metav1.ObjectMeta{
// Name must match the expected route created by the buildInternalMonitoringRoute() function
Name: "test-kube-apiserver-monitoring",
Namespace: "test",
},
}
routemonitor = v1alpha1.RouteMonitor{
ObjectMeta: metav1.ObjectMeta{
// Name must match the expected routemonitor created by the buildInternalMonitoringRouteMonitor() function
Name: "test-kube-apiserver-monitoring",
Namespace: "test",
},
}
)
// Testing
tests := []struct {
// name defines the name of each subtest
name string
// objs defines the object present on-cluster when testing
objs []client.Object
// eval defines the logic used to determine if the test passed or failed, along with the reason for the failure, if applicable
eval func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string)
}{
// Cases
// Test both route&routemonitor
{
name: "no error is returned when both route and routemonitor are present",
objs: []client.Object{
&route,
&routemonitor,
},
eval: func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
if err != nil {
return false, fmt.Sprintf("unexpected error returned: %v", err)
}
return true, ""
},
},
{
name: "route and routemonitor are both deleted when both are present on cluster",
objs: []client.Object{
&route,
&routemonitor,
},
eval: func(_ error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
err := r.Get(ctx, types.NamespacedName{Name: route.Name, Namespace: route.Namespace}, &routev1.Route{})
if !errors.IsNotFound(err) {
return false, fmt.Sprintf("expected route to be deleted, instead got err: %v", err)
}
err = r.Get(ctx, types.NamespacedName{Name: routemonitor.Name, Namespace: routemonitor.Namespace}, &v1alpha1.RouteMonitor{})
if !errors.IsNotFound(err) {
return false, fmt.Sprintf("expected routemonitor to be deleted, instead got err: %v", err)
}
return true, ""
},
},
// Test when route is already gone
{
name: "no error is returned when route does not exist",
objs: []client.Object{
&routemonitor,
},
eval: func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
if err != nil {
return false, fmt.Sprintf("unexpected error returned: %v", err)
}
return true, ""
},
},
{
name: "routemonitor is still deleted when route is not present",
objs: []client.Object{
&routemonitor,
},
eval: func(_ error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
err := r.Get(ctx, types.NamespacedName{Name: routemonitor.Name, Namespace: routemonitor.Namespace}, &v1alpha1.RouteMonitor{})
if !errors.IsNotFound(err) {
return false, fmt.Sprintf("expected routemonitor to have been deleted, instead got err: %v", err)
}
return true, ""
},
},
// Test when routemonitor is already gone
{
name: "no error is returned when routemonitor does not exist",
objs: []client.Object{
&route,
},
eval: func(err error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
if err != nil {
return false, fmt.Sprintf("unexpected error returned: %v", err)
}
return true, ""
},
},
{
name: "route is still deleted when routemonitor is not present",
objs: []client.Object{
&route,
},
eval: func(_ error, r *HostedControlPlaneReconciler) (passed bool, reason string) {
err := r.Get(ctx, types.NamespacedName{Name: route.Name, Namespace: route.Namespace}, &routev1.Route{})
if !errors.IsNotFound(err) {
return false, fmt.Sprintf("expected route to have been deleted, instead got err: %v", err)
}
return true, ""
},
},
}
// Execution
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := newTestReconciler(t, tt.objs...)
err := r.deleteInternalMonitoringObjects(ctx, log, &hcp)
passed, reason := tt.eval(err, r)
if !passed {
t.Errorf("HostedControlPlaneReconciler.deleteInternalMonitoringObjects() error = %v, did not pass due to = %s", err, reason)
}
})
}
}
// newTestReconciler creates a test client containing the following objects
func newTestReconciler(t *testing.T, objs ...client.Object) *HostedControlPlaneReconciler {
var err error
s := scheme.Scheme
err = hypershiftv1beta1.AddToScheme(s)
if err != nil {
t.Errorf("failed to add hypershiftv1beta1 to scheme: %v", err)
}
err = v1alpha1.AddToScheme(s)
if err != nil {
t.Errorf("failed to add v1alpha1 to scheme: %v", err)
}
err = routev1.AddToScheme(s)
if err != nil {
t.Errorf("failed to add routev1 to scheme: %v", err)
}
err = avov1alpha2.AddToScheme(s)
if err != nil {
t.Errorf("unable to add avov1alpha2 scheme to test: %v", err)
}
client := fake.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build()
r := &HostedControlPlaneReconciler{
Client: client,
Scheme: s,
}
return r
}
func TestIsVpcEndpointReady(t *testing.T) {
tests := []struct {
name string
vpcEndpointStatus string
expectedResult bool
expectedError bool
}{
{
name: "VpcEndpoint is available",
vpcEndpointStatus: "available",
expectedResult: true,
expectedError: false,
},
{
name: "VpcEndpoint is pending",
vpcEndpointStatus: "pending",
expectedResult: false,
expectedError: false, // Pending is not an error, just not ready
},
{
name: "VpcEndpoint is rejected",
vpcEndpointStatus: "rejected",
expectedResult: false,
expectedError: true,
},
{
name: "VpcEndpoint is failed",
vpcEndpointStatus: "failed",
expectedResult: false,
expectedError: true,
},
{
name: "VpcEndpoint not found",
vpcEndpointStatus: "",
expectedResult: false,
expectedError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// client := fake.NewClientBuilder().Build()
// Create a mock HostedControlPlane instance
hcp := &hypershiftv1beta1.HostedControlPlane{
ObjectMeta: metav1.ObjectMeta{
Name: "test-hostedcontrolplane",
Namespace: "default",
},
}
r := newTestReconciler(t)
ctx := context.Background()
// r.Create(ctx, hcp)
// Mocking the VpcEndpoint
if tt.vpcEndpointStatus != "" {
vpcEndpointTest := &avov1alpha2.VpcEndpoint{
ObjectMeta: metav1.ObjectMeta{
Name: "private-hcp",
Namespace: "default",
},
Status: avov1alpha2.VpcEndpointStatus{
Status: tt.vpcEndpointStatus,
},
}
err := r.Create(ctx, vpcEndpointTest)
if err != nil {
t.Fatalf("Failed to create mock VpcEndpoint resource: %v", err)
}
}
// Test the function
result, err := r.isVpcEndpointReady(context.Background(), hcp)
// Validate the results
if result != tt.expectedResult {
t.Errorf("expected result %v, but got %v", tt.expectedResult, result)
}
// Check if error status matches expectedError
if (err != nil) != tt.expectedError {
t.Errorf("expected error: %v, but got error: %v", tt.expectedError, err != nil)
}
})
}
}
func TestHostedControlPlaneReconciler_getRHOBSConfig(t *testing.T) {
ctx := context.Background()
// Fallback config from command-line flags
fallbackConfig := RHOBSConfig{
ProbeAPIURL: "https://fallback-api.example.com/probes",
Tenant: "fallback-tenant",
OIDCClientID: "fallback-client-id",
OIDCClientSecret: "fallback-secret",
OIDCIssuerURL: "https://fallback-issuer.example.com",
OnlyPublicClusters: false,
}
tests := []struct {
name string
configMap *corev1.ConfigMap
fallbackConfig RHOBSConfig
expectedRHOBS RHOBSConfig
expectedDynatrace DynatraceConfig
}{
{
name: "ConfigMap not present - uses fallback config",
configMap: nil,
fallbackConfig: fallbackConfig,
expectedRHOBS: fallbackConfig,
expectedDynatrace: DynatraceConfig{Enabled: false}, // Default is disabled
},
{
name: "ConfigMap present with all values - uses ConfigMap values",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: config.OperatorNamespace,
},
Data: map[string]string{
"probe-api-url": "https://configmap-api.example.com/probes",
"probe-tenant": "configmap-tenant",
"oidc-client-id": "configmap-client-id",
"oidc-client-secret": "configmap-secret",
"oidc-issuer-url": "https://configmap-issuer.example.com",
"only-public-clusters": "true",
"dynatrace-enabled": "true",
},
},
fallbackConfig: fallbackConfig,
expectedRHOBS: RHOBSConfig{
ProbeAPIURL: "https://configmap-api.example.com/probes",
Tenant: "configmap-tenant",
OIDCClientID: "configmap-client-id",
OIDCClientSecret: "configmap-secret",
OIDCIssuerURL: "https://configmap-issuer.example.com",
OnlyPublicClusters: true,
},
expectedDynatrace: DynatraceConfig{Enabled: true},
},
{
name: "ConfigMap present with partial values - merges with fallback",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: config.OperatorNamespace,
},
Data: map[string]string{
"probe-api-url": "https://partial-api.example.com/probes",
"probe-tenant": "partial-tenant",
// Other values not set - should use fallback
},
},
fallbackConfig: fallbackConfig,
expectedRHOBS: RHOBSConfig{
ProbeAPIURL: "https://partial-api.example.com/probes",
Tenant: "partial-tenant",
OIDCClientID: "fallback-client-id",
OIDCClientSecret: "fallback-secret",
OIDCIssuerURL: "https://fallback-issuer.example.com",
OnlyPublicClusters: false,
},
expectedDynatrace: DynatraceConfig{Enabled: false}, // Default is disabled when not specified
},
{
name: "ConfigMap present with empty values - uses fallback for empty fields",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: config.OperatorNamespace,
},
Data: map[string]string{
"probe-api-url": "",
"probe-tenant": " ", // whitespace only
"oidc-client-id": "valid-id",
"oidc-client-secret": "",
"oidc-issuer-url": "",
"only-public-clusters": "false",
"dynatrace-enabled": "", // empty defaults to enabled
},
},
fallbackConfig: fallbackConfig,
expectedRHOBS: RHOBSConfig{
ProbeAPIURL: "fallback-api.example.com/probes", // wrong, should be fallback
Tenant: "fallback-tenant", // empty/whitespace uses fallback
OIDCClientID: "valid-id",
OIDCClientSecret: "fallback-secret",
OIDCIssuerURL: "https://fallback-issuer.example.com",
OnlyPublicClusters: false,
},
expectedDynatrace: DynatraceConfig{Enabled: false}, // Empty defaults to disabled
},
{
name: "ConfigMap in wrong namespace - uses fallback config",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: "wrong-namespace",
},
Data: map[string]string{
"probe-api-url": "https://wrong-namespace.example.com/probes",
},
},
fallbackConfig: fallbackConfig,
expectedRHOBS: fallbackConfig,
expectedDynatrace: DynatraceConfig{Enabled: false}, // Default is disabled
},
{
name: "ConfigMap with wrong name - uses fallback config",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "wrong-configmap-name",
Namespace: config.OperatorNamespace,
},
Data: map[string]string{
"probe-api-url": "https://wrong-name.example.com/probes",
},
},
fallbackConfig: fallbackConfig,
expectedRHOBS: fallbackConfig,
expectedDynatrace: DynatraceConfig{Enabled: false}, // Default is disabled
},
{
name: "ConfigMap with Dynatrace enabled",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: config.OperatorNamespace,
},
Data: map[string]string{
"dynatrace-enabled": "true",
},
},
fallbackConfig: fallbackConfig,
expectedRHOBS: fallbackConfig,
expectedDynatrace: DynatraceConfig{Enabled: true},
},
{
name: "ConfigMap with Dynatrace disabled explicitly",
configMap: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{