-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdaemonset_test.go
More file actions
713 lines (624 loc) · 22.1 KB
/
Copy pathdaemonset_test.go
File metadata and controls
713 lines (624 loc) · 22.1 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
package spiffe_csi_driver
import (
"context"
"errors"
"reflect"
"testing"
"github.com/go-logr/logr"
"github.com/openshift/zero-trust-workload-identity-manager/api/v1alpha1"
"github.com/openshift/zero-trust-workload-identity-manager/pkg/client/fakes"
"github.com/openshift/zero-trust-workload-identity-manager/pkg/controller/status"
"github.com/openshift/zero-trust-workload-identity-manager/pkg/controller/utils"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func TestGenerateSpiffeCsiDriverDaemonSet(t *testing.T) {
// Mock the utility functions that are called in the main function
// These would need to be properly mocked in a real test environment
config := v1alpha1.SpiffeCSIDriverSpec{
AgentSocketPath: "/run/spire/agent-sockets",
PluginName: "csi.spiffe.io",
}
daemonSet := generateSpiffeCsiDriverDaemonSet(config)
// Test ObjectMeta
if daemonSet.Name != "spire-spiffe-csi-driver" {
t.Errorf("Expected name 'spire-spiffe-csi-driver', got '%s'", daemonSet.Name)
}
if daemonSet.Namespace != utils.GetOperatorNamespace() {
t.Errorf("Expected namespace '%s', got '%s'", utils.GetOperatorNamespace(), daemonSet.Namespace)
}
expectedLabels := utils.SpiffeCSIDriverLabels(nil)
if !reflect.DeepEqual(daemonSet.Labels, expectedLabels) {
t.Errorf("Expected labels %v, got %v", expectedLabels, daemonSet.Labels)
}
// Test Selector - using centralized labeling approach
allLabels := utils.SpiffeCSIDriverLabels(nil)
expectedSelectorLabels := map[string]string{
"app.kubernetes.io/name": allLabels["app.kubernetes.io/name"],
"app.kubernetes.io/instance": allLabels["app.kubernetes.io/instance"],
"app.kubernetes.io/component": allLabels["app.kubernetes.io/component"],
}
if !reflect.DeepEqual(daemonSet.Spec.Selector.MatchLabels, expectedSelectorLabels) {
t.Errorf("Expected selector labels %v, got %v", expectedSelectorLabels, daemonSet.Spec.Selector.MatchLabels)
}
// Test UpdateStrategy
if daemonSet.Spec.UpdateStrategy.Type != appsv1.RollingUpdateDaemonSetStrategyType {
t.Errorf("Expected update strategy type '%s', got '%s'",
appsv1.RollingUpdateDaemonSetStrategyType, daemonSet.Spec.UpdateStrategy.Type)
}
expectedMaxUnavailable := &intstr.IntOrString{
Type: intstr.Int,
IntVal: 1,
}
if !reflect.DeepEqual(daemonSet.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable, expectedMaxUnavailable) {
t.Errorf("Expected MaxUnavailable %v, got %v",
expectedMaxUnavailable, daemonSet.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable)
}
// Test PodTemplateSpec Labels
if !reflect.DeepEqual(daemonSet.Spec.Template.Labels, allLabels) {
t.Errorf("Expected template labels %v, got %v", allLabels, daemonSet.Spec.Template.Labels)
}
// Test ServiceAccountName
if daemonSet.Spec.Template.Spec.ServiceAccountName != "spire-spiffe-csi-driver" {
t.Errorf("Expected service account name 'spire-spiffe-csi-driver', got '%s'",
daemonSet.Spec.Template.Spec.ServiceAccountName)
}
// Test InitContainers
if len(daemonSet.Spec.Template.Spec.InitContainers) != 1 {
t.Errorf("Expected 1 init container, got %d", len(daemonSet.Spec.Template.Spec.InitContainers))
}
initContainer := daemonSet.Spec.Template.Spec.InitContainers[0]
testInitContainer(t, initContainer)
// Test Containers
if len(daemonSet.Spec.Template.Spec.Containers) != 2 {
t.Errorf("Expected 2 containers, got %d", len(daemonSet.Spec.Template.Spec.Containers))
}
spiffeContainer := daemonSet.Spec.Template.Spec.Containers[0]
registrarContainer := daemonSet.Spec.Template.Spec.Containers[1]
testSpiffeContainer(t, spiffeContainer)
testNodeDriverRegistrarContainer(t, registrarContainer)
// Test Volumes
if len(daemonSet.Spec.Template.Spec.Volumes) != 4 {
t.Errorf("Expected 4 volumes, got %d", len(daemonSet.Spec.Template.Spec.Volumes))
}
testVolumes(t, daemonSet.Spec.Template.Spec.Volumes)
}
func TestGenerateSpiffeCsiDriverDaemonSetWithCustomConfig(t *testing.T) {
// Test with custom plugin name and agent socket path
config := v1alpha1.SpiffeCSIDriverSpec{
AgentSocketPath: "/custom/agent/socket",
PluginName: "csi.custom.io",
}
daemonSet := generateSpiffeCsiDriverDaemonSet(config)
// Verify plugin name is used in container args
spiffeContainer := daemonSet.Spec.Template.Spec.Containers[0]
expectedArgs := []string{
"-workload-api-socket-dir", "/spire-agent-socket",
"-plugin-name", "csi.custom.io",
"-csi-socket-path", "/spiffe-csi/csi.sock",
}
if !reflect.DeepEqual(spiffeContainer.Args, expectedArgs) {
t.Errorf("Expected spiffe container args %v, got %v", expectedArgs, spiffeContainer.Args)
}
// Verify plugin name is used in node-driver-registrar args
registrarContainer := daemonSet.Spec.Template.Spec.Containers[1]
expectedRegistrarArgs := []string{
"-csi-address", "/spiffe-csi/csi.sock",
"-kubelet-registration-path", "/var/lib/kubelet/plugins/csi.custom.io/csi.sock",
"-health-port", "9809",
}
if !reflect.DeepEqual(registrarContainer.Args, expectedRegistrarArgs) {
t.Errorf("Expected registrar container args %v, got %v", expectedRegistrarArgs, registrarContainer.Args)
}
// Verify custom agent socket path is used in volumes
volumes := daemonSet.Spec.Template.Spec.Volumes
agentSocketVolume := volumes[0] // spire-agent-socket-dir
if agentSocketVolume.HostPath.Path != "/custom/agent/socket" {
t.Errorf("Expected agent socket hostPath '/custom/agent/socket', got '%s'", agentSocketVolume.HostPath.Path)
}
// Verify plugin name is used in CSI socket directory path
csiSocketVolume := volumes[1] // spiffe-csi-socket-dir
expectedCSIPath := "/var/lib/kubelet/plugins/csi.custom.io"
if csiSocketVolume.HostPath.Path != expectedCSIPath {
t.Errorf("Expected CSI socket hostPath '%s', got '%s'", expectedCSIPath, csiSocketVolume.HostPath.Path)
}
}
func testInitContainer(t *testing.T, container corev1.Container) {
t.Helper()
if container.Name != "set-context" {
t.Errorf("Expected init container name 'set-context', got '%s'", container.Name)
}
if container.Image != "registry.redhat.io/ubi10/ubi:10.1" {
t.Errorf("Expected init container image 'registry.redhat.io/ubi10/ubi:10.1', got '%s'", container.Image)
}
expectedCommand := []string{"chcon", "-Rvt", "container_file_t", "spire-agent-socket/"}
if !reflect.DeepEqual(container.Command, expectedCommand) {
t.Errorf("Expected init container command %v, got %v", expectedCommand, container.Command)
}
if container.ImagePullPolicy != corev1.PullAlways {
t.Errorf("Expected init container pull policy '%s', got '%s'", corev1.PullAlways, container.ImagePullPolicy)
}
// Test SecurityContext
if container.SecurityContext.Privileged == nil || !*container.SecurityContext.Privileged {
t.Error("Expected init container to be privileged")
}
expectedCapabilities := []corev1.Capability{"all"}
if !reflect.DeepEqual(container.SecurityContext.Capabilities.Drop, expectedCapabilities) {
t.Errorf("Expected init container capabilities drop %v, got %v",
expectedCapabilities, container.SecurityContext.Capabilities.Drop)
}
// Test VolumeMounts
if len(container.VolumeMounts) != 1 {
t.Errorf("Expected 1 volume mount for init container, got %d", len(container.VolumeMounts))
}
expectedVolumeMount := corev1.VolumeMount{
Name: "spire-agent-socket-dir",
MountPath: "/spire-agent-socket",
}
if !reflect.DeepEqual(container.VolumeMounts[0], expectedVolumeMount) {
t.Errorf("Expected init container volume mount %v, got %v", expectedVolumeMount, container.VolumeMounts[0])
}
// Test termination message settings
if container.TerminationMessagePath != "/dev/termination-log" {
t.Errorf("Expected termination message path '/dev/termination-log', got '%s'", container.TerminationMessagePath)
}
if container.TerminationMessagePolicy != corev1.TerminationMessageReadFile {
t.Errorf("Expected termination message policy '%s', got '%s'",
corev1.TerminationMessageReadFile, container.TerminationMessagePolicy)
}
}
func testSpiffeContainer(t *testing.T, container corev1.Container) {
t.Helper()
if container.Name != "spiffe-csi-driver" {
t.Errorf("Expected container name 'spiffe-csi-driver', got '%s'", container.Name)
}
// Note: In a real test, you'd mock utils.GetSpiffeCSIDriverImage()
if container.Image != utils.GetSpiffeCSIDriverImage() {
t.Errorf("Expected container image from utils.GetSpiffeCSIDriverImage(), got '%s'", container.Image)
}
expectedArgs := []string{
"-workload-api-socket-dir", "/spire-agent-socket",
"-plugin-name", "csi.spiffe.io",
"-csi-socket-path", "/spiffe-csi/csi.sock",
}
if !reflect.DeepEqual(container.Args, expectedArgs) {
t.Errorf("Expected container args %v, got %v", expectedArgs, container.Args)
}
if container.ImagePullPolicy != corev1.PullIfNotPresent {
t.Errorf("Expected container pull policy '%s', got '%s'", corev1.PullIfNotPresent, container.ImagePullPolicy)
}
// Test Environment Variables
if len(container.Env) != 1 {
t.Errorf("Expected 1 environment variable, got %d", len(container.Env))
}
expectedEnv := corev1.EnvVar{
Name: "MY_NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "spec.nodeName",
},
},
}
if !reflect.DeepEqual(container.Env[0], expectedEnv) {
t.Errorf("Expected environment variable %v, got %v", expectedEnv, container.Env[0])
}
// Test SecurityContext
if container.SecurityContext.ReadOnlyRootFilesystem == nil || !*container.SecurityContext.ReadOnlyRootFilesystem {
t.Error("Expected container to have read-only root filesystem")
}
if container.SecurityContext.Privileged == nil || !*container.SecurityContext.Privileged {
t.Error("Expected container to be privileged")
}
expectedCapabilities := []corev1.Capability{"all"}
if !reflect.DeepEqual(container.SecurityContext.Capabilities.Drop, expectedCapabilities) {
t.Errorf("Expected container capabilities drop %v, got %v",
expectedCapabilities, container.SecurityContext.Capabilities.Drop)
}
// Test VolumeMounts
if len(container.VolumeMounts) != 3 {
t.Errorf("Expected 3 volume mounts for spiffe container, got %d", len(container.VolumeMounts))
}
expectedVolumeMounts := []corev1.VolumeMount{
{
Name: "spire-agent-socket-dir",
MountPath: "/spire-agent-socket",
ReadOnly: true,
},
{
Name: "spiffe-csi-socket-dir",
MountPath: "/spiffe-csi",
},
{
Name: "mountpoint-dir",
MountPath: "/var/lib/kubelet/pods",
MountPropagation: mountPropagationPtr(corev1.MountPropagationBidirectional),
},
}
for i, expectedMount := range expectedVolumeMounts {
if !reflect.DeepEqual(container.VolumeMounts[i], expectedMount) {
t.Errorf("Expected volume mount %d to be %v, got %v", i, expectedMount, container.VolumeMounts[i])
}
}
}
func testNodeDriverRegistrarContainer(t *testing.T, container corev1.Container) {
t.Helper()
if container.Name != "node-driver-registrar" {
t.Errorf("Expected container name 'node-driver-registrar', got '%s'", container.Name)
}
// Note: In a real test, you'd mock utils.GetNodeDriverRegistrarImage()
if container.Image != utils.GetNodeDriverRegistrarImage() {
t.Errorf("Expected container image from utils.GetNodeDriverRegistrarImage(), got '%s'", container.Image)
}
expectedArgs := []string{
"-csi-address", "/spiffe-csi/csi.sock",
"-kubelet-registration-path", "/var/lib/kubelet/plugins/csi.spiffe.io/csi.sock",
"-health-port", "9809",
}
if !reflect.DeepEqual(container.Args, expectedArgs) {
t.Errorf("Expected container args %v, got %v", expectedArgs, container.Args)
}
if container.ImagePullPolicy != corev1.PullIfNotPresent {
t.Errorf("Expected container pull policy '%s', got '%s'", corev1.PullIfNotPresent, container.ImagePullPolicy)
}
// Test VolumeMounts
if len(container.VolumeMounts) != 2 {
t.Errorf("Expected 2 volume mounts for registrar container, got %d", len(container.VolumeMounts))
}
expectedVolumeMounts := []corev1.VolumeMount{
{
Name: "spiffe-csi-socket-dir",
MountPath: "/spiffe-csi",
},
{
Name: "kubelet-plugin-registration-dir",
MountPath: "/registration",
},
}
for i, expectedMount := range expectedVolumeMounts {
if !reflect.DeepEqual(container.VolumeMounts[i], expectedMount) {
t.Errorf("Expected volume mount %d to be %v, got %v", i, expectedMount, container.VolumeMounts[i])
}
}
// Test Ports
if len(container.Ports) != 1 {
t.Errorf("Expected 1 port for registrar container, got %d", len(container.Ports))
}
expectedPort := corev1.ContainerPort{
ContainerPort: 9809,
Name: "healthz",
}
if !reflect.DeepEqual(container.Ports[0], expectedPort) {
t.Errorf("Expected port %v, got %v", expectedPort, container.Ports[0])
}
// Test LivenessProbe
if container.LivenessProbe == nil {
t.Error("Expected liveness probe to be set")
} else {
if container.LivenessProbe.InitialDelaySeconds != 5 {
t.Errorf("Expected liveness probe initial delay 5, got %d", container.LivenessProbe.InitialDelaySeconds)
}
if container.LivenessProbe.TimeoutSeconds != 5 {
t.Errorf("Expected liveness probe timeout 5, got %d", container.LivenessProbe.TimeoutSeconds)
}
if container.LivenessProbe.HTTPGet == nil {
t.Error("Expected HTTPGet probe handler")
} else {
if container.LivenessProbe.HTTPGet.Path != "/healthz" {
t.Errorf("Expected probe path '/healthz', got '%s'", container.LivenessProbe.HTTPGet.Path)
}
expectedPort := intstr.FromString("healthz")
if !reflect.DeepEqual(container.LivenessProbe.HTTPGet.Port, expectedPort) {
t.Errorf("Expected probe port %v, got %v", expectedPort, container.LivenessProbe.HTTPGet.Port)
}
}
}
// Test SecurityContext
if container.SecurityContext == nil {
t.Error("Expected SecurityContext to be set")
} else {
if container.SecurityContext.Privileged == nil || !*container.SecurityContext.Privileged {
t.Error("Expected node-driver-registrar container to be privileged")
}
if container.SecurityContext.Capabilities == nil {
t.Error("Expected Capabilities to be set")
} else {
expectedCapabilities := []corev1.Capability{"all"}
if !reflect.DeepEqual(container.SecurityContext.Capabilities.Drop, expectedCapabilities) {
t.Errorf("Expected node-driver-registrar container capabilities drop %v, got %v",
expectedCapabilities, container.SecurityContext.Capabilities.Drop)
}
}
}
}
func testVolumes(t *testing.T, volumes []corev1.Volume) {
t.Helper()
expectedVolumes := []corev1.Volume{
{
Name: "spire-agent-socket-dir",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/run/spire/agent-sockets",
Type: hostPathTypePtr(corev1.HostPathDirectoryOrCreate),
},
},
},
{
Name: "spiffe-csi-socket-dir",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/lib/kubelet/plugins/csi.spiffe.io",
Type: hostPathTypePtr(corev1.HostPathDirectoryOrCreate),
},
},
},
{
Name: "mountpoint-dir",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/lib/kubelet/pods",
Type: hostPathTypePtr(corev1.HostPathDirectory),
},
},
},
{
Name: "kubelet-plugin-registration-dir",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/lib/kubelet/plugins_registry",
Type: hostPathTypePtr(corev1.HostPathDirectory),
},
},
},
}
for i, expectedVolume := range expectedVolumes {
if !reflect.DeepEqual(volumes[i], expectedVolume) {
t.Errorf("Expected volume %d to be %v, got %v", i, expectedVolume, volumes[i])
}
}
}
func TestHostPathTypePtr(t *testing.T) {
tests := []struct {
name string
input corev1.HostPathType
expected corev1.HostPathType
}{
{
name: "DirectoryOrCreate",
input: corev1.HostPathDirectoryOrCreate,
expected: corev1.HostPathDirectoryOrCreate,
},
{
name: "Directory",
input: corev1.HostPathDirectory,
expected: corev1.HostPathDirectory,
},
{
name: "File",
input: corev1.HostPathFile,
expected: corev1.HostPathFile,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := hostPathTypePtr(tt.input)
if result == nil {
t.Error("Expected non-nil pointer")
return
}
if *result != tt.expected {
t.Errorf("Expected %v, got %v", tt.expected, *result)
}
})
}
}
func TestMountPropagationPtr(t *testing.T) {
tests := []struct {
name string
input corev1.MountPropagationMode
expected corev1.MountPropagationMode
}{
{
name: "Bidirectional",
input: corev1.MountPropagationBidirectional,
expected: corev1.MountPropagationBidirectional,
},
{
name: "HostToContainer",
input: corev1.MountPropagationHostToContainer,
expected: corev1.MountPropagationHostToContainer,
},
{
name: "None",
input: corev1.MountPropagationNone,
expected: corev1.MountPropagationNone,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := mountPropagationPtr(tt.input)
if result == nil {
t.Error("Expected non-nil pointer")
return
}
if *result != tt.expected {
t.Errorf("Expected %v, got %v", tt.expected, *result)
}
})
}
}
// TestReconcileDaemonSet tests the reconcileDaemonSet function
func TestReconcileDaemonSet(t *testing.T) {
tests := []struct {
name string
notFound bool
getError error
createError error
updateError error
createOnlyMode bool
useEmptyScheme bool
expectError bool
expectCreate bool
expectUpdate bool
}{
{
name: "create success",
notFound: true,
expectError: false,
expectCreate: true,
},
{
name: "create error",
notFound: true,
createError: errors.New("create failed"),
expectError: true,
},
{
name: "get error",
getError: errors.New("connection refused"),
expectError: true,
},
{
name: "update success",
expectError: false,
expectUpdate: true,
},
{
name: "update error",
updateError: errors.New("update conflict"),
expectError: true,
},
{
name: "create only mode skips update",
createOnlyMode: true,
expectError: false,
expectUpdate: false,
},
{
name: "set controller reference error",
useEmptyScheme: true,
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakeClient := &fakes.FakeCustomCtrlClient{}
var reconciler *SpiffeCsiReconciler
if tt.useEmptyScheme {
reconciler = &SpiffeCsiReconciler{
ctrlClient: fakeClient,
ctx: context.Background(),
log: logr.Discard(),
scheme: runtime.NewScheme(),
eventRecorder: record.NewFakeRecorder(100),
}
} else {
reconciler = newDaemonSetTestReconciler(fakeClient)
}
driver := createDaemonSetTestDriver()
driver.Spec.Labels = map[string]string{"new": "label"}
statusMgr := status.NewManager(fakeClient)
if tt.notFound {
fakeClient.GetReturns(kerrors.NewNotFound(schema.GroupResource{}, "spiffe-csi-driver"))
} else if tt.getError != nil {
fakeClient.GetReturns(tt.getError)
} else {
existingDS := &appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "spiffe-csi-driver",
Namespace: utils.GetOperatorNamespace(),
ResourceVersion: "123",
Labels: map[string]string{"old": "label"},
},
}
fakeClient.GetStub = func(ctx context.Context, key client.ObjectKey, obj client.Object) error {
if ds, ok := obj.(*appsv1.DaemonSet); ok {
*ds = *existingDS
}
return nil
}
}
fakeClient.CreateReturns(tt.createError)
fakeClient.UpdateReturns(tt.updateError)
err := reconciler.reconcileDaemonSet(context.Background(), driver, statusMgr, tt.createOnlyMode)
if tt.expectError && err == nil {
t.Error("Expected error but got none")
}
if !tt.expectError && err != nil {
t.Errorf("Expected no error, got: %v", err)
}
if tt.expectCreate && fakeClient.CreateCallCount() != 1 {
t.Errorf("Expected Create to be called once, got %d", fakeClient.CreateCallCount())
}
if tt.expectUpdate && fakeClient.UpdateCallCount() != 1 {
t.Errorf("Expected Update to be called once, got %d", fakeClient.UpdateCallCount())
}
if tt.createOnlyMode && fakeClient.UpdateCallCount() != 0 {
t.Error("Expected Update not to be called in create-only mode")
}
})
}
}
// TestNeedsUpdate tests the needsUpdate function
func TestNeedsUpdate(t *testing.T) {
t.Run("same daemonsets do not need update", func(t *testing.T) {
ds := appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Labels: map[string]string{"app": "test"},
},
}
if needsUpdate(ds, ds) {
t.Error("Expected same daemonsets not to need update")
}
})
t.Run("different labels need update", func(t *testing.T) {
current := appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Labels: map[string]string{"old": "label"},
},
}
desired := appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Labels: map[string]string{"new": "label"},
},
}
if !needsUpdate(current, desired) {
t.Error("Expected different labels to need update")
}
})
}
// newDaemonSetTestReconciler creates a reconciler for DaemonSet tests
func newDaemonSetTestReconciler(fakeClient *fakes.FakeCustomCtrlClient) *SpiffeCsiReconciler {
scheme := runtime.NewScheme()
_ = v1alpha1.AddToScheme(scheme)
_ = appsv1.AddToScheme(scheme)
return &SpiffeCsiReconciler{
ctrlClient: fakeClient,
ctx: context.Background(),
log: logr.Discard(),
scheme: scheme,
eventRecorder: record.NewFakeRecorder(100),
}
}
// createDaemonSetTestDriver creates a test SpiffeCSIDriver for DaemonSet tests
func createDaemonSetTestDriver() *v1alpha1.SpiffeCSIDriver {
return &v1alpha1.SpiffeCSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "cluster",
UID: "test-uid",
},
Spec: v1alpha1.SpiffeCSIDriverSpec{
AgentSocketPath: "/run/spire/agent-sockets",
PluginName: "csi.spiffe.io",
},
}
}