-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfigrepo_test.go
1020 lines (846 loc) · 39.5 KB
/
configrepo_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
package gocd_test
import (
_ "embed"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/nikhilsbhat/gocd-sdk-go"
"github.com/stretchr/testify/assert"
)
var (
//go:embed internal/fixtures/config_repos.json
configReposJSON string
//go:embed internal/fixtures/config_repo.json
configRepoJSON string
//go:embed internal/fixtures/config_repo_definitions.json
configRepoDefinition string
//go:embed internal/fixtures/config_repo_internal.json
configRepoInternalJSON string
eTag = "05548388f7ef5042cd39f7fe42e85735"
correctHeader = map[string]string{"Accept": gocd.HeaderVersionFour}
configRepo = testGetConfigRepoObj()
)
func TestConfig_GetConfigRepoInfo(t *testing.T) {
t.Run("should error out while fetching config repos information from server", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.GetConfigRepos()
assert.EqualError(t, err, "call made to get config-repos errored with: "+
"Get \"http://localhost:8156/go/api/admin/config_repos\": dial tcp [::1]:8156: connect: connection refused")
assert.Nil(t, actual)
})
t.Run("should error out while fetching config repos information as server returned non 200 status code", func(t *testing.T) {
server := mockServer([]byte("backupJSON"), http.StatusBadGateway, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepos()
assert.EqualError(t, err, "got 502 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos\nwith BODY:backupJSON")
assert.Nil(t, actual)
})
t.Run("should error out while fetching config repos information as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte(`{"email_on_failure"}`), http.StatusOK, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepos()
assert.EqualError(t, err, "reading response body errored with: invalid character '}' after object key")
assert.Nil(t, actual)
})
t.Run("should be able retrieve config repos information", func(t *testing.T) {
server := mockServer([]byte(configReposJSON), http.StatusOK, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := []gocd.ConfigRepo{
{
ID: "repo1",
PluginID: "json.config.plugin",
Material: gocd.Material{
Type: "git",
Attributes: gocd.Attribute{
URL: "https://github.com/config-repo/gocd-json-config-example.git",
Username: "bob",
EncryptedPassword: "aSdiFgRRZ6A=",
Branch: "master",
AutoUpdate: true,
},
},
Configuration: []gocd.PluginConfiguration{
{
Key: "username",
Value: "admin",
},
{
Key: "password",
EncryptedValue: "1f3rrs9uhn63hd",
},
{
Key: "url",
Value: "https://github.com/sample/example.git",
IsSecure: true,
},
},
Rules: []map[string]string{
{
"directive": "allow",
"action": "refer",
"type": "pipeline_group",
"resource": "*",
},
},
},
}
actual, err := client.GetConfigRepos()
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
}
func TestConfig_GetConfigReposInternal(t *testing.T) {
t.Run("should error out while fetching config repos information from server using GoCD's internal API", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.GetConfigReposInternal()
assert.EqualError(t, err, "call made to get config-repos using internal API errored with: "+
"Get \"http://localhost:8156/go/api/internal/config_repos\": dial tcp [::1]:8156: connect: connection refused")
assert.Nil(t, actual)
})
t.Run("should error out while fetching config repos information using GoCD's internal API, as server returned non 200 status code", func(t *testing.T) {
server := mockServer([]byte("backupJSON"), http.StatusBadGateway, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigReposInternal()
assert.EqualError(t, err, "got 502 from GoCD while making GET call for "+server.URL+
"/api/internal/config_repos\nwith BODY:backupJSON")
assert.Nil(t, actual)
})
t.Run("should error out while fetching config repos information using GoCD's internal API, as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte(`{"email_on_failure"}`), http.StatusOK, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigReposInternal()
assert.EqualError(t, err, "reading response body errored with: invalid character '}' after object key")
assert.Nil(t, actual)
})
t.Run("should be able retrieve config repos information using GoCD's internal API", func(t *testing.T) {
server := mockServer([]byte(configRepoInternalJSON), http.StatusOK, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := []gocd.ConfigRepo{
{
PluginID: "json.config.plugin",
ID: "gocd-go-sdk",
Material: gocd.Material{
Type: "git",
Attributes: gocd.Attribute{
URL: "https://github.com/nikhilsbhat/gocd-sdk-go.git",
Branch: "master",
AutoUpdate: true,
},
},
Configuration: []gocd.PluginConfiguration{},
Rules: []map[string]string{},
ConfigRepoParseInfo: gocd.ConfigRepoParseInfo{
LatestParsedModification: map[string]interface{}{
"comment": "Add support for GET config-repo definitions API",
"email_address": interface{}(nil),
"modified_time": "2023-06-27T13:46:33Z",
"revision": "2d1e4525a6f26cf0699c06c2ce36ab6ac512c9e6",
"username": "nikhilsbhat <[email protected]>",
},
GoodModification: map[string]interface{}{
"comment": "Add support for GET config-repo definitions API",
"email_address": interface{}(nil), "modified_time": "2023-06-27T13:46:33Z",
"revision": "2d1e4525a6f26cf0699c06c2ce36ab6ac512c9e6",
"username": "nikhilsbhat <[email protected]>",
},
},
},
{
PluginID: "yaml.config.plugin",
ID: "sample_config_repo",
Material: gocd.Material{
Type: "git",
Attributes: gocd.Attribute{
URL: "https://github.com/config-repo/gocd-json-config-example.git",
Username: "bob",
EncryptedPassword: "AES:I/umvAruOKkDyHJFflavCQ==:4hikK7OSpJN50E4SerstZw==",
Branch: "master",
AutoUpdate: true,
},
},
Configuration: []gocd.PluginConfiguration{
{
Key: "url",
Value: "https://github.com/config-repo/gocd-json-config-example.git",
},
{
Key: "username",
Value: "admin",
},
{
Key: "password",
Value: "admin",
},
},
Rules: []map[string]string{
{
"action": "refer",
"directive": "allow",
"resource": "*",
"type": "pipeline_group",
},
},
ConfigRepoParseInfo: gocd.ConfigRepoParseInfo{
Error: "MODIFICATION CHECK FAILED FOR MATERIAL: " +
"URL: HTTPS://GITHUB.COM/CONFIG-REPO/GOCD-JSON-CONFIG-EXAMPLE.GIT, " +
"BRANCH: MASTER\nNO PIPELINES ARE AFFECTED BY THIS MATERIAL, " +
"PERHAPS THIS MATERIAL IS UNUSED.\nFailed to run git clone command " +
"STDERR: Cloning into '/Users/nikhil.bhat/idfc/gocd-setup/go-server-22.1.0/pipelines/flyweight/2b3feb60-efd7-41d3-8041-3e0d3208285e'...\n" +
"STDERR: remote: Support for password authentication was removed on August 13, 2021.\n" +
"STDERR: remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls " +
"for information on currently recommended modes of authentication.\n" +
"STDERR: fatal: Authentication failed for 'https://github.com/config-repo/gocd-json-config-example.git/'",
},
},
}
actual, err := client.GetConfigReposInternal()
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
}
func Test_client_CreateConfigRepoInfo(t *testing.T) {
t.Run("server should return internal server error as malformed json passed while creating config repo", func(t *testing.T) {
server := mockConfigRepoServer(configReposJSON, http.MethodPost, map[string]string{"Accept": gocd.HeaderVersionFour, "Content-Type": gocd.ContentJSON}, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
err := client.CreateConfigRepo(gocd.ConfigRepo{})
assert.EqualError(t, err, "got 500 from GoCD while making POST call for "+server.URL+
"/api/admin/config_repos\nwith BODY:json: cannot unmarshal string into Go value of type gocd.ConfigRepo")
})
t.Run("should error out while making client call to create config repo", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
err := client.CreateConfigRepo(gocd.ConfigRepo{})
assert.EqualError(t, err, "call made to create config repo errored with: "+
"Post \"http://localhost:8156/go/api/admin/config_repos\": dial tcp [::1]:8156: connect: connection refused")
})
t.Run("should create config repo successfully", func(t *testing.T) {
server := mockConfigRepoServer(configRepo, http.MethodPost, map[string]string{"Accept": gocd.HeaderVersionFour, "Content-Type": gocd.ContentJSON}, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
err := client.CreateConfigRepo(*configRepo)
assert.NoError(t, err)
})
}
func Test_client_DeleteConfigRepo(t *testing.T) {
repoName := "repo1"
t.Run("should error out while deleting config repo due to server connectivity issues", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
err := client.DeleteConfigRepo(repoName)
assert.EqualError(t, err, "call made to delete config repo 'repo1' errored with: "+
"Delete \"http://localhost:8156/go/api/admin/config_repos/repo1\": dial tcp [::1]:8156: connect: connection refused")
})
t.Run("server should return 404 due to wrong header set while deleting config repo", func(t *testing.T) {
server := mockConfigRepoServer(nil, http.MethodDelete, map[string]string{"Accept": gocd.HeaderVersionOne}, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
err := client.DeleteConfigRepo(repoName)
assert.EqualError(t, err, "got 404 from GoCD while making DELETE call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
})
t.Run("should be able to delete config repo successfully", func(t *testing.T) {
server := mockConfigRepoServer(nil, http.MethodDelete, map[string]string{"Accept": gocd.HeaderVersionFour}, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
err := client.DeleteConfigRepo(repoName)
assert.NoError(t, err)
})
}
func Test_client_GetConfigRepo(t *testing.T) {
repoName := "repo1"
t.Run("should error out while fetching config repo information as server returned non 200 status code", func(t *testing.T) {
server := mockConfigRepoServer(configRepoJSON, http.MethodPost, correctHeader, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepo(repoName)
assert.EqualError(t, err, "got 500 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:json: cannot unmarshal string into Go value of type gocd.ConfigRepo")
assert.Equal(t, gocd.ConfigRepo{}, actual)
})
t.Run("should error out while fetching config repo information as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte(`{"email_on_failure"}`), http.StatusOK, correctHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepo(repoName)
assert.EqualError(t, err, "reading response body errored with: invalid character '}' after object key")
assert.Equal(t, gocd.ConfigRepo{}, actual)
})
t.Run("should error out while fetching config repo information from server since server is not reachable", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.GetConfigRepo(repoName)
assert.EqualError(t, err, "call made to get config-repo errored with: "+
"Get \"http://localhost:8156/go/api/admin/config_repos/repo1\": dial tcp [::1]:8156: connect: connection refused")
assert.Equal(t, gocd.ConfigRepo{}, actual)
})
t.Run("server should return 404 due to wrong header set while fetching config repo", func(t *testing.T) {
server := mockConfigRepoServer(nil, http.MethodGet, map[string]string{"Accept": gocd.HeaderVersionOne}, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepo(repoName)
assert.EqualError(t, err, "got 404 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, gocd.ConfigRepo{}, actual)
})
t.Run("server should return 404 no header set while fetching config repo", func(t *testing.T) {
server := mockConfigRepoServer(nil, http.MethodGet, nil, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepo(repoName)
assert.EqualError(t, err, "got 404 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, gocd.ConfigRepo{}, actual)
})
t.Run("should error when header ETag is not set by server", func(t *testing.T) {
server := mockConfigRepoServer(configRepo, http.MethodGet, correctHeader, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.GetConfigRepo(repoName)
assert.EqualError(t, err, "header ETag not set, this will impact while getting config-repo")
assert.Equal(t, configRepo.ID, actual.ID)
assert.Equal(t, *configRepo, actual)
})
t.Run("should be able to get config repo successfully", func(t *testing.T) {
newConfigRepo := configRepo
server := mockConfigRepoServer(newConfigRepo, http.MethodGet, correctHeader, true)
client := gocd.NewClient(server.URL, auth, "info", nil)
newConfigRepo.ETAG = eTag
actual, err := client.GetConfigRepo(repoName)
assert.Nil(t, err)
assert.Equal(t, newConfigRepo.ID, actual.ID)
assert.Equal(t, *newConfigRepo, actual)
})
}
func Test_client_UpdateConfigRepo(t *testing.T) {
t.Run("should error out while updating config repo information as server returned non 200 status code", func(t *testing.T) {
newConfigRepo := configRepo
newConfigRepo.ETAG = eTag
newCorrectHeader := correctHeader
newCorrectHeader["If-Match"] = eTag
server := mockConfigRepoServer(configReposJSON, http.MethodPut, newCorrectHeader, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.UpdateConfigRepo(*configRepo)
assert.EqualError(t, err, "got 500 from GoCD while making PUT call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:json: cannot unmarshal string into Go value of type gocd.ConfigRepo")
assert.Equal(t, "", actual)
})
t.Run("should error out while updating config repo since server is not reachable", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.UpdateConfigRepo(*configRepo)
assert.EqualError(t, err, "call made to call made to update config repo errored with: "+
"Put \"http://localhost:8156/go/api/admin/config_repos/repo1\": dial tcp [::1]:8156: connect: connection refused")
assert.Equal(t, "", actual)
})
t.Run("server should return 404 due to wrong header set while updating config repo", func(t *testing.T) {
newConfigRepo := configRepo
newConfigRepo.ETAG = eTag
server := mockConfigRepoServer(newConfigRepo, http.MethodPut, map[string]string{"If-Match": eTag, "Accept": gocd.HeaderVersionOne}, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.UpdateConfigRepo(*newConfigRepo)
assert.EqualError(t, err, "got 404 from GoCD while making PUT call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, "", actual)
})
t.Run("server should return 404 no header set while updating config repo", func(t *testing.T) {
server := mockConfigRepoServer(nil, http.MethodPut, nil, false)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.UpdateConfigRepo(*configRepo)
assert.EqualError(t, err, "got 404 from GoCD while making PUT call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, "", actual)
})
t.Run("should error since wrong ETag was specified while updating config repo", func(t *testing.T) {
newConfigRepo := configRepo
newConfigRepo.ETAG = eTag
newCorrectHeader := correctHeader
newCorrectHeader["If-Match"] = "eTag"
server := mockConfigRepoServer(newConfigRepo, http.MethodPut, newCorrectHeader, true)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.UpdateConfigRepo(*newConfigRepo)
assert.EqualError(t, err, "got 406 from GoCD while making PUT call for "+server.URL+
"/api/admin/config_repos/repo1\nwith BODY:lost update")
assert.Equal(t, "", actual)
})
t.Run("should update config repo successfully", func(t *testing.T) {
newConfigRepo := configRepo
newConfigRepo.ETAG = eTag
correctHeader["If-Match"] = eTag
server := mockConfigRepoServer(newConfigRepo, http.MethodPut, correctHeader, true)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.UpdateConfigRepo(*newConfigRepo)
assert.NoError(t, err)
assert.Equal(t, eTag, actual)
})
}
func Test_client_ConfigRepoTriggerUpdate(t *testing.T) {
correctConfigHeader := map[string]string{"Accept": gocd.HeaderVersionFour, "X-GoCD-Confirm": "true"}
t.Run("Should be able to trigger update for a config repo successfully", func(t *testing.T) {
server := mockServer([]byte(`{"message": "OK"}`), http.StatusCreated, correctConfigHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := map[string]string{
"message": "OK",
}
actual, err := client.ConfigRepoTriggerUpdate("config_repo_1")
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
t.Run("Should error out while triggering config repo update as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte(`{"message": }`), http.StatusCreated, correctConfigHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.ConfigRepoTriggerUpdate("config_repo_1")
assert.EqualError(t, err, "reading response body errored with: invalid character '}' looking for beginning of value")
assert.Equal(t, map[string]string(nil), actual)
})
t.Run("Should not update config repo as scheduled update is still in progress", func(t *testing.T) {
server := mockServer([]byte(`{"message": "Update already in progress."}`), http.StatusConflict, correctConfigHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := map[string]string{
"message": "Update already in progress.",
}
actual, err := client.ConfigRepoTriggerUpdate("config_repo_1")
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
t.Run("Should error out while triggering update config due to wrong headers", func(t *testing.T) {
server := mockServer(nil, http.StatusConflict,
map[string]string{"Accept": gocd.HeaderVersionThree, "X-GoCD-Confirm": "true"}, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.ConfigRepoTriggerUpdate("config_repo_1")
assert.EqualError(t, err, "got 404 from GoCD while making POST call for "+server.URL+
"/api/admin/config_repos/config_repo_1/trigger_update\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, map[string]string(nil), actual)
})
t.Run("Should error out while triggering update config due to missing headers", func(t *testing.T) {
server := mockServer(nil, http.StatusOK, nil, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.ConfigRepoTriggerUpdate("config_repo_1")
assert.EqualError(t, err, "got 404 from GoCD while making POST call for "+server.URL+
"/api/admin/config_repos/config_repo_1/trigger_update\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, map[string]string(nil), actual)
})
t.Run("Should error out while triggering update config as server is not reachable", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.ConfigRepoTriggerUpdate("config_repo_1")
assert.EqualError(t, err, "call made to trigger update configrepo 'config_repo_1' errored with: "+
"Post \"http://localhost:8156/go/api/admin/config_repos/config_repo_1/trigger_update\": dial tcp [::1]:8156: connect: connection refused")
assert.Nil(t, actual)
})
}
func Test_client_ConfigRepoStatus(t *testing.T) {
correctConfigHeader := map[string]string{"Accept": gocd.HeaderVersionFour}
t.Run("Should be able to fetch the status of the config-repo successfully", func(t *testing.T) {
server := mockServer([]byte(`{"in_progress": true}`), http.StatusOK, correctConfigHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := map[string]bool{
"in_progress": true,
}
actual, err := client.ConfigRepoStatus("config_repo_1")
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
t.Run("Should error out while fetching config-repo status as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte(`{"in_progress": }`), http.StatusOK, correctConfigHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.ConfigRepoStatus("config_repo_1")
assert.EqualError(t, err, "reading response body errored with: invalid character '}' looking for beginning of value")
assert.Equal(t, map[string]bool(nil), actual)
})
t.Run("Should error out while fetching config-repo status due to wrong headers", func(t *testing.T) {
server := mockServer(nil, http.StatusConflict,
map[string]string{"Accept": gocd.HeaderVersionThree, "X-GoCD-Confirm": "true"}, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.ConfigRepoStatus("config_repo_1")
assert.EqualError(t, err, "got 404 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/config_repo_1/status\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, map[string]bool(nil), actual)
})
t.Run("Should error out while fetching config-repo status due to missing headers", func(t *testing.T) {
server := mockServer(nil, http.StatusOK, nil, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
actual, err := client.ConfigRepoStatus("config_repo_1")
assert.EqualError(t, err, "got 404 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/config_repo_1/status\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, map[string]bool(nil), actual)
})
t.Run("Should error out while fetching config-repo status as server is not reachable", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
actual, err := client.ConfigRepoStatus("config_repo_1")
assert.EqualError(t, err, "call made to get status of configrepo 'config_repo_1' errored with: "+
"Get \"http://localhost:8156/go/api/admin/config_repos/config_repo_1/status\": dial tcp [::1]:8156: connect: connection refused")
assert.Nil(t, actual)
})
}
func Test_client_ConfigRepoPreflightCheck(t *testing.T) {
correctPreflightHeader := map[string]string{"Accept": gocd.HeaderVersionOne}
preflightCheckJSON := `{"errors" : [],"valid" : true}`
t.Run("should be able to run config-repo preflight checks successfully", func(t *testing.T) {
server := mockServer([]byte(preflightCheckJSON), http.StatusOK,
correctPreflightHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
pipelineFiles, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
pipelineMap := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipelineMap, "yaml.config.plugin", "sample")
assert.NoError(t, err)
assert.Equal(t, true, actual)
})
t.Run("should error out while running config-repo preflight checks in GoCD due to wrong headers", func(t *testing.T) {
server := mockServer([]byte(preflightCheckJSON), http.StatusOK,
map[string]string{"Accept": gocd.HeaderVersionThree}, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
pipelineFiles, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
pipelineMap := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipelineMap, "yaml.config.plugin", "sample")
assert.EqualError(t, err, "got 404 from GoCD while making POST call for "+server.URL+
"/api/admin/config_repo_ops/preflight?pluginId=yaml.config.plugin&repoId=sample\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, false, actual)
})
t.Run("should error out while running config-repo preflight checks in GoCD due to missing headers", func(t *testing.T) {
server := mockServer([]byte(preflightCheckJSON), http.StatusOK,
nil, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
pipelineFiles, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
pipelineMap := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipelineMap, "yaml.config.plugin", "sample")
assert.EqualError(t, err, "got 404 from GoCD while making POST call for "+server.URL+
"/api/admin/config_repo_ops/preflight?pluginId=yaml.config.plugin&repoId=sample\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, false, actual)
})
t.Run("should error out while running config-repo preflight checks in GoCD as preflight checks failed", func(t *testing.T) {
preflightCheckJSONNew := `{"errors" : ["invalid merge configurations, duplicate key TEST","invalid merge configurations, duplicate key ENV"],"valid" : false}`
server := mockServer([]byte(preflightCheckJSONNew), http.StatusOK, correctPreflightHeader,
false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
pipelineFiles, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
pipelineMap := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipelineMap, "yaml.config.plugin", "sample")
assert.EqualError(t, err, "invalid merge configurations, duplicate key TEST\ninvalid merge configurations, duplicate key ENV")
assert.Equal(t, false, actual)
})
t.Run("should error out while running config-repo preflight checks in GoCD as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte("preflightCheckJSON"), http.StatusOK, correctPreflightHeader,
false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
pipelineFiles, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
pipelineMap := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipelineMap, "yaml.config.plugin", "sample")
assert.EqualError(t, err, "reading response body errored with: invalid character 'p' looking for beginning of value")
assert.Equal(t, false, actual)
})
t.Run("should error out while running config-repo preflight checks in GoCD as server is not reachable", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
pipelineFiles, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
pipelineMap := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipelineMap, "yaml.config.plugin", "sample")
assert.EqualError(t, err, "call made to preflight check of confirepo 'sample' errored with: "+
"Post \"http://localhost:8156/go/api/admin/config_repo_ops/preflight?pluginId=yaml.config.plugin&repoId=sample\": "+
"dial tcp [::1]:8156: connect: connection refused")
assert.Equal(t, false, actual)
})
t.Run("should be able to run config-repo preflight checks successfully", func(t *testing.T) {
goCDAuth := gocd.Auth{
UserName: "admin",
Password: "admin",
}
client := gocd.NewClient("http://localhost:8153/go", goCDAuth, "info", nil)
homeDir, err := os.UserHomeDir()
assert.NoError(t, err)
pipelineFiles, err := client.GetPipelineFiles(filepath.Join(homeDir, "opensource/gocd-git-path-sample"), "*.gocd.yaml")
assert.NoError(t, err)
pipeliness := client.SetPipelineFiles(pipelineFiles)
actual, err := client.ConfigRepoPreflightCheck(pipeliness, "yaml.config.plugin", "sample-repo")
assert.NoError(t, err)
assert.Equal(t, true, actual)
})
}
func Test_client_SetPipelineFiles(t *testing.T) {
t.Run("should be able to return the map equivalent of []gocd.PipelineFiles", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
pipelines := []gocd.PipelineFiles{
{
Name: "pipeline1",
Path: "absolute/path/to/pipeline/1",
},
{
Name: "pipeline2",
Path: "absolute/path/to/pipeline/2",
},
{
Name: "pipeline3",
Path: "absolute/path/to/pipeline/3",
},
{
Name: "pipeline4",
Path: "absolute/path/to/pipeline/4",
},
{
Name: "pipeline5",
Path: "absolute/path/to/pipeline/5",
},
}
expected := map[string]string{
"pipeline1": "absolute/path/to/pipeline/1",
"pipeline2": "absolute/path/to/pipeline/2",
"pipeline3": "absolute/path/to/pipeline/3",
"pipeline4": "absolute/path/to/pipeline/4",
"pipeline5": "absolute/path/to/pipeline/5",
}
actual := client.SetPipelineFiles(pipelines)
assert.Equal(t, expected, actual)
})
}
func Test_client_GetPipelineFiles(t *testing.T) {
t.Run("should be able to identify the path as directory and fetch the pipelines", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "debug", nil)
expected := []gocd.PipelineFiles{
{
Name: "mail_server_config.json",
Path: "/Users/nikhil.bhat/my-opensource/gocd-sdk-go/internal/fixtures/mail_server_config.json",
},
{
Name: "role_config.json",
Path: "/Users/nikhil.bhat/my-opensource/gocd-sdk-go/internal/fixtures/role_config.json",
},
{
Name: "roles_config.json",
Path: "/Users/nikhil.bhat/my-opensource/gocd-sdk-go/internal/fixtures/roles_config.json",
},
{
Name: "secrets_config.json",
Path: "/Users/nikhil.bhat/my-opensource/gocd-sdk-go/internal/fixtures/secrets_config.json",
},
}
actual, err := client.GetPipelineFiles("internal/fixtures", "*_config.json")
assert.NoError(t, err)
assert.Equal(t, len(expected), len(actual))
assert.Equal(t, expected, actual)
})
t.Run("should error out while parsing directory to fetch the pipelines since pattern is missing", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "debug", nil)
actual, err := client.GetPipelineFiles("internal/fixture", "*_config.json")
assert.EqualError(t, err, "stat internal/fixture: no such file or directory")
assert.Nil(t, actual)
})
t.Run("should error out while parsing directory due to wrong path", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "debug", nil)
actual, err := client.GetPipelineFiles("internal/fixtures")
assert.EqualError(t, err, "pipeline files pattern not passed (ex: *.gocd.yaml)")
assert.Nil(t, actual)
})
t.Run("should be able to identify the path as file", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "debug", nil)
expected := []gocd.PipelineFiles{
{
Name: "mail_server_config.json",
Path: "/Users/nikhil.bhat/my-opensource/gocd-sdk-go/internal/fixtures/mail_server_config.json",
},
}
actual, err := client.GetPipelineFiles("internal/fixtures/mail_server_config.json")
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
t.Run("should error out while identifying the pipeline files due to wrong path", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "debug", nil)
actual, err := client.GetPipelineFiles("internal/fixture/mail_server_config.json")
assert.EqualError(t, err, "stat internal/fixture/mail_server_config.json: no such file or directory")
assert.Nil(t, actual)
})
}
func mockConfigRepoServer(request interface{}, method string, header map[string]string, etag bool) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
if header == nil {
writer.WriteHeader(http.StatusNotFound)
if _, err := writer.Write([]byte(`<html>
<body>
<h2>404 Not found</h2>
</body>
</html>`)); err != nil {
log.Fatalln(err)
}
return
}
var configRepo gocd.ConfigRepo
requestByte, err := json.Marshal(request)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
if _, err = writer.Write([]byte(fmt.Sprintf("%s %s", string(requestByte), err.Error()))); err != nil {
log.Fatalln(err)
}
return
}
if err = json.Unmarshal(requestByte, &configRepo); err != nil {
writer.WriteHeader(http.StatusInternalServerError)
if _, err = writer.Write([]byte(err.Error())); err != nil {
log.Fatalln(err)
}
return
}
for key, value := range header {
if len(req.Header.Get("If-Match")) != 0 {
if header["If-Match"] != request.(*gocd.ConfigRepo).ETAG {
writer.WriteHeader(http.StatusNotAcceptable)
if _, err := writer.Write([]byte(`lost update`)); err != nil {
log.Fatalln(err)
}
return
}
}
if req.Header.Get(key) != value {
writer.WriteHeader(http.StatusNotFound)
if _, err := writer.Write([]byte(`<html>
<body>
<h2>404 Not found</h2>
</body>
</html>`)); err != nil {
log.Fatalln(err)
}
return
}
}
if method == http.MethodDelete {
writer.WriteHeader(http.StatusOK)
if _, err := writer.Write([]byte(`{"message": "The config repo 'repo-1' was deleted successfully."}`)); err != nil {
log.Fatalln(err)
}
return
}
if etag {
writer.Header().Set("ETag", eTag)
}
writer.WriteHeader(http.StatusOK)
if method == http.MethodGet {
if _, err = writer.Write(requestByte); err != nil {
log.Fatalln(err)
}
}
}))
}
func Test_client_GetConfigRepoDefinitions(t *testing.T) {
correctArtifactHeader := map[string]string{"Accept": gocd.HeaderVersionFour}
configRepoName := "config-repo-group"
t.Run("should be able to fetch the definitions defined in config repo successfully", func(t *testing.T) {
server := mockServer([]byte(configRepoDefinition), http.StatusOK,
correctArtifactHeader, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := gocd.ConfigRepo{
Environments: []gocd.Environment{
{
Name: "dev",
},
},
Groups: []gocd.PipelineGroup{
{
Name: configRepoName,
Pipelines: []gocd.Pipeline{
{
Name: "pipeline1",
},
{
Name: "pipeline2",
},
},
},
},
}
actual, err := client.GetConfigRepoDefinitions(configRepoName)
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
t.Run("should error out while fetching definitions defined in config repo present in GoCD due to wrong headers", func(t *testing.T) {
server := mockServer([]byte(artifactStoresJSON), http.StatusOK,
map[string]string{"Accept": gocd.HeaderVersionThree}, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := gocd.ConfigRepo{}
actual, err := client.GetConfigRepoDefinitions(configRepoName)
assert.EqualError(t, err, "got 404 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/config-repo-group/definitions\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, expected, actual)
})
t.Run("should error out while fetching definitions defined in config repo present in GoCD due to missing headers", func(t *testing.T) {
server := mockServer([]byte(artifactStoresJSON), http.StatusOK,
nil, false, nil)
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := gocd.ConfigRepo{}
actual, err := client.GetConfigRepoDefinitions(configRepoName)
assert.EqualError(t, err, "got 404 from GoCD while making GET call for "+server.URL+
"/api/admin/config_repos/config-repo-group/definitions\nwith BODY:<html>\n<body>\n\t<h2>404 Not found</h2>\n</body>\n\n</html>")
assert.Equal(t, expected, actual)
})
t.Run("should error out while fetching definitions defined in config repo from GoCD as server returned malformed response", func(t *testing.T) {
server := mockServer([]byte("artifactStoreJSON"), http.StatusOK, correctArtifactHeader,
false, map[string]string{"ETag": "cbc5f2d5b9c13a2cc1b1efb3d8a6155d"})
client := gocd.NewClient(server.URL, auth, "info", nil)
expected := gocd.ConfigRepo{}
actual, err := client.GetConfigRepoDefinitions(configRepoName)
assert.EqualError(t, err, "reading response body errored with: invalid character 'a' looking for beginning of value")
assert.Equal(t, expected, actual)
})
t.Run("should error out while fetching definitions defined in config repo present in GoCD as server is not reachable", func(t *testing.T) {
client := gocd.NewClient("http://localhost:8156/go", auth, "info", nil)
client.SetRetryCount(1)
client.SetRetryWaitTime(1)
expected := gocd.ConfigRepo{}
actual, err := client.GetConfigRepoDefinitions(configRepoName)
assert.EqualError(t, err, "call made to get config-repo definitions for 'config-repo-group' errored with: "+
"Get \"http://localhost:8156/go/api/admin/config_repos/config-repo-group/definitions\": dial tcp [::1]:8156: connect: connection refused")
assert.Equal(t, expected, actual)
})
}
func testGetConfigRepoObj() *gocd.ConfigRepo {
configRepo := &gocd.ConfigRepo{
PluginID: "json.config.plugin",
ID: "repo1",
Configuration: nil,
Rules: nil,
}
configRepo.Material.Type = "git"
configRepo.Material.Attributes.URL = "https://github.com/config-repo/gocd-json-config-example.git"
configRepo.Material.Attributes.AutoUpdate = false
configRepo.Material.Attributes.Branch = "master"
configRepo.Rules = []map[string]string{
{
"directive": "allow",
"action": "refer",
"type": "pipeline_group",
"resource": "*",