forked from kubernetes-sigs/azurefile-csi-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_test.go
More file actions
1407 lines (1314 loc) · 38.7 KB
/
utils_test.go
File metadata and controls
1407 lines (1314 loc) · 38.7 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
/*
Copyright 2020 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 azurefile
import (
"context"
"errors"
"fmt"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/container-storage-interface/spec/lib/go/csi"
nodev1 "k8s.io/api/node/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
fake "k8s.io/client-go/kubernetes/fake"
utiltesting "k8s.io/client-go/util/testing"
"k8s.io/kubernetes/pkg/volume"
azureconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config"
)
func TestSimpleLockEntry(t *testing.T) {
testLockMap := newLockMap()
callbackChan1 := make(chan interface{})
go testLockMap.lockAndCallback(t, "entry1", callbackChan1)
ensureCallbackHappens(t, callbackChan1)
}
func TestSimpleLockUnlockEntry(t *testing.T) {
testLockMap := newLockMap()
callbackChan1 := make(chan interface{})
go testLockMap.lockAndCallback(t, "entry1", callbackChan1)
ensureCallbackHappens(t, callbackChan1)
testLockMap.UnlockEntry("entry1")
}
func TestConcurrentLockEntry(t *testing.T) {
testLockMap := newLockMap()
callbackChan1 := make(chan interface{})
callbackChan2 := make(chan interface{})
go testLockMap.lockAndCallback(t, "entry1", callbackChan1)
ensureCallbackHappens(t, callbackChan1)
go testLockMap.lockAndCallback(t, "entry1", callbackChan2)
ensureNoCallback(t, callbackChan2)
testLockMap.UnlockEntry("entry1")
ensureCallbackHappens(t, callbackChan2)
testLockMap.UnlockEntry("entry1")
}
func (lm *lockMap) lockAndCallback(_ *testing.T, entry string, callbackChan chan<- interface{}) {
lm.LockEntry(entry)
callbackChan <- true
}
var callbackTimeout = 2 * time.Second
func ensureCallbackHappens(t *testing.T, callbackChan <-chan interface{}) bool {
select {
case <-callbackChan:
return true
case <-time.After(callbackTimeout):
t.Fatalf("timed out waiting for callback")
return false
}
}
func ensureNoCallback(t *testing.T, callbackChan <-chan interface{}) bool {
select {
case <-callbackChan:
t.Fatalf("unexpected callback")
return false
case <-time.After(callbackTimeout):
return true
}
}
func TestUnlockEntryNotExists(t *testing.T) {
testLockMap := newLockMap()
callbackChan1 := make(chan interface{})
go testLockMap.lockAndCallback(t, "entry1", callbackChan1)
ensureCallbackHappens(t, callbackChan1)
// entry2 does not exist
testLockMap.UnlockEntry("entry2")
testLockMap.UnlockEntry("entry1")
}
func TestIsDiskFsType(t *testing.T) {
tests := []struct {
fsType string
expectedResult bool
}{
{
fsType: "ext4",
expectedResult: true,
},
{
fsType: "ext3",
expectedResult: true,
},
{
fsType: "ext2",
expectedResult: true,
},
{
fsType: "xfs",
expectedResult: true,
},
{
fsType: "",
expectedResult: false,
},
{
fsType: "cifs",
expectedResult: false,
},
{
fsType: "invalid",
expectedResult: false,
},
}
for _, test := range tests {
result := isDiskFsType(test.fsType)
if result != test.expectedResult {
t.Errorf("isDiskFsType(%s) returned with %v, not equal to %v", test.fsType, result, test.expectedResult)
}
}
}
func TestIsSupportedShareNamePrefix(t *testing.T) {
tests := []struct {
prefix string
expectedResult bool
}{
{
prefix: "",
expectedResult: true,
},
{
prefix: "ext3",
expectedResult: true,
},
{
prefix: "ext-2",
expectedResult: true,
},
{
prefix: "-xfs",
expectedResult: false,
},
{
prefix: "Absdf",
expectedResult: false,
},
{
prefix: "tooooooooooooooooooooooooolong",
expectedResult: false,
},
{
prefix: "+invalid",
expectedResult: false,
},
{
prefix: " invalidspace",
expectedResult: false,
},
}
for _, test := range tests {
result := isSupportedShareNamePrefix(test.prefix)
if result != test.expectedResult {
t.Errorf("isSupportedShareNamePrefix(%s) returned with %v, not equal to %v", test.prefix, result, test.expectedResult)
}
}
}
func TestIsSupportedFsType(t *testing.T) {
tests := []struct {
fsType string
expectedResult bool
}{
{
fsType: "ext4",
expectedResult: true,
},
{
fsType: "ext3",
expectedResult: true,
},
{
fsType: "ext2",
expectedResult: true,
},
{
fsType: "xfs",
expectedResult: true,
},
{
fsType: "",
expectedResult: true,
},
{
fsType: "cifs",
expectedResult: true,
},
{
fsType: "smb",
expectedResult: true,
},
{
fsType: "invalid",
expectedResult: false,
},
}
for _, test := range tests {
result := isSupportedFsType(test.fsType)
if result != test.expectedResult {
t.Errorf("isSupportedFsType(%s) returned with %v, not equal to %v", test.fsType, result, test.expectedResult)
}
}
}
func TestIsSupportedFSGroupChangePolicy(t *testing.T) {
tests := []struct {
policy string
expectedResult bool
}{
{
policy: "",
expectedResult: true,
},
{
policy: "None",
expectedResult: true,
},
{
policy: "Always",
expectedResult: true,
},
{
policy: "OnRootMismatch",
expectedResult: true,
},
{
policy: "onRootMismatch",
expectedResult: false,
},
{
policy: "invalid",
expectedResult: false,
},
}
for _, test := range tests {
result := isSupportedFSGroupChangePolicy(test.policy)
if result != test.expectedResult {
t.Errorf("isSupportedFSGroupChangePolicy(%s) returned with %v, not equal to %v", test.policy, result, test.expectedResult)
}
}
}
func TestIsRetriableError(t *testing.T) {
tests := []struct {
desc string
rpcErr error
expectedBool bool
}{
{
desc: "non-retriable error",
rpcErr: nil,
expectedBool: false,
},
{
desc: "accountNotProvisioned",
rpcErr: errors.New("could not get storage key for storage account : could not get storage key for storage account f233333: Retriable: true, RetryAfter: 0001-01-01 00:00:00 +0000 UTC, HTTPStatusCode: 409, RawError: storage.AccountsClient#ListKeys: Failure sending request: StatusCode=409 -- Original Error: autorest/azure: Service returned an error. Status=<nil> Code=\"StorageAccountIsNotProvisioned\" Message=\"The storage account provisioning state must be 'Succeeded' before executing the operation.\""),
expectedBool: true,
},
{
desc: "tooManyRequests",
rpcErr: errors.New("could not get storage key for storage account : could not list storage accounts for account type Premium_LRS: Retriable: true, RetryAfter: 0001-01-01 00:00:00 +0000 UTC m=+231.866923225, HTTPStatusCode: 429, RawError: storage.AccountsClient#ListByResourceGroup: Failure responding to request: StatusCode=429 -- Original Error: autorest/azure: Service returned an error. Status=429 Code=\"TooManyRequests\" Message=\"The request is being throttled as the limit has been reached for operation type - List. For more information, see - https://aka.ms/srpthrottlinglimits\""),
expectedBool: true,
},
{
desc: "shareBeingDeleted",
rpcErr: errors.New("storage.FileSharesClient#Create: Failure sending request: StatusCode=409 -- Original Error: autorest/azure: Service returned an error. Status=<nil> Code=\"ShareBeingDeleted\" Message=\"The specified share is being deleted. Try operation later.\""),
expectedBool: true,
},
{
desc: "clientThrottled",
rpcErr: errors.New("could not list storage accounts for account type : Retriable: true, RetryAfter: 16s, HTTPStatusCode: 0, RawError: azure cloud provider throttled for operation StorageAccountListByResourceGroup with reason \"client throttled\""),
expectedBool: true,
},
}
for _, test := range tests {
result := isRetriableError(test.rpcErr)
if result != test.expectedBool {
t.Errorf("desc: (%s), input: rpcErr(%v), isRetriableError returned with bool(%v), not equal to expectedBool(%v)",
test.desc, test.rpcErr, result, test.expectedBool)
}
}
}
func TestSleepIfThrottled(t *testing.T) {
start := time.Now()
sleepIfThrottled(errors.New("tooManyRequests"), 10)
elapsed := time.Since(start)
if elapsed.Seconds() < 10 {
t.Errorf("Expected sleep time(%d), Actual sleep time(%f)", 10, elapsed.Seconds())
}
}
func TestGetRetryAfterSeconds(t *testing.T) {
tests := []struct {
desc string
err error
expected int
}{
{
desc: "nil error",
err: nil,
expected: 0,
},
{
desc: "no match",
err: errors.New("no match"),
expected: 0,
},
{
desc: "match",
err: errors.New("RetryAfter: 10s"),
expected: 10,
},
{
desc: "match error message",
err: errors.New("could not list storage accounts for account type Premium_LRS: Retriable: true, RetryAfter: 217s, HTTPStatusCode: 0, RawError: azure cloud provider throttled for operation StorageAccountListByResourceGroup with reason \"client throttled\""),
expected: 217,
},
{
desc: "match error message exceeds 1200s",
err: errors.New("could not list storage accounts for account type Premium_LRS: Retriable: true, RetryAfter: 2170s, HTTPStatusCode: 0, RawError: azure cloud provider throttled for operation StorageAccountListByResourceGroup with reason \"client throttled\""),
expected: maxThrottlingSleepSec,
},
}
for _, test := range tests {
result := getRetryAfterSeconds(test.err)
if result != test.expected {
t.Errorf("desc: (%s), input: err(%v), getRetryAfterSeconds returned with int(%d), not equal to expected(%d)",
test.desc, test.err, result, test.expected)
}
}
}
func TestCreateStorageAccountSecret(t *testing.T) {
result := createStorageAccountSecret("TestAccountName", "TestAccountKey")
if result[defaultSecretAccountName] != "TestAccountName" || result[defaultSecretAccountKey] != "TestAccountKey" {
t.Errorf("Expected account name(%s), Actual account name(%s); Expected account key(%s), Actual account key(%s)", "TestAccountName", result[defaultSecretAccountName], "TestAccountKey", result[defaultSecretAccountKey])
}
}
func TestConvertTagsToMap(t *testing.T) {
tests := []struct {
desc string
tags string
tagsDelimiter string
expectedError error
}{
{
desc: "Invalid tag",
tags: "invalid,test,tag",
tagsDelimiter: ",",
expectedError: errors.New("Tags 'invalid,test,tag' are invalid, the format should like: 'key1=value1,key2=value2'"),
},
{
desc: "Invalid key",
tags: "=test",
tagsDelimiter: ",",
expectedError: errors.New("Tags '=test' are invalid, the format should like: 'key1=value1,key2=value2'"),
},
{
desc: "Valid tags",
tags: "testTag=testValue",
tagsDelimiter: ",",
expectedError: nil,
},
{
desc: "should return success for empty tagsDelimiter",
tags: "key1=value1,key2=value2",
tagsDelimiter: "",
expectedError: nil,
},
{
desc: "should return success for special tagsDelimiter and tag values containing commas and equal sign",
tags: "key1=aGVsbG8=;key2=value-2, value-3",
tagsDelimiter: ";",
expectedError: nil,
},
}
for _, test := range tests {
_, err := ConvertTagsToMap(test.tags, test.tagsDelimiter)
if !reflect.DeepEqual(err, test.expectedError) {
t.Errorf("test[%s]: unexpected error: %v, expected error: %v", test.desc, err, test.expectedError)
}
}
}
func TestChmodIfPermissionMismatch(t *testing.T) {
skipIfTestingOnWindows(t)
permissionMatchingPath, _ := getWorkDirPath("permissionMatchingPath")
_ = makeDir(permissionMatchingPath, 0755)
_ = os.Chmod(permissionMatchingPath, 0755&^os.ModeSetgid) // clear setgid bit
defer os.RemoveAll(permissionMatchingPath)
permissionMismatchPath, _ := getWorkDirPath("permissionMismatchPath")
_ = makeDir(permissionMismatchPath, 0721)
_ = os.Chmod(permissionMismatchPath, 0721&^os.ModeSetgid) // clear setgid bit
defer os.RemoveAll(permissionMismatchPath)
permissionMatchGidMismatchPath, _ := getWorkDirPath("permissionMatchGidMismatchPath")
_ = makeDir(permissionMatchGidMismatchPath, 0755)
_ = os.Chmod(permissionMatchGidMismatchPath, 0755|os.ModeSetgid) // Setgid bit is set
defer os.RemoveAll(permissionMatchGidMismatchPath)
permissionMismatchGidMismatch, _ := getWorkDirPath("permissionMismatchGidMismatch")
_ = makeDir(permissionMismatchGidMismatch, 0721)
_ = os.Chmod(permissionMismatchGidMismatch, 0721|os.ModeSetgid) // Setgid bit is set
defer os.RemoveAll(permissionMismatchGidMismatch)
tests := []struct {
desc string
path string
mode os.FileMode
expectedPerms os.FileMode
expectedGidBit bool
expectedError error
}{
{
desc: "Invalid path",
path: "invalid-path",
mode: 0755,
expectedError: fmt.Errorf("CreateFile invalid-path: The system cannot find the file specified"),
},
{
desc: "permission matching path",
path: permissionMatchingPath,
mode: 0755,
expectedPerms: 0755,
expectedGidBit: false,
expectedError: nil,
},
{
desc: "permission mismatch path",
path: permissionMismatchPath,
mode: 0755,
expectedPerms: 0755,
expectedGidBit: false,
expectedError: nil,
},
{
desc: "only match the permission mode bits",
path: permissionMatchGidMismatchPath,
mode: 0755,
expectedPerms: 0755,
expectedGidBit: true,
expectedError: nil,
},
{
desc: "only change the permission mode bits when gid is set",
path: permissionMismatchGidMismatch,
mode: 0755,
expectedPerms: 0755,
expectedGidBit: true,
expectedError: nil,
},
{
desc: "only change the permission mode bits when gid is not set but mode bits have gid set",
path: permissionMismatchPath,
mode: 02755,
expectedPerms: 0755,
expectedGidBit: false,
expectedError: nil,
},
}
for _, test := range tests {
err := chmodIfPermissionMismatch(test.path, test.mode)
if !reflect.DeepEqual(err, test.expectedError) {
if err == nil || test.expectedError == nil && !strings.Contains(err.Error(), test.expectedError.Error()) {
t.Errorf("test[%s]: unexpected error: %v, expected error: %v", test.desc, err, test.expectedError)
}
}
if test.expectedError == nil {
info, _ := os.Lstat(test.path)
if test.expectedError == nil && (info.Mode()&os.ModePerm != test.expectedPerms) {
t.Errorf("test[%s]: unexpected perms: %v, expected perms: %v, ", test.desc, info.Mode()&os.ModePerm, test.expectedPerms)
}
if (info.Mode()&os.ModeSetgid != 0) != test.expectedGidBit {
t.Errorf("test[%s]: unexpected gid bit: %v, expected gid bit: %v", test.desc, info.Mode()&os.ModeSetgid != 0, test.expectedGidBit)
}
}
}
}
// getWorkDirPath returns the path to the current working directory
func getWorkDirPath(dir string) (string, error) {
path, err := os.Getwd()
if err != nil {
return "", err
}
return fmt.Sprintf("%s%c%s", path, os.PathSeparator, dir), nil
}
func TestSetVolumeOwnership(t *testing.T) {
tmpVDir, err := utiltesting.MkTmpdir("SetVolumeOwnership")
if err != nil {
t.Fatalf("can't make a temp dir: %v", err)
}
//deferred clean up
defer os.RemoveAll(tmpVDir)
tests := []struct {
path string
gid string
fsGroupChangePolicy string
expectedError error
}{
{
path: "path",
gid: "",
expectedError: fmt.Errorf("convert %s to int failed with %v", "", `strconv.Atoi: parsing "": invalid syntax`),
},
{
path: "path",
gid: "alpha",
expectedError: fmt.Errorf("convert %s to int failed with %v", "alpha", `strconv.Atoi: parsing "alpha": invalid syntax`),
},
{
path: "not-exists",
gid: "1000",
expectedError: fmt.Errorf("lstat not-exists: no such file or directory"),
},
{
path: tmpVDir,
gid: "1000",
expectedError: nil,
},
{
path: tmpVDir,
gid: "1000",
fsGroupChangePolicy: "Always",
expectedError: nil,
},
{
path: tmpVDir,
gid: "1000",
fsGroupChangePolicy: "OnRootMismatch",
expectedError: nil,
},
}
for _, test := range tests {
err := SetVolumeOwnership(test.path, test.gid, test.fsGroupChangePolicy)
if err != nil && (err.Error() != test.expectedError.Error()) {
t.Errorf("unexpected error: %v, expected error: %v", err, test.expectedError)
}
}
}
func TestSetKeyValueInMap(t *testing.T) {
tests := []struct {
desc string
m map[string]string
key string
value string
expected map[string]string
}{
{
desc: "nil map",
key: "key",
value: "value",
},
{
desc: "empty map",
m: map[string]string{},
key: "key",
value: "value",
expected: map[string]string{"key": "value"},
},
{
desc: "non-empty map",
m: map[string]string{"k": "v"},
key: "key",
value: "value",
expected: map[string]string{
"k": "v",
"key": "value",
},
},
{
desc: "same key already exists",
m: map[string]string{"subDir": "value2"},
key: "subDir",
value: "value",
expected: map[string]string{"subDir": "value"},
},
{
desc: "case insensitive key already exists",
m: map[string]string{"subDir": "value2"},
key: "subdir",
value: "value",
expected: map[string]string{"subDir": "value"},
},
}
for _, test := range tests {
setKeyValueInMap(test.m, test.key, test.value)
if !reflect.DeepEqual(test.m, test.expected) {
t.Errorf("test[%s]: unexpected output: %v, expected result: %v", test.desc, test.m, test.expected)
}
}
}
func TestGetValueInMap(t *testing.T) {
tests := []struct {
desc string
m map[string]string
key string
expected string
}{
{
desc: "nil map",
key: "key",
expected: "",
},
{
desc: "empty map",
m: map[string]string{},
key: "key",
expected: "",
},
{
desc: "non-empty map",
m: map[string]string{"k": "v"},
key: "key",
expected: "",
},
{
desc: "same key already exists",
m: map[string]string{"subDir": "value2"},
key: "subDir",
expected: "value2",
},
{
desc: "case insensitive key already exists",
m: map[string]string{"subDir": "value2"},
key: "subdir",
expected: "value2",
},
}
for _, test := range tests {
result := getValueInMap(test.m, test.key)
if result != test.expected {
t.Errorf("test[%s]: unexpected output: %v, expected result: %v", test.desc, result, test.expected)
}
}
}
func TestReplaceWithMap(t *testing.T) {
tests := []struct {
desc string
str string
m map[string]string
expected string
}{
{
desc: "empty string",
str: "",
expected: "",
},
{
desc: "empty map",
str: "",
m: map[string]string{},
expected: "",
},
{
desc: "empty key",
str: "prefix-" + pvNameMetadata,
m: map[string]string{"": "pv"},
expected: "prefix-" + pvNameMetadata,
},
{
desc: "empty value",
str: "prefix-" + pvNameMetadata,
m: map[string]string{pvNameMetadata: ""},
expected: "prefix-",
},
{
desc: "one replacement",
str: "prefix-" + pvNameMetadata,
m: map[string]string{pvNameMetadata: "pv"},
expected: "prefix-pv",
},
{
desc: "multiple replacements",
str: pvcNamespaceMetadata + pvcNameMetadata,
m: map[string]string{pvcNamespaceMetadata: "namespace", pvcNameMetadata: "pvcname"},
expected: "namespacepvcname",
},
}
for _, test := range tests {
result := replaceWithMap(test.str, test.m)
if result != test.expected {
t.Errorf("test[%s]: unexpected output: %v, expected result: %v", test.desc, result, test.expected)
}
}
}
func TestIsReadOnlyFromCapability(t *testing.T) {
testCases := []struct {
name string
vc *csi.VolumeCapability
expectedResult bool
}{
{
name: "false with empty capabilities",
vc: &csi.VolumeCapability{},
expectedResult: false,
},
{
name: "fail with capabilities no access mode",
vc: &csi.VolumeCapability{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{},
},
},
},
{
name: "false with SINGLE_NODE_WRITER capabilities",
vc: &csi.VolumeCapability{
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER,
},
},
expectedResult: false,
},
{
name: "true with MULTI_NODE_READER_ONLY capabilities",
vc: &csi.VolumeCapability{
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY,
},
},
expectedResult: true,
},
{
name: "true with SINGLE_NODE_READER_ONLY capabilities",
vc: &csi.VolumeCapability{
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY,
},
},
expectedResult: true,
},
}
for _, test := range testCases {
result := isReadOnlyFromCapability(test.vc)
if result != test.expectedResult {
t.Errorf("case(%s): isReadOnlyFromCapability returned with %v, not equal to %v", test.name, result, test.expectedResult)
}
}
}
func TestIsConfidentialRuntimeClass(t *testing.T) {
ctx := context.TODO()
// Test the case where kubeClient is nil
_, err := isConfidentialRuntimeClass(ctx, nil, "test-runtime-class", defaultRuntimeClassHandler)
if err == nil || err.Error() != "kubeClient is nil" {
t.Fatalf("expected error 'kubeClient is nil', got %v", err)
}
// Create a fake clientset
clientset := fake.NewSimpleClientset()
// Test the case where the runtime class exists and has the confidential handler
runtimeClass := &nodev1.RuntimeClass{
ObjectMeta: metav1.ObjectMeta{
Name: "test-runtime-class",
},
Handler: defaultRuntimeClassHandler,
}
_, err = clientset.NodeV1().RuntimeClasses().Create(ctx, runtimeClass, metav1.CreateOptions{})
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
isConfidential, err := isConfidentialRuntimeClass(ctx, clientset, "test-runtime-class", defaultRuntimeClassHandler)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if !isConfidential {
t.Fatalf("expected runtime class to be confidential, got %v", isConfidential)
}
// Test the case where the runtime class exists but does not have the confidential handler
nonConfidentialRuntimeClass := &nodev1.RuntimeClass{
ObjectMeta: metav1.ObjectMeta{
Name: "test-runtime-class-non-confidential",
},
Handler: "non-confidential-handler",
}
_, err = clientset.NodeV1().RuntimeClasses().Create(ctx, nonConfidentialRuntimeClass, metav1.CreateOptions{})
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
isConfidential, err = isConfidentialRuntimeClass(ctx, clientset, "test-runtime-class-non-confidential", defaultRuntimeClassHandler)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if isConfidential {
t.Fatalf("expected runtime class to not be confidential, got %v", isConfidential)
}
// Test the case where the runtime class does not exist
_, err = isConfidentialRuntimeClass(ctx, clientset, "nonexistent-runtime-class", defaultRuntimeClassHandler)
if err == nil {
t.Fatalf("expected an error, got nil")
}
}
func TestIsThrottlingError(t *testing.T) {
tests := []struct {
desc string
err error
expected bool
}{
{
desc: "nil error",
err: nil,
expected: false,
},
{
desc: "no match",
err: errors.New("no match"),
expected: false,
},
{
desc: "match error message",
err: errors.New("could not list storage accounts for account type Premium_LRS: Retriable: true, RetryAfter: 217s, HTTPStatusCode: 0, RawError: azure cloud provider throttled for operation StorageAccountListByResourceGroup with reason \"client throttled\""),
expected: true,
},
{
desc: "match error message exceeds 1200s",
err: errors.New("could not list storage accounts for account type Premium_LRS: Retriable: true, RetryAfter: 2170s, HTTPStatusCode: 0, RawError: azure cloud provider throttled for operation StorageAccountListByResourceGroup with reason \"client throttled\""),
expected: true,
},
{
desc: "match error message with TooManyRequests throttling",
err: errors.New("could not list storage accounts for account type Premium_LRS: Retriable: true, RetryAfter: 2170s, HTTPStatusCode: 429, RawError: azure cloud provider throttled for operation StorageAccountListByResourceGroup with reason \"TooManyRequests\""),
expected: true,
},
}
for _, test := range tests {
result := isThrottlingError(test.err)
if result != test.expected {
t.Errorf("desc: (%s), input: err(%v), IsThrottlingError returned with bool(%t), not equal to expected(%t)",
test.desc, test.err, result, test.expected)
}
}
}
func TestGetBackOff(t *testing.T) {
tests := []struct {
desc string
config azureconfig.Config
expected wait.Backoff
}{
{
desc: "default backoff",
config: azureconfig.Config{
AzureClientConfig: azureconfig.AzureClientConfig{
CloudProviderBackoffRetries: 0,
CloudProviderBackoffDuration: 5,
},
CloudProviderBackoffExponent: 2,
CloudProviderBackoffJitter: 1,
},
expected: wait.Backoff{
Steps: 1,
Duration: 5 * time.Second,
Factor: 2,
Jitter: 1,
},
},
{
desc: "backoff with retries > 1",
config: azureconfig.Config{
AzureClientConfig: azureconfig.AzureClientConfig{
CloudProviderBackoffRetries: 3,
CloudProviderBackoffDuration: 4,
},
CloudProviderBackoffExponent: 2,
CloudProviderBackoffJitter: 1,
},
expected: wait.Backoff{
Steps: 3,
Duration: 4 * time.Second,
Factor: 2,
Jitter: 1,
},
},
}
for _, test := range tests {
result := getBackOff(test.config)
if !reflect.DeepEqual(result, test.expected) {
t.Errorf("desc: (%s), input: config(%v), getBackOff returned with backoff(%v), not equal to expected(%v)",
test.desc, test.config, result, test.expected)
}
}
}
func TestVolumeMounter(t *testing.T) {
path := "/mnt/data"
attributes := volume.Attributes{}
mounter := &VolumeMounter{
path: path,
attributes: attributes,
}
if mounter.GetPath() != path {
t.Errorf("Expected path %s, but got %s", path, mounter.GetPath())
}
if mounter.GetAttributes() != attributes {
t.Errorf("Expected attributes %v, but got %v", attributes, mounter.GetAttributes())
}
if err := mounter.CanMount(); err != nil {
t.Errorf("Unexpected error: %v", err)
}
if err := mounter.SetUp(volume.MounterArgs{}); err != nil {
t.Errorf("Unexpected error: %v", err)
}
if err := mounter.SetUpAt("", volume.MounterArgs{}); err != nil {
t.Errorf("Unexpected error: %v", err)
}
metrics, err := mounter.GetMetrics()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if metrics != nil {
t.Errorf("Expected nil metrics, but got %v", metrics)
}
}
func TestGetFileServiceURL(t *testing.T) {
tests := []struct {