forked from devfile/library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_test.go
1239 lines (1159 loc) · 29.6 KB
/
util_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2021-2023 Red Hat, Inc.
//
// 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 util
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"testing"
"github.com/devfile/library/v2/pkg/testingutil/filesystem"
"github.com/kylelemons/godebug/pretty"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
)
func TestNamespaceOpenShiftObject(t *testing.T) {
tests := []struct {
testName string
componentName string
applicationName string
want string
wantErr bool
}{
{
testName: "Test namespacing",
componentName: "foo",
applicationName: "bar",
want: "foo-bar",
},
{
testName: "Blank applicationName with namespacing",
componentName: "foo",
applicationName: "",
wantErr: true,
},
{
testName: "Blank componentName with namespacing",
componentName: "",
applicationName: "bar",
wantErr: true,
},
}
// Test that it "joins"
for _, tt := range tests {
t.Log("Running test: ", tt.testName)
t.Run(tt.testName, func(t *testing.T) {
name, err := NamespaceOpenShiftObject(tt.componentName, tt.applicationName)
if tt.wantErr && err == nil {
t.Errorf("Expected an error, got success")
} else if tt.wantErr == false && err != nil {
t.Errorf("Error with namespacing: %s", err)
}
if tt.want != name {
t.Errorf("Expected %s, got %s", tt.want, name)
}
})
}
}
func TestExtractComponentType(t *testing.T) {
tests := []struct {
testName string
componentType string
want string
wantErr bool
}{
{
testName: "Test namespacing and versioning",
componentType: "myproject/foo:3.5",
want: "foo",
},
{
testName: "Test versioning",
componentType: "foo:3.5",
want: "foo",
},
{
testName: "Test plain component type",
componentType: "foo",
want: "foo",
},
}
// Test that it "joins"
for _, tt := range tests {
t.Log("Running test: ", tt.testName)
t.Run(tt.testName, func(t *testing.T) {
name := ExtractComponentType(tt.componentType)
if tt.want != name {
t.Errorf("Expected %s, got %s", tt.want, name)
}
})
}
}
func TestGetRandomName(t *testing.T) {
type args struct {
prefix string
existList []string
}
tests := []struct {
testName string
args args
// want is regexp if expectConflictResolution is true else it is a full name
want string
}{
{
testName: "Case: Optional suffix passed and prefix-suffix as a name is not already used",
args: args{
prefix: "odo",
existList: []string{
"odo-auth",
"odo-pqrs",
},
},
want: "odo-[a-z]{4}",
},
{
testName: "Case: Optional suffix passed and prefix-suffix as a name is already used",
args: args{
prefix: "nodejs-ex-nodejs",
existList: []string{
"nodejs-ex-nodejs-yvrp",
"nodejs-ex-nodejs-abcd",
},
},
want: "nodejs-ex-nodejs-[a-z]{4}",
},
}
for _, tt := range tests {
t.Log("Running test: ", tt.testName)
t.Run(tt.testName, func(t *testing.T) {
name, err := GetRandomName(tt.args.prefix, -1, tt.args.existList, 3)
if err != nil {
t.Errorf("failed to generate a random name. Error %v", err)
}
r, _ := regexp.Compile(tt.want)
match := r.MatchString(name)
if !match {
t.Errorf("Received name %s which does not match %s", name, tt.want)
}
})
}
}
func TestGenerateRandomString(t *testing.T) {
tests := []struct {
testName string
strLength int
}{
{
testName: "Case: Generate random string of length 4",
strLength: 4,
},
{
testName: "Case: Generate random string of length 3",
strLength: 3,
},
}
for _, tt := range tests {
t.Log("Running test: ", tt.testName)
t.Run(tt.testName, func(t *testing.T) {
name := GenerateRandomString(tt.strLength)
r, _ := regexp.Compile(fmt.Sprintf("[a-z]{%d}", tt.strLength))
match := r.MatchString(name)
if !match {
t.Errorf("Randomly generated string %s which does not match regexp %s", name, fmt.Sprintf("[a-z]{%d}", tt.strLength))
}
})
}
}
func TestGetAbsPath(t *testing.T) {
tests := []struct {
name string
path string
absPath string
wantErr bool
}{
{
name: "Case 1: Valid abs path resolution of `~`",
path: "~",
wantErr: false,
},
{
name: "Case 2: Valid abs path resolution of `.`",
path: ".",
wantErr: false,
},
}
for _, tt := range tests {
t.Log("Running test: ", tt.name)
t.Run(tt.name, func(t *testing.T) {
switch tt.path {
case "~":
if len(customHomeDir) > 0 {
tt.absPath = customHomeDir
} else {
usr, err := user.Current()
if err != nil {
t.Errorf("Failed to get absolute path corresponding to `~`. Error %v", err)
return
}
tt.absPath = usr.HomeDir
}
case ".":
absPath, err := os.Getwd()
if err != nil {
t.Errorf("Failed to get absolute path corresponding to `.`. Error %v", err)
return
}
tt.absPath = absPath
}
result, err := GetAbsPath(tt.path)
if result != tt.absPath {
t.Errorf("Expected %v, got %v", tt.absPath, result)
}
if !tt.wantErr == (err != nil) {
t.Errorf("Expected error: %v got error %v", tt.wantErr, err)
}
})
}
}
func TestCheckPathExists(t *testing.T) {
fs := filesystem.NewFakeFs()
fs.MkdirAll("/path/to/devfile", 0755)
fs.WriteFile("/path/to/devfile/devfile.yaml", []byte(""), 0755)
file := "/path/to/devfile/devfile.yaml"
missingFile := "/path/to/not/devfile"
tests := []struct {
name string
filePath string
want bool
}{
{
name: "should be able to get file that exists",
filePath: file,
want: true,
},
{
name: "should fail if file does not exist",
filePath: missingFile,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := checkPathExistsOnFS(tt.filePath, fs)
if !reflect.DeepEqual(result, tt.want) {
t.Errorf("Got error: %t, want error: %t", result, tt.want)
}
})
}
}
func TestGetHostWithPort(t *testing.T) {
tests := []struct {
inputURL string
want string
wantErr bool
}{
{
inputURL: "https://example.com",
want: "example.com:443",
wantErr: false,
},
{
inputURL: "https://example.com:8443",
want: "example.com:8443",
wantErr: false,
},
{
inputURL: "http://example.com",
want: "example.com:80",
wantErr: false,
},
{
inputURL: "notexisting://example.com",
want: "",
wantErr: true,
},
{
inputURL: "http://127.0.0.1",
want: "127.0.0.1:80",
wantErr: false,
},
{
inputURL: "example.com:1234",
want: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("Testing inputURL: %s", tt.inputURL), func(t *testing.T) {
got, err := GetHostWithPort(tt.inputURL)
if (err != nil) != tt.wantErr {
t.Errorf("getHostWithPort() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("getHostWithPort() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetAbsGlobExps(t *testing.T) {
tests := []struct {
testName string
directoryName string
inputRelativeGlobExps []string
expectedGlobExps []string
}{
{
testName: "test case 1: with a filename",
directoryName: "/home/redhat/nodejs-ex/",
inputRelativeGlobExps: []string{
"example.txt",
},
expectedGlobExps: []string{
"/home/redhat/nodejs-ex/example.txt",
},
},
{
testName: "test case 2: with a folder name",
directoryName: "/home/redhat/nodejs-ex/",
inputRelativeGlobExps: []string{
"example/",
},
expectedGlobExps: []string{
"/home/redhat/nodejs-ex/example",
},
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
resultExps := GetAbsGlobExps(tt.directoryName, tt.inputRelativeGlobExps)
if runtime.GOOS == "windows" {
for index, element := range resultExps {
resultExps[index] = filepath.ToSlash(element)
}
}
if !reflect.DeepEqual(resultExps, tt.expectedGlobExps) {
t.Errorf("expected %v, got %v", tt.expectedGlobExps, resultExps)
}
})
}
}
func TestGetSortedKeys(t *testing.T) {
tests := []struct {
testName string
input map[string]string
expected []string
}{
{
testName: "default",
input: map[string]string{"a": "av", "c": "cv", "b": "bv"},
expected: []string{"a", "b", "c"},
},
}
for _, tt := range tests {
t.Log("Running test: ", tt.testName)
t.Run(tt.testName, func(t *testing.T) {
actual := GetSortedKeys(tt.input)
if !reflect.DeepEqual(tt.expected, actual) {
t.Errorf("expected: %+v, got: %+v", tt.expected, actual)
}
})
}
}
func TestGetSplitValuesFromStr(t *testing.T) {
tests := []struct {
testName string
input string
expected []string
}{
{
testName: "Empty string",
input: "",
expected: []string{},
},
{
testName: "Single value",
input: "s1",
expected: []string{"s1"},
},
{
testName: "Multiple values",
input: "s1, s2, s3 ",
expected: []string{"s1", "s2", "s3"},
},
}
for _, tt := range tests {
t.Log("Running test: ", tt.testName)
t.Run(tt.testName, func(t *testing.T) {
actual := GetSplitValuesFromStr(tt.input)
if !reflect.DeepEqual(tt.expected, actual) {
t.Errorf("expected: %+v, got: %+v", tt.expected, actual)
}
})
}
}
func TestGetContainerPortsFromStrings(t *testing.T) {
tests := []struct {
name string
ports []string
containerPorts []corev1.ContainerPort
wantErr bool
}{
{
name: "with normal port values and normal protocol values in lowercase",
ports: []string{"8080/tcp", "9090/udp"},
containerPorts: []corev1.ContainerPort{
{
Name: "8080-tcp",
ContainerPort: 8080,
Protocol: corev1.ProtocolTCP,
},
{
Name: "9090-udp",
ContainerPort: 9090,
Protocol: corev1.ProtocolUDP,
},
},
wantErr: false,
},
{
name: "with normal port values and normal protocol values in mixed case",
ports: []string{"8080/TcP", "9090/uDp"},
containerPorts: []corev1.ContainerPort{
{
Name: "8080-tcp",
ContainerPort: 8080,
Protocol: corev1.ProtocolTCP,
},
{
Name: "9090-udp",
ContainerPort: 9090,
Protocol: corev1.ProtocolUDP,
},
},
wantErr: false,
},
{
name: "with normal port values and with one protocol value not mentioned",
ports: []string{"8080", "9090/Udp"},
containerPorts: []corev1.ContainerPort{
{
Name: "8080-tcp",
ContainerPort: 8080,
Protocol: corev1.ProtocolTCP,
},
{
Name: "9090-udp",
ContainerPort: 9090,
Protocol: corev1.ProtocolUDP,
},
},
wantErr: false,
},
{
name: "with normal port values and with one invalid protocol value",
ports: []string{"8080/blah", "9090/Udp"},
wantErr: true,
},
{
name: "with invalid port values and normal protocol",
ports: []string{"ads/Tcp", "9090/Udp"},
wantErr: true,
},
{
name: "with invalid port values and one missing protocol value",
ports: []string{"ads", "9090/Udp"},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ports, err := GetContainerPortsFromStrings(tt.ports)
if err == nil && !tt.wantErr {
if !reflect.DeepEqual(tt.containerPorts, ports) {
t.Errorf("the ports are not matching, expected %#v, got %#v", tt.containerPorts, ports)
}
} else if err == nil && tt.wantErr {
t.Error("error was expected, but no error was returned")
} else if err != nil && !tt.wantErr {
t.Errorf("test failed, no error was expected, but got unexpected error: %s", err)
}
})
}
}
func TestIsGlobExpMatch(t *testing.T) {
tests := []struct {
testName string
strToMatch string
globExps []string
want bool
wantErr bool
}{
{
testName: "Test glob matches",
strToMatch: "/home/redhat/nodejs-ex/.git",
globExps: []string{"/home/redhat/nodejs-ex/.git", "/home/redhat/nodejs-ex/tests/"},
want: true,
wantErr: false,
},
{
testName: "Test glob does not match",
strToMatch: "/home/redhat/nodejs-ex/gimmt.gimmt",
globExps: []string{"/home/redhat/nodejs-ex/.git/", "/home/redhat/nodejs-ex/tests/"},
want: false,
wantErr: false,
},
{
testName: "Test glob match files",
strToMatch: "/home/redhat/nodejs-ex/openshift/templates/example.json",
globExps: []string{"/home/redhat/nodejs-ex/*.json", "/home/redhat/nodejs-ex/tests/"},
want: true,
wantErr: false,
},
{
testName: "Test '**' glob matches",
strToMatch: "/home/redhat/nodejs-ex/openshift/templates/example.json",
globExps: []string{"/home/redhat/nodejs-ex/openshift/**/*.json"},
want: true,
wantErr: false,
},
{
testName: "Test '!' in glob matches",
strToMatch: "/home/redhat/nodejs-ex/openshift/templates/example.json",
globExps: []string{"/home/redhat/nodejs-ex/!*.json", "/home/redhat/nodejs-ex/tests/"},
want: false,
wantErr: false,
},
{
testName: "Test [ in glob matches",
strToMatch: "/home/redhat/nodejs-ex/openshift/templates/example.json",
globExps: []string{"/home/redhat/nodejs-ex/["},
want: false,
wantErr: true,
},
{
testName: "Test '#' comment glob matches",
strToMatch: "/home/redhat/nodejs-ex/openshift/templates/example.json",
globExps: []string{"#/home/redhat/nodejs-ex/openshift/**/*.json"},
want: false,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
matched, err := IsGlobExpMatch(tt.strToMatch, tt.globExps)
if !tt.wantErr == (err != nil) {
t.Errorf("unexpected error %v, wantErr %v", err, tt.wantErr)
return
}
if tt.want != matched {
t.Errorf("expected %v, got %v", tt.want, matched)
}
})
}
}
func TestRemoveRelativePathFromFiles(t *testing.T) {
type args struct {
path string
input []string
output []string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "Case 1 - Remove the relative path from a list of files",
args: args{
path: "/foo/bar",
input: []string{"/foo/bar/1", "/foo/bar/2", "/foo/bar/3/", "/foo/bar/4/5/foo/bar"},
output: []string{"1", "2", "3", "4/5/foo/bar"},
},
wantErr: false,
},
{
name: "Case 2 - Fail on purpose with an invalid path",
args: args{
path: `..`,
input: []string{"foo", "bar"},
output: []string{},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Run function RemoveRelativePathFromFiles
output, err := RemoveRelativePathFromFiles(tt.args.input, tt.args.path)
if runtime.GOOS == "windows" {
for index, element := range output {
output[index] = filepath.ToSlash(element)
}
}
// Check for error
if !tt.wantErr == (err != nil) {
t.Errorf("unexpected error %v, wantErr %v", err, tt.wantErr)
return
}
if !(reflect.DeepEqual(output, tt.args.output)) {
t.Errorf("expected %v, got %v", tt.args.output, output)
}
})
}
}
func TestHTTPGetFreePort(t *testing.T) {
tests := []struct {
name string
wantErr bool
}{
{
name: "case 1: get a valid free port",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HTTPGetFreePort()
if (err != nil) != tt.wantErr {
t.Errorf("HTTPGetFreePort() error = %v, wantErr %v", err, tt.wantErr)
return
}
addressLook := "localhost:" + strconv.Itoa(got)
listener, err := net.Listen("tcp", addressLook)
if err != nil {
t.Errorf("expected a free port, but listening failed cause: %v", err)
} else {
_ = listener.Close()
}
})
}
}
func TestGetRemoteFilesMarkedForDeletion(t *testing.T) {
tests := []struct {
name string
files []string
remotePath string
want []string
}{
{
name: "case 1: no files",
files: []string{},
remotePath: "/projects",
want: nil,
},
{
name: "case 2: one file",
files: []string{"abc.txt"},
remotePath: "/projects",
want: []string{"/projects/abc.txt"},
},
{
name: "case 3: multiple files",
files: []string{"abc.txt", "def.txt", "hello.txt"},
remotePath: "/projects",
want: []string{"/projects/abc.txt", "/projects/def.txt", "/projects/hello.txt"},
},
{
name: "case 4: remote path multiple folders",
files: []string{"abc.txt", "def.txt", "hello.txt"},
remotePath: "/test/folder",
want: []string{"/test/folder/abc.txt", "/test/folder/def.txt", "/test/folder/hello.txt"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
remoteFiles := GetRemoteFilesMarkedForDeletion(tt.files, tt.remotePath)
if !reflect.DeepEqual(tt.want, remoteFiles) {
t.Errorf("Expected %s, got %s", tt.want, remoteFiles)
}
})
}
}
func TestHTTPGetRequest(t *testing.T) {
invalidHTTPTimeout := -1
validHTTPTimeout := 20
// Start a local HTTP server
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// Send response to be tested
_, err := rw.Write([]byte("OK"))
if err != nil {
t.Error(err)
}
}))
// Close the server when test finishes
defer server.Close()
tests := []struct {
name string
url string
want []byte
timeout *int
}{
{
name: "Case 1: Input url is valid",
url: server.URL,
// Want(Expected) result is "OK"
// According to Unicode table: O == 79, K == 75
want: []byte{79, 75},
},
{
name: "Case 2: Input url is invalid",
url: "invalid",
want: nil,
},
{
name: "Case 3: Test invalid httpTimeout, default timeout will be used",
url: server.URL,
timeout: &invalidHTTPTimeout,
want: []byte{79, 75},
},
{
name: "Case 4: Test valid httpTimeout",
url: server.URL,
timeout: &validHTTPTimeout,
want: []byte{79, 75},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := HTTPRequestParams{
URL: tt.url,
Timeout: tt.timeout,
}
got, err := HTTPGetRequest(request, 0)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Got: %v, want: %v", got, tt.want)
t.Logf("Error message is: %v", err)
}
})
}
}
func TestFilterIgnores(t *testing.T) {
tests := []struct {
name string
changedFiles []string
deletedFiles []string
ignoredFiles []string
wantChangedFiles []string
wantDeletedFiles []string
}{
{
name: "Case 1: No ignored files",
changedFiles: []string{"hello.txt", "test.abc"},
deletedFiles: []string{"one.txt", "two.txt"},
ignoredFiles: []string{},
wantChangedFiles: []string{"hello.txt", "test.abc"},
wantDeletedFiles: []string{"one.txt", "two.txt"},
},
{
name: "Case 2: One ignored file",
changedFiles: []string{"hello.txt", "test.abc"},
deletedFiles: []string{"one.txt", "two.txt"},
ignoredFiles: []string{"hello.txt"},
wantChangedFiles: []string{"test.abc"},
wantDeletedFiles: []string{"one.txt", "two.txt"},
},
{
name: "Case 3: Multiple ignored file",
changedFiles: []string{"hello.txt", "test.abc"},
deletedFiles: []string{"one.txt", "two.txt"},
ignoredFiles: []string{"hello.txt", "two.txt"},
wantChangedFiles: []string{"test.abc"},
wantDeletedFiles: []string{"one.txt"},
},
{
name: "Case 4: No changed or deleted files",
changedFiles: []string{""},
deletedFiles: []string{""},
ignoredFiles: []string{"hello.txt", "two.txt"},
wantChangedFiles: []string{""},
wantDeletedFiles: []string{""},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
filterChanged, filterDeleted := FilterIgnores(tt.changedFiles, tt.deletedFiles, tt.ignoredFiles)
if !reflect.DeepEqual(tt.wantChangedFiles, filterChanged) {
t.Errorf("Expected %s, got %s", tt.wantChangedFiles, filterChanged)
}
if !reflect.DeepEqual(tt.wantDeletedFiles, filterDeleted) {
t.Errorf("Expected %s, got %s", tt.wantDeletedFiles, filterDeleted)
}
})
}
}
func TestDownloadFile(t *testing.T) {
// Start a local HTTP server
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// Send response to be tested
_, err := rw.Write([]byte("OK"))
if err != nil {
t.Error(err)
}
}))
// Close the server when test finishes
defer server.Close()
tests := []struct {
name string
url string
filepath string
want []byte
wantErr bool
}{
{
name: "Case 1: Input url is valid",
url: server.URL,
filepath: "./test.yaml",
// Want(Expected) result is "OK"
// According to Unicode table: O == 79, K == 75
want: []byte{79, 75},
wantErr: false,
},
{
name: "Case 2: Input url is invalid",
url: "invalid",
filepath: "./test.yaml",
want: []byte{},
wantErr: true,
},
{
name: "Case 3: Input url is an empty string",
url: "",
filepath: "./test.yaml",
want: []byte{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotErr := false
params := DownloadParams{
Request: HTTPRequestParams{
URL: tt.url,
},
Filepath: tt.filepath,
}
err := DownloadFile(params)
if err != nil {
gotErr = true
}
if !reflect.DeepEqual(gotErr, tt.wantErr) {
t.Error("Failed to get expected error")
}
if !tt.wantErr {
if err != nil {
t.Errorf("Failed to download file with error %s", err)
}
got, err := os.ReadFile(tt.filepath)
if err != nil {
t.Errorf("Failed to read file with error %s", err)
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Got: %v, want: %v", got, tt.want)
}
// Clean up the file that downloaded in this test case
err = os.Remove(tt.filepath)
if err != nil {
t.Errorf("Failed to delete file with error %s", err)
}
}
})
}
}
func TestDownloadInMemory(t *testing.T) {
const downloadErr = "failed to retrieve %s, 404: Not Found"
// Start a local HTTP server
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// Send response to be tested
_, err := rw.Write([]byte("OK"))
if err != nil {
t.Error(err)
}
}))
// Close the server when test finishes
defer server.Close()
tests := []struct {
name string
url string
token string
want []byte
wantErr string
}{
{
name: "Case 1: Input url is valid",
url: server.URL,
want: []byte{79, 75},
},
{
name: "Case 2: Input url is invalid",
url: "invalid",
wantErr: "unsupported protocol scheme",
},
{
name: "Case 3: Git provider with invalid url",
url: "github.com/mike-hoang/invalid-repo",
token: "",
want: []byte(nil),
wantErr: "failed to parse git repo. error:*",
},
{
name: "Case 4: Public Github repo with missing blob",
url: "https://github.com/devfile/library/main/README.md",
wantErr: "failed to parse git repo. error: url path to directory or file should contain 'tree' or 'blob'*",
},
{
name: "Case 5: Public Github repo, with invalid token ",
url: "https://github.com/devfile/library/blob/main/devfile.yaml",
token: "fake-token",
wantErr: fmt.Sprintf(downloadErr, "https://"+RawGitHubHost+"/devfile/library/main/devfile.yaml"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := DownloadInMemory(HTTPRequestParams{URL: tt.url, Token: tt.token})
if (err != nil) != (tt.wantErr != "") {
t.Errorf("Failed to download file with error: %s", err)
} else if err == nil && !reflect.DeepEqual(data, tt.want) {
t.Errorf("Expected: %v, received: %v, difference at %v", tt.want, string(data[:]), pretty.Compare(tt.want, data))
} else if err != nil {
assert.Regexp(t, tt.wantErr, err.Error(), "Error message should match")