Repository navigation
Expand file tree
/
Copy pathCmdSendMetadata_test.go
More file actions
1058 lines (947 loc) · 29.7 KB
/
Copy pathCmdSendMetadata_test.go
File metadata and controls
1058 lines (947 loc) · 29.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 2026 IBM Corp
//
// 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 main
import (
"flag"
"os"
"path/filepath"
"strings"
"testing"
)
// TestSendMetadataCommand_NilFlagSet tests that the function returns an error when flagSet is nil
func TestSendMetadataCommand_NilFlagSet(t *testing.T) {
err := sendMetadataCommand(nil, []string{})
if err == nil {
t.Fatal("Expected error for nil flag set, got nil")
}
expectedMsg := "flag set cannot be nil"
if !strings.Contains(err.Error(), expectedMsg) {
t.Errorf("Expected error message to contain %q, got: %v", expectedMsg, err)
}
}
// TestSendMetadataCommand_MutualExclusivity tests that create and delete flags are mutually exclusive
func TestSendMetadataCommand_MutualExclusivity(t *testing.T) {
// Create a valid metadata test file
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
args []string
expectError bool
errorMsg string
}{
{
name: "both create and delete specified",
args: []string{
"--createMetadata", tmpFile,
"--deleteMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
},
expectError: true,
errorMsg: "cannot specify both --createMetadata and --deleteMetadata",
},
{
name: "neither create nor delete specified",
args: []string{"--serverIP", "192.168.1.100"},
expectError: true,
errorMsg: "required flag --createMetadata or --deleteMetadata must be specified",
},
{
name: "only create specified",
args: []string{
"--createMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
},
expectError: true, // Will fail at connection stage
errorMsg: "create failed during metadata transmission: operation cancelled during retry backoff: context deadline exceeded",
},
{
name: "only delete specified",
args: []string{
"--deleteMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
},
expectError: true, // Will fail at connection stage
errorMsg: "delete failed during metadata transmission: operation cancelled during retry backoff: context deadline exceeded",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
err := sendMetadataCommand(flagSet, tt.args)
if tt.expectError {
if err == nil {
t.Fatal("Expected error, got nil")
}
if tt.errorMsg != "" && !strings.Contains(err.Error(), tt.errorMsg) {
t.Errorf("Expected error to contain %q, got: %v", tt.errorMsg, err)
}
} else {
if err != nil {
t.Errorf("Expected no error, got: %v", err)
}
}
})
}
}
// TestSendMetadataCommand_MissingServerIP tests that serverIP is required
func TestSendMetadataCommand_MissingServerIP(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
args []string
}{
{
name: "create without serverIP",
args: []string{"--createMetadata", tmpFile},
},
{
name: "delete without serverIP",
args: []string{"--deleteMetadata", tmpFile},
},
{
name: "empty serverIP with create",
args: []string{
"--createMetadata", tmpFile,
"--serverIP", "",
},
},
{
name: "whitespace serverIP with delete",
args: []string{
"--deleteMetadata", tmpFile,
"--serverIP", " ",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
err := sendMetadataCommand(flagSet, tt.args)
if err == nil {
t.Fatal("Expected error for missing/empty serverIP, got nil")
}
expectedMsg := "required flag --serverIP not specified"
if !strings.Contains(err.Error(), expectedMsg) {
t.Errorf("Expected error message to contain %q, got: %v", expectedMsg, err)
}
})
}
}
// TestSendMetadataCommand_InvalidServerIP tests that invalid IP addresses are rejected
func TestSendMetadataCommand_InvalidServerIP(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
serverIP string
}{
{
name: "invalid IP format",
serverIP: "999.999.999.999",
},
{
name: "malformed IP",
serverIP: "192.168.1",
},
{
name: "invalid characters",
serverIP: "192.168.1.abc",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", tt.serverIP,
}
err := sendMetadataCommand(flagSet, args)
if err == nil {
t.Fatalf("Expected error for invalid serverIP %q, got nil", tt.serverIP)
}
expectedMsg := "invalid IP address or hostname"
if !strings.Contains(err.Error(), expectedMsg) {
t.Errorf("Expected error message to contain %q, got: %v", expectedMsg, err)
}
})
}
}
// TestSendMetadataCommand_FileValidation tests that metadata file must exist
func TestSendMetadataCommand_FileValidation(t *testing.T) {
tests := []struct {
name string
setupFile func(t *testing.T) string
cleanupFile func(string)
expectError bool
errorMsg string
}{
{
name: "non-existent file",
setupFile: func(t *testing.T) string {
return filepath.Join(os.TempDir(), "non-existent-file-12345.json")
},
cleanupFile: func(s string) {},
expectError: true,
errorMsg: "create failed during file validation: file does not exist",
},
{
name: "valid file",
setupFile: func(t *testing.T) string {
return createValidMetadataFile(t, "valid-metadata.json")
},
cleanupFile: func(s string) { os.Remove(s) },
expectError: true, // Will fail at connection stage
errorMsg: "create failed during metadata transmission: operation cancelled during retry backoff: context deadline exceeded",
},
{
name: "empty filename",
setupFile: func(t *testing.T) string {
return ""
},
cleanupFile: func(s string) {},
expectError: true,
errorMsg: "required flag --createMetadata or --deleteMetadata must be specified",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
filePath := tt.setupFile(t)
defer tt.cleanupFile(filePath)
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", filePath,
"--timeout", "1s",
"--serverIP", "192.168.1.100",
}
err := sendMetadataCommand(flagSet, args)
if tt.expectError {
if err == nil {
t.Fatal("Expected error, got nil")
}
if tt.errorMsg != "" && !strings.Contains(err.Error(), tt.errorMsg) {
t.Errorf("Expected error to contain %q, got: %v", tt.errorMsg, err)
}
} else {
if err != nil {
t.Errorf("Expected no error, got: %v", err)
}
}
})
}
}
// TestSendMetadataCommand_InvalidDebugFlag tests that invalid debug flag values are rejected
func TestSendMetadataCommand_InvalidDebugFlag(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
debugValue string
}{
{
name: "invalid value",
debugValue: "invalid",
},
{
name: "numeric value",
debugValue: "2",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
"--shouldDebug", tt.debugValue,
}
err := sendMetadataCommand(flagSet, args)
if err == nil {
t.Fatalf("Expected error for invalid debug flag %q, got nil", tt.debugValue)
}
if !strings.Contains(err.Error(), "shouldDebug") {
t.Errorf("Expected error message to mention shouldDebug flag, got: %v", err)
}
})
}
}
// TestSendMetadataCommand_ValidDebugFlags tests that valid debug flag values are accepted
func TestSendMetadataCommand_ValidDebugFlags(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
debugValue string
}{
{name: "true lowercase", debugValue: "true"},
{name: "false lowercase", debugValue: "false"},
{name: "TRUE uppercase", debugValue: "TRUE"},
{name: "FALSE uppercase", debugValue: "FALSE"},
{name: "1 numeric", debugValue: "1"},
{name: "0 numeric", debugValue: "0"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
"--shouldDebug", tt.debugValue,
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection stage, not at flag parsing
if err != nil && strings.Contains(err.Error(), "must be 'true' or 'false'") {
t.Errorf("Debug flag %q should be valid but got parsing error: %v", tt.debugValue, err)
}
})
}
}
// TestSendMetadataCommand_CreateOperation tests create metadata operation
func TestSendMetadataCommand_CreateOperation(t *testing.T) {
tmpFile := createValidMetadataFile(t, "create-metadata.json")
defer os.Remove(tmpFile)
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--timeout", "1s",
"--serverIP", "192.168.1.100",
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection stage (expected)
if err == nil {
t.Fatal("Expected error (connection failure), got nil")
}
// Should not fail at validation
if strings.Contains(err.Error(), "metadata file validation failed") {
t.Errorf("Should not fail at file validation, got: %v", err)
}
if strings.Contains(err.Error(), "invalid server IP") {
t.Errorf("Should not fail at IP validation, got: %v", err)
}
}
// TestSendMetadataCommand_DeleteOperation tests delete metadata operation
func TestSendMetadataCommand_DeleteOperation(t *testing.T) {
tmpFile := createValidMetadataFile(t, "delete-metadata.json")
defer os.Remove(tmpFile)
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--deleteMetadata", tmpFile,
"--timeout", "1s",
"--serverIP", "192.168.1.100",
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection stage (expected)
if err == nil {
t.Fatal("Expected error (connection failure), got nil")
}
// Should not fail at validation
if strings.Contains(err.Error(), "metadata file validation failed") {
t.Errorf("Should not fail at file validation, got: %v", err)
}
if strings.Contains(err.Error(), "invalid server IP") {
t.Errorf("Should not fail at IP validation, got: %v", err)
}
}
// TestSendMetadataCommand_ErrorPrefix tests that errors have the correct prefix
func TestSendMetadataCommand_ErrorPrefix(t *testing.T) {
tests := []struct {
name string
args []string
}{
{
name: "missing operation",
args: []string{"--serverIP", "192.168.1.100"},
},
{
name: "invalid serverIP",
args: []string{
"--createMetadata", "test.json",
"--serverIP", "999.999.999.999",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
err := sendMetadataCommand(flagSet, tt.args)
if err == nil {
t.Fatal("Expected error, got nil")
}
expectedPrefix := "Error:"
if !strings.Contains(err.Error(), expectedPrefix) {
t.Errorf("Expected error to contain prefix %q, got: %v", expectedPrefix, err)
}
})
}
}
// TestSendMetadataCommand_Constants tests that constants are defined correctly
func TestSendMetadataCommand_Constants(t *testing.T) {
// Test flag name constants
if flagSendCreateMetadata == "" {
t.Error("flagSendCreateMetadata constant should not be empty")
}
if flagSendDeleteMetadata == "" {
t.Error("flagSendDeleteMetadata constant should not be empty")
}
if flagSendServerIP == "" {
t.Error("flagSendServerIP constant should not be empty")
}
if flagSendShouldDebug == "" {
t.Error("flagSendShouldDebug constant should not be empty")
}
// Test default value constants
if defaultSendCreateMetadata != "" {
t.Errorf("defaultSendCreateMetadata should be empty string, got: %q", defaultSendCreateMetadata)
}
if defaultSendDeleteMetadata != "" {
t.Errorf("defaultSendDeleteMetadata should be empty string, got: %q", defaultSendDeleteMetadata)
}
if defaultSendServerIP != "" {
t.Errorf("defaultSendServerIP should be empty string, got: %q", defaultSendServerIP)
}
if defaultSendShouldDebug != "false" {
t.Errorf("defaultSendShouldDebug should be 'false', got: %q", defaultSendShouldDebug)
}
// Test operation name constants
if operationCreate != "create" {
t.Errorf("operationCreate should be 'create', got: %q", operationCreate)
}
if operationDelete != "delete" {
t.Errorf("operationDelete should be 'delete', got: %q", operationDelete)
}
if operationCreated != "created" {
t.Errorf("operationCreated should be 'created', got: %q", operationCreated)
}
if operationDeleted != "deleted" {
t.Errorf("operationDeleted should be 'deleted', got: %q", operationDeleted)
}
// Test error prefix
if errPrefixSend == "" {
t.Error("errPrefixSend constant should not be empty")
}
}
// TestSendMetadataCommand_FlagDefaults tests that default values are set correctly
func TestSendMetadataCommand_FlagDefaults(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
// Define flags without parsing
createMetadata := flagSet.String(flagSendCreateMetadata, defaultSendCreateMetadata, usageSendCreateMetadata)
deleteMetadata := flagSet.String(flagSendDeleteMetadata, defaultSendDeleteMetadata, usageSendDeleteMetadata)
serverIP := flagSet.String(flagSendServerIP, defaultSendServerIP, usageSendServerIP)
shouldDebug := flagSet.String(flagSendShouldDebug, defaultSendShouldDebug, usageSendShouldDebug)
// Check defaults before parsing
if *createMetadata != "" {
t.Errorf("Default createMetadata should be empty, got: %q", *createMetadata)
}
if *deleteMetadata != "" {
t.Errorf("Default deleteMetadata should be empty, got: %q", *deleteMetadata)
}
if *serverIP != "" {
t.Errorf("Default serverIP should be empty, got: %q", *serverIP)
}
if *shouldDebug != "false" {
t.Errorf("Default shouldDebug should be 'false', got: %q", *shouldDebug)
}
}
// TestSendMetadataCommand_WhitespaceHandling tests that whitespace is properly trimmed
func TestSendMetadataCommand_WhitespaceHandling(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
args []string
shouldOK bool // true if should pass validation
}{
{
name: "whitespace in createMetadata",
args: []string{
"--createMetadata", " " + tmpFile + " ",
"--timeout", "1s",
"--serverIP", "192.168.1.100",
},
shouldOK: true,
},
{
name: "whitespace in serverIP",
args: []string{
"--createMetadata", tmpFile,
"--timeout", "1s",
"--serverIP", " 192.168.1.100 ",
},
shouldOK: true,
},
{
name: "only whitespace in createMetadata",
args: []string{
"--createMetadata", " ",
"--timeout", "1s",
"--serverIP", "192.168.1.100",
},
shouldOK: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
err := sendMetadataCommand(flagSet, tt.args)
if tt.shouldOK {
// Should fail at connection, not validation
if err != nil && (strings.Contains(err.Error(), "metadata file validation failed") ||
strings.Contains(err.Error(), "invalid server IP") ||
strings.Contains(err.Error(), "required flag")) {
t.Errorf("Should pass validation but got: %v", err)
}
} else {
// Should fail at validation
if err == nil {
t.Error("Expected validation error, got nil")
}
}
})
}
}
// TestSendMetadataCommand_ValidIPv4Addresses tests various valid IPv4 formats
func TestSendMetadataCommand_ValidIPv4Addresses(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
serverIP string
}{
{name: "standard IPv4", serverIP: "192.168.1.100"},
{name: "localhost", serverIP: "127.0.0.1"},
{name: "zero address", serverIP: "0.0.0.0"},
{name: "broadcast", serverIP: "255.255.255.255"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", tt.serverIP,
"--timeout", "1s",
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection stage, not validation
if err != nil && strings.Contains(err.Error(), "invalid server IP") {
t.Errorf("IP %q should be valid but got validation error: %v", tt.serverIP, err)
}
})
}
}
// TestSendMetadataCommand_ValidIPv6Addresses tests various valid IPv6 formats
func TestSendMetadataCommand_ValidIPv6Addresses(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
serverIP string
}{
{name: "full IPv6", serverIP: "2001:0db8:85a3:0000:0000:8a2e:0370:7334"},
{name: "compressed IPv6", serverIP: "2001:db8:85a3::8a2e:370:7334"},
{name: "localhost IPv6", serverIP: "::1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", tt.serverIP,
"--timeout", "1s",
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection stage, not validation
if err != nil && strings.Contains(err.Error(), "invalid server IP") {
t.Errorf("IP %q should be valid but got validation error: %v", tt.serverIP, err)
}
})
}
}
// TestSendMetadataCommand_MultipleInvocations tests that the function can be called multiple times
func TestSendMetadataCommand_MultipleInvocations(t *testing.T) {
// First invocation
flagSet1 := flag.NewFlagSet("send-metadata-1", flag.ContinueOnError)
err1 := sendMetadataCommand(flagSet1, []string{})
if err1 == nil {
t.Error("First invocation: expected error for missing flags")
}
// Second invocation
flagSet2 := flag.NewFlagSet("send-metadata-2", flag.ContinueOnError)
err2 := sendMetadataCommand(flagSet2, []string{})
if err2 == nil {
t.Error("Second invocation: expected error for missing flags")
}
// Both should have similar errors
if err1.Error() != err2.Error() {
t.Errorf("Multiple invocations should produce consistent errors.\nFirst: %v\nSecond: %v", err1, err2)
}
}
// Helper function to create a temporary test file
func createTempTestFile(t *testing.T, name, content string) string {
t.Helper()
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, name)
err := os.WriteFile(filePath, []byte(content), 0644)
if err != nil {
t.Fatalf("Failed to create temp file: %v", err)
}
return filePath
}
// Helper function to create a valid metadata test file with required fields
func createValidMetadataFile(t *testing.T, name string) string {
t.Helper()
validMetadata := `{
"clusterName": "test-cluster",
"clusterID": "12345678-1234-1234-1234-123456789012",
"infraID": "test-cluster-abcde",
"openstack": {
"cloud": "test-cloud",
"identifier": {
"openshiftClusterID": "test-cluster-id"
}
}
}`
return createTempTestFile(t, name, validMetadata)
}
// Made with Bob
// TestSendMetadataCommand_InvalidMetadataContent tests that invalid metadata content is rejected
func TestSendMetadataCommand_InvalidMetadataContent(t *testing.T) {
tests := []struct {
name string
content string
errorMsg string
}{
{
name: "missing clusterName",
content: `{"infraID": "test-infra", "openstack": {"cloud": "test"}}`,
errorMsg: "required field 'clusterName' is missing or empty",
},
{
name: "missing infraID",
content: `{"clusterName": "test-cluster", "openstack": {"cloud": "test"}}`,
errorMsg: "required field 'infraID' is missing or empty",
},
{
name: "missing platform metadata",
content: `{"clusterName": "test-cluster", "infraID": "test-infra"}`,
errorMsg: "metadata must contain either 'openstack' or 'powervc' platform configuration",
},
{
name: "invalid JSON",
content: `{"clusterName": "test-cluster", "infraID": "test-infra"`,
errorMsg: "invalid JSON format",
},
{
name: "empty clusterName",
content: `{"clusterName": "", "infraID": "test-infra", "openstack": {"cloud": "test"}}`,
errorMsg: "required field 'clusterName' is missing or empty",
},
{
name: "empty infraID",
content: `{"clusterName": "test-cluster", "infraID": "", "openstack": {"cloud": "test"}}`,
errorMsg: "required field 'infraID' is missing or empty",
},
{
name: "whitespace-only clusterName",
content: `{"clusterName": " ", "infraID": "test-infra", "openstack": {"cloud": "test"}}`,
errorMsg: "required field 'clusterName' is missing or empty",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpFile := createTempTestFile(t, "invalid-metadata.json", tt.content)
defer os.Remove(tmpFile)
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
}
err := sendMetadataCommand(flagSet, args)
if err == nil {
t.Fatal("Expected error for invalid metadata content, got nil")
}
if !strings.Contains(err.Error(), tt.errorMsg) {
t.Errorf("Expected error to contain %q, got: %v", tt.errorMsg, err)
}
// Verify it failed at content validation, not connection
if strings.Contains(err.Error(), "failed to connect to server") {
t.Errorf("Should fail at content validation, not connection. Got: %v", err)
}
})
}
}
// TestSendMetadataCommand_ValidMetadataContent tests that valid metadata content is accepted
func TestSendMetadataCommand_ValidMetadataContent(t *testing.T) {
tests := []struct {
name string
content string
}{
{
name: "valid OpenStack metadata",
content: `{
"clusterName": "test-cluster",
"infraID": "test-infra",
"openstack": {
"cloud": "test-cloud",
"identifier": {"openshiftClusterID": "test-id"}
}
}`,
},
{
name: "valid PowerVC metadata",
content: `{
"clusterName": "test-cluster",
"infraID": "test-infra",
"powervc": {
"cloud": "test-cloud",
"identifier": {"openshiftClusterID": "test-id"}
}
}`,
},
{
name: "both OpenStack and PowerVC metadata",
content: `{
"clusterName": "test-cluster",
"infraID": "test-infra",
"openstack": {
"cloud": "openstack-cloud",
"identifier": {"openshiftClusterID": "test-id"}
},
"powervc": {
"cloud": "powervc-cloud",
"identifier": {"openshiftClusterID": "test-id"}
}
}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpFile := createTempTestFile(t, "valid-metadata.json", tt.content)
defer os.Remove(tmpFile)
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection stage, not content validation
if err != nil && strings.Contains(err.Error(), "metadata content validation") {
t.Errorf("Should not fail at content validation for valid metadata. Got: %v", err)
}
})
}
}
// TestSendMetadataCommand_TimeoutFlag tests the timeout flag functionality
func TestSendMetadataCommand_TimeoutFlag(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
timeout string
expectError bool
errorMsg string
}{
{
name: "valid timeout - 5m",
timeout: "5m",
expectError: true, // Will fail at connection, not timeout parsing
errorMsg: "connection to server",
},
{
name: "invalid timeout format",
timeout: "invalid",
expectError: true,
errorMsg: "timeout parsing",
},
{
name: "negative timeout",
timeout: "-5m",
expectError: true,
errorMsg: "timeout must be positive",
},
{
name: "zero timeout",
timeout: "0s",
expectError: true,
errorMsg: "timeout must be positive",
},
{
name: "empty timeout uses default",
timeout: "",
expectError: true,
errorMsg: "connection to server",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", "192.168.1.100",
}
if tt.timeout != "" {
args = append(args, "--timeout", tt.timeout)
}
err := sendMetadataCommand(flagSet, args)
if tt.expectError {
if err == nil {
t.Fatal("Expected error, got nil")
}
if tt.errorMsg != "" && !strings.Contains(err.Error(), tt.errorMsg) {
t.Errorf("Expected error to contain %q, got: %v", tt.errorMsg, err)
}
} else {
if err != nil {
t.Errorf("Expected no error, got: %v", err)
}
}
})
}
}
// TestSendMetadataCommand_TimeoutWithDifferentOperations tests timeout with create and delete
func TestSendMetadataCommand_TimeoutWithDifferentOperations(t *testing.T) {
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
operation string
timeout string
}{
{
name: "create with custom timeout",
operation: "createMetadata",
timeout: "2m",
},
{
name: "delete with custom timeout",
operation: "deleteMetadata",
timeout: "3m",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--" + tt.operation, tmpFile,
"--serverIP", "192.168.1.100",
"--timeout", "1s",
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection, not timeout parsing
if err == nil {
t.Fatal("Expected connection error, got nil")
}
if strings.Contains(err.Error(), "timeout parsing") {
t.Errorf("Should not fail at timeout parsing. Got: %v", err)
}
})
}
}
// TestSendMetadataCommand_ValidHostnames tests that valid hostnames are accepted by the validation
func TestSendMetadataCommand_ValidHostnames(t *testing.T) {
// Create a valid metadata test file
tmpFile := createValidMetadataFile(t, "test-metadata.json")
defer os.Remove(tmpFile)
tests := []struct {
name string
hostname string
}{
{name: "localhost", hostname: "localhost"},
{name: "FQDN", hostname: "server.example.com"},
{name: "subdomain", hostname: "api.cluster.example.com"},
{name: "multi-level subdomain", hostname: "api.prod.cluster.example.com"},
{name: "hostname with hyphen", hostname: "my-server.example.com"},
{name: "short hostname", hostname: "server"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
flagSet := flag.NewFlagSet("send-metadata", flag.ContinueOnError)
args := []string{
"--createMetadata", tmpFile,
"--serverIP", tt.hostname,
}
err := sendMetadataCommand(flagSet, args)
// Should fail at connection, not validation
if err != nil && strings.Contains(err.Error(), "invalid server IP") {
t.Errorf("Hostname %q should be valid but got validation error: %v",
tt.hostname, err)
}
// We expect connection errors since these are not real servers
// but we should NOT get validation errors
if err != nil && !strings.Contains(err.Error(), "metadata transmission") {
t.Logf("Got expected connection error for hostname %q: %v", tt.hostname, err)
}
})
}
}