forked from tektoncd/pipelines-as-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitlab_test.go
More file actions
1171 lines (1124 loc) · 31 KB
/
gitlab_test.go
File metadata and controls
1171 lines (1124 loc) · 31 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
package gitlab
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"testing"
"github.com/openshift-pipelines/pipelines-as-code/pkg/events"
"github.com/openshift-pipelines/pipelines-as-code/pkg/opscomments"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/clients"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/info"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/settings"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype"
"github.com/openshift-pipelines/pipelines-as-code/pkg/provider"
thelp "github.com/openshift-pipelines/pipelines-as-code/pkg/provider/gitlab/test"
testclient "github.com/openshift-pipelines/pipelines-as-code/pkg/test/clients"
"github.com/openshift-pipelines/pipelines-as-code/pkg/test/logger"
gitlab "gitlab.com/gitlab-org/api/client-go"
"go.uber.org/zap"
zapobserver "go.uber.org/zap/zaptest/observer"
"gotest.tools/v3/assert"
rtesting "knative.dev/pkg/reconciler/testing"
)
func TestCreateStatus(t *testing.T) {
type fields struct {
targetProjectID int
}
type args struct {
event *info.Event
statusOpts provider.StatusOpts
postStr string
}
tests := []struct {
name string
fields fields
args args
wantErr bool
wantClient bool
}{
{
name: "no client has been set",
wantErr: true,
},
{
name: "skip in progress",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Status: "in_progress",
},
},
},
{
name: "skipped conclusion",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "skipped",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "has skipped",
},
},
{
name: "neutral conclusion",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "neutral",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "has stopped",
},
},
{
name: "failure conclusion",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "failure",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "has failed",
},
},
{
name: "success conclusion",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "success",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "has successfully",
},
},
{
name: "pending conclusion",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "pending",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "",
},
},
{
name: "completed conclusion",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "completed",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "has completed",
},
},
{
name: "gitops comments completed",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "completed",
},
event: &info.Event{
TriggerTarget: "Note",
},
postStr: "has completed",
},
},
{
name: "completed with a details url",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "skipped",
DetailsURL: "https://url.com",
},
event: &info.Event{
TriggerTarget: "pull_request",
},
postStr: "https://url.com",
},
},
{
name: "pending conclusion for gitops command on pushed commit",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "pending",
},
event: &info.Event{
TriggerTarget: "push",
EventType: opscomments.TestAllCommentEventType.String(),
},
postStr: "",
},
},
{
name: "completed conclusion for gitops command on pushed commit",
wantClient: true,
wantErr: false,
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "completed",
},
event: &info.Event{
TriggerTarget: "push",
EventType: opscomments.RetestAllCommentEventType.String(),
},
postStr: "has completed",
},
},
{
name: "commit status success on source project",
wantClient: true,
wantErr: false,
fields: fields{
targetProjectID: 100,
},
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "success",
},
event: &info.Event{
TriggerTarget: "pull_request",
SourceProjectID: 200,
TargetProjectID: 100,
SHA: "abc123",
},
postStr: "has successfully",
},
},
{
name: "commit status falls back to target project",
wantClient: true,
wantErr: false,
fields: fields{
targetProjectID: 100,
},
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "success",
},
event: &info.Event{
TriggerTarget: "pull_request",
SourceProjectID: 404, // Will fail to find this project
TargetProjectID: 100,
SHA: "abc123",
},
postStr: "has successfully",
},
},
{
name: "commit status fails on both projects but continues",
wantClient: true,
wantErr: false,
fields: fields{
targetProjectID: 100,
},
args: args{
statusOpts: provider.StatusOpts{
Conclusion: "success",
},
event: &info.Event{
TriggerTarget: "pull_request",
SourceProjectID: 404, // Will fail
TargetProjectID: 405, // Will fail
SHA: "abc123",
},
postStr: "has successfully",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
logger, _ := logger.GetLogger()
stdata, _ := testclient.SeedTestData(t, ctx, testclient.Data{})
run := ¶ms.Run{
Clients: clients.Clients{
Kube: stdata.Kube,
Log: logger,
},
}
v := &Provider{
targetProjectID: tt.fields.targetProjectID,
run: params.New(),
Logger: logger,
pacInfo: &info.PacOpts{
Settings: settings.Settings{
ApplicationName: settings.PACApplicationNameDefaultValue,
},
},
eventEmitter: events.NewEventEmitter(run.Clients.Kube, logger),
}
if tt.args.event == nil {
tt.args.event = info.NewEvent()
}
tt.args.event.PullRequestNumber = 666
if tt.wantClient {
client, mux, tearDown := thelp.Setup(t)
v.SetGitLabClient(client)
defer tearDown()
// Mock commit status endpoints for both source and target projects
if tt.args.event.SourceProjectID != 0 {
// Mock source project commit status endpoint
sourceStatusPath := fmt.Sprintf("/projects/%d/statuses/%s", tt.args.event.SourceProjectID, tt.args.event.SHA)
mux.HandleFunc(sourceStatusPath, func(rw http.ResponseWriter, _ *http.Request) {
if tt.args.event.SourceProjectID == 404 {
// Simulate failure on source project
rw.WriteHeader(http.StatusNotFound)
fmt.Fprint(rw, `{"message": "404 Project Not Found"}`)
return
}
// Success on source project
rw.WriteHeader(http.StatusCreated)
fmt.Fprint(rw, `{}`)
})
}
if tt.args.event.TargetProjectID != 0 {
// Mock target project commit status endpoint
targetStatusPath := fmt.Sprintf("/projects/%d/statuses/%s", tt.args.event.TargetProjectID, tt.args.event.SHA)
mux.HandleFunc(targetStatusPath, func(rw http.ResponseWriter, _ *http.Request) {
if tt.args.event.TargetProjectID == 404 {
// Simulate failure on target project
rw.WriteHeader(http.StatusNotFound)
fmt.Fprint(rw, `{"message": "404 Project Not Found"}`)
return
}
// Success on target project
rw.WriteHeader(http.StatusCreated)
fmt.Fprint(rw, `{}`)
})
}
thelp.MuxNotePost(t, mux, v.targetProjectID, tt.args.event.PullRequestNumber, tt.args.postStr)
}
if err := v.CreateStatus(ctx, tt.args.event, tt.args.statusOpts); (err != nil) != tt.wantErr {
t.Errorf("CreateStatus() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestGetCommitInfo(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
client, _, tearDown := thelp.Setup(t)
v := &Provider{gitlabClient: client}
defer tearDown()
assert.NilError(t, v.GetCommitInfo(ctx, info.NewEvent()))
ncv := &Provider{}
assert.Assert(t, ncv.GetCommitInfo(ctx, info.NewEvent()) != nil)
}
func TestGetConfig(t *testing.T) {
v := &Provider{}
assert.Assert(t, v.GetConfig().APIURL != "")
assert.Assert(t, v.GetConfig().TaskStatusTMPL != "")
}
func TestSetClient(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
core, observer := zapobserver.New(zap.InfoLevel)
fakelogger := zap.New(core).Sugar()
run := ¶ms.Run{
Clients: clients.Clients{
Log: fakelogger,
},
}
v := &Provider{}
assert.Assert(t, v.SetClient(ctx, run, info.NewEvent(), nil, nil) != nil)
client, _, tearDown := thelp.Setup(t)
defer tearDown()
vv := &Provider{gitlabClient: client}
err := vv.SetClient(ctx, run, &info.Event{
Provider: &info.Provider{
Token: "hello",
},
Organization: "my-org",
Repository: "my-repo",
SourceProjectID: 1234,
TargetProjectID: 1234,
}, nil, nil)
assert.NilError(t, err)
assert.Assert(t, *vv.Token != "")
logs := observer.TakeAll()
assert.Assert(t, len(logs) > 0, "expected a log entry, got none")
expected := fmt.Sprintf(
"gitlab: initialized for client with token for apiURL=%s, org=%s, repo=%s",
vv.apiURL, "my-org", "my-repo")
assert.Equal(t, expected, logs[0].Message)
}
func TestSetClientDetectAPIURL(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
observer, _ := zapobserver.New(zap.InfoLevel)
fakelogger := zap.New(observer).Sugar()
run := ¶ms.Run{
Clients: clients.Clients{
Log: fakelogger,
},
}
mockClient, _, tearDown := thelp.Setup(t)
defer tearDown()
// Define test cases
tests := []struct {
name string
providerToken string
providerURL string // input: event.Provider.URL
repoURL string // input: v.repoURL
pathWithNamespace string // input: v.pathWithNamespace (needed if repoURL is used)
eventURL string // input: event.URL
// Define expected outcomes
expectedAPIURL string
expectedError string // Substring expected in the error message, "" for no error
}{
{
name: "Error: No token provided",
providerToken: "",
expectedError: "no git_provider.secret has been set",
},
{
name: "Success: API URL from event.Provider.URL (highest precedence)",
providerToken: "token",
providerURL: "https://provider.example.com",
repoURL: "https://repo.example.com/foo/bar", // Should be ignored
pathWithNamespace: "foo/bar",
eventURL: "https://event.example.com/foo/bar", // Should be ignored
expectedAPIURL: "https://provider.example.com",
expectedError: "",
},
{
name: "Success: API URL from v.repoURL (non-public)",
providerToken: "token",
providerURL: "", // This must be empty to test the next case
repoURL: "https://private-gitlab.com/my/repo",
pathWithNamespace: "my/repo",
eventURL: "https://event.example.com/my/repo", // Should be ignored
expectedAPIURL: "https://private-gitlab.com/",
expectedError: "",
},
{
name: "Success: API URL from event.URL",
providerToken: "token",
providerURL: "", // This must be empty
repoURL: "", // This must be empty
eventURL: "https://event-url.com/org/project",
expectedAPIURL: "https://event-url.com",
expectedError: "",
},
{
name: "Success: Fallback to default public API URL",
providerToken: "token",
providerURL: "",
repoURL: "",
eventURL: "",
expectedAPIURL: apiPublicURL, // Default case
expectedError: "",
},
{
name: "Success: Default URL when repoURL is public GitLab",
providerToken: "token",
providerURL: "",
repoURL: apiPublicURL + "/public/repo", // Starts with public URL, so skipped
pathWithNamespace: "public/repo",
eventURL: "", // Falls through to default
expectedAPIURL: apiPublicURL,
expectedError: "",
},
{
name: "Error: Invalid URL from event.URL",
providerToken: "token",
providerURL: "",
repoURL: "",
eventURL: "://bad-schema",
expectedError: "parse \"://bad-schema\": missing protocol scheme", // Specific error from url.Parse
},
{
name: "Error: Invalid URL from event.Provider.URL (final parse)",
providerToken: "token",
providerURL: "ht tp://invalid host", // Invalid URL format
repoURL: "",
eventURL: "",
expectedError: "failed to parse api url", // Wrapper error message
},
{
name: "Error: Invalid URL from v.repoURL (final parse)",
providerToken: "token",
providerURL: "",
repoURL: "ht tp://invalid.repo.url/foo/bar", // Invalid format
pathWithNamespace: "foo/bar",
eventURL: "",
// Note: The calculated apiURL would be "ht tp://invalid.repo.url" before parsing
expectedError: "failed to parse api url",
},
}
// Run test cases
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Setup specific to this test case
v := &Provider{
gitlabClient: mockClient, // Use the shared mock client
repoURL: tc.repoURL,
pathWithNamespace: tc.pathWithNamespace,
}
event := info.NewEvent()
event.Provider.Token = tc.providerToken
event.Provider.URL = tc.providerURL
event.URL = tc.eventURL
// Set some default IDs to avoid potential nil pointer issues or side effects
// if the GetProject part of SetClient is reached unexpectedly.
event.TargetProjectID = 1
event.SourceProjectID = 1
// Execute the function under test
// Using placeholder nil values for arguments not directly related to URL detection
err := v.SetClient(ctx, run, event, nil, nil)
// Assertions
if tc.expectedError != "" {
assert.ErrorContains(t, err, tc.expectedError)
// If an error is expected, we usually don't check the apiURL state,
// as it might be indeterminate or irrelevant.
} else {
assert.NilError(t, err)
// Only check the resulting apiURL if no error was expected
assert.Equal(t, tc.expectedAPIURL, v.apiURL)
// Optionally, check if the client was actually set (if no error)
assert.Assert(t, v.Client() != nil)
assert.Assert(t, v.Token != nil && *v.Token == tc.providerToken)
}
})
}
}
func TestGetTektonDir(t *testing.T) {
samplePR, err := os.ReadFile("../../resolve/testdata/pipeline-finally.yaml")
assert.NilError(t, err)
type fields struct {
targetProjectID int
sourceProjectID int
userID int
}
type args struct {
event *info.Event
path string
provenance string
}
tests := []struct {
name string
fields fields
args args
wantStr string
wantErr string
wantTreeAPIErr bool
wantFilesAPIErr bool
wantClient bool
prcontent string
filterMessageSnippet string
}{
{
name: "no client set",
wantErr: noClientErrStr,
},
{
name: "not found, no err",
wantClient: true,
args: args{event: &info.Event{}},
},
{
name: "bad yaml",
wantClient: true,
args: args{
event: &info.Event{SHA: "abcd", HeadBranch: "main"},
path: ".tekton",
},
fields: fields{
sourceProjectID: 10,
},
prcontent: "bad:\n- yaml\nfoo",
wantErr: "error unmarshalling yaml file pr.yaml: yaml: line 4: could not find expected ':'",
},
{
name: "list tekton dir on pull request",
prcontent: string(samplePR),
args: args{
path: ".tekton",
event: &info.Event{
HeadBranch: "main",
TriggerTarget: triggertype.PullRequest,
},
},
fields: fields{
sourceProjectID: 100,
},
wantClient: true,
wantStr: "kind: PipelineRun",
filterMessageSnippet: `Using PipelineRun definition from source merge request on commit SHA`,
},
{
name: "list tekton dir on push",
prcontent: string(samplePR),
args: args{
path: ".tekton",
event: &info.Event{
HeadBranch: "main",
TriggerTarget: triggertype.Push,
},
},
fields: fields{
sourceProjectID: 100,
},
wantClient: true,
wantStr: "kind: PipelineRun",
filterMessageSnippet: `Using PipelineRun definition from source push on commit SHA`,
},
{
name: "list tekton dir on default_branch",
prcontent: string(samplePR),
args: args{
provenance: "default_branch",
path: ".tekton",
event: &info.Event{
DefaultBranch: "main",
},
},
fields: fields{
sourceProjectID: 100,
},
wantClient: true,
wantStr: "kind: PipelineRun",
},
{
name: "list tekton dir no --- prefix",
prcontent: strings.TrimPrefix(string(samplePR), "---"),
args: args{
path: ".tekton",
event: &info.Event{
HeadBranch: "main",
},
},
fields: fields{
sourceProjectID: 100,
},
wantClient: true,
wantStr: "kind: PipelineRun",
},
{
name: "list tekton dir tree api call error",
prcontent: strings.TrimPrefix(string(samplePR), "---"),
args: args{
path: ".tekton",
event: &info.Event{
HeadBranch: "main",
},
},
fields: fields{
sourceProjectID: 100,
},
wantClient: true,
wantTreeAPIErr: true,
wantErr: "failed to list .tekton dir",
},
{
name: "get file raw api call error",
prcontent: strings.TrimPrefix(string(samplePR), "---"),
args: args{
path: ".tekton",
event: &info.Event{
HeadBranch: "main",
},
},
fields: fields{
sourceProjectID: 100,
},
wantClient: true,
wantFilesAPIErr: true,
wantErr: "failed to get filename from api pr.yaml dir",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
observer, exporter := zapobserver.New(zap.InfoLevel)
fakelogger := zap.New(observer).Sugar()
v := &Provider{
targetProjectID: tt.fields.targetProjectID,
sourceProjectID: tt.fields.sourceProjectID,
userID: tt.fields.userID,
Logger: fakelogger,
}
if tt.wantClient {
client, mux, tearDown := thelp.Setup(t)
v.SetGitLabClient(client)
muxbranch := tt.args.event.HeadBranch
if tt.args.provenance == "default_branch" {
muxbranch = tt.args.event.DefaultBranch
}
if tt.args.path != "" && tt.prcontent != "" {
thelp.MuxListTektonDir(t, mux, tt.fields.sourceProjectID, muxbranch, tt.prcontent, tt.wantTreeAPIErr, tt.wantFilesAPIErr)
}
defer tearDown()
}
got, err := v.GetTektonDir(ctx, tt.args.event, tt.args.path, tt.args.provenance)
if tt.wantErr != "" {
assert.Assert(t, err != nil, "expected error %s, got %v", tt.wantErr, err)
assert.ErrorContains(t, err, tt.wantErr)
return
}
if tt.wantStr != "" {
assert.Assert(t, strings.Contains(got, tt.wantStr), "%s is not in %s", tt.wantStr, got)
}
if tt.filterMessageSnippet != "" {
gotcha := exporter.FilterMessageSnippet(tt.filterMessageSnippet)
assert.Assert(t, gotcha.Len() > 0, "expected to find %s in logs, found %v", tt.filterMessageSnippet, exporter.All())
}
})
}
}
func TestGetFileInsideRepo(t *testing.T) {
content := "hello moto"
ctx, _ := rtesting.SetupFakeContext(t)
client, mux, tearDown := thelp.Setup(t)
defer tearDown()
event := &info.Event{
HeadBranch: "branch",
}
v := Provider{
sourceProjectID: 10,
gitlabClient: client,
}
thelp.MuxListTektonDir(t, mux, v.sourceProjectID, event.HeadBranch, content, false, false)
got, err := v.GetFileInsideRepo(ctx, event, "pr.yaml", "")
assert.NilError(t, err)
assert.Equal(t, content, got)
_, err = v.GetFileInsideRepo(ctx, event, "notfound", "")
assert.Assert(t, err != nil)
}
func TestValidate(t *testing.T) {
tests := []struct {
name string
wantErr bool
secretToken string
eventToken string
}{
{
name: "valid event",
wantErr: false,
secretToken: "test",
eventToken: "test",
},
{
name: "fail validation, no secret defined",
wantErr: true,
secretToken: "",
eventToken: "test",
},
{
name: "fail validation",
wantErr: true,
secretToken: "secret",
eventToken: "test",
},
{
name: "fail validation, missing event token",
wantErr: true,
secretToken: "secret",
eventToken: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v := &Provider{}
httpHeader := http.Header{}
httpHeader.Set("X-Gitlab-Token", tt.eventToken)
event := info.NewEvent()
event.Request = &info.Request{
Header: httpHeader,
}
event.Provider = &info.Provider{
WebhookSecret: tt.secretToken,
}
if err := v.Validate(context.TODO(), nil, event); (err != nil) != tt.wantErr {
t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestGetFiles(t *testing.T) {
tests := []struct {
name string
event *info.Event
mrchanges []*gitlab.MergeRequestDiff
pushChanges []*gitlab.Diff
wantAddedFilesCount int
wantDeletedFilesCount int
wantModifiedFilesCount int
wantRenamedFilesCount int
sourceProjectID, targetProjectID int
wantError bool
}{
{
name: "pull-request",
event: &info.Event{
TriggerTarget: "pull_request",
Organization: "pullrequestowner",
Repository: "pullrequestrepository",
PullRequestNumber: 10,
},
mrchanges: []*gitlab.MergeRequestDiff{
{
NewPath: "modified.yaml",
},
{
NewPath: "added.doc",
NewFile: true,
},
{
NewPath: "removed.yaml",
DeletedFile: true,
},
{
NewPath: "renamed.doc",
RenamedFile: true,
},
},
wantAddedFilesCount: 1,
wantDeletedFilesCount: 1,
wantModifiedFilesCount: 1,
wantRenamedFilesCount: 1,
targetProjectID: 10,
},
{
name: "pull-request with wrong project ID",
event: &info.Event{
TriggerTarget: "pull_request",
Organization: "pullrequestowner",
Repository: "pullrequestrepository",
PullRequestNumber: 10,
},
mrchanges: []*gitlab.MergeRequestDiff{
{
NewPath: "modified.yaml",
},
{
NewPath: "added.doc",
NewFile: true,
},
{
NewPath: "removed.yaml",
DeletedFile: true,
},
{
NewPath: "renamed.doc",
RenamedFile: true,
},
},
wantAddedFilesCount: 0,
wantDeletedFilesCount: 0,
wantModifiedFilesCount: 0,
wantRenamedFilesCount: 0,
targetProjectID: 12,
wantError: true,
},
{
name: "push",
event: &info.Event{
TriggerTarget: "push",
Organization: "pushrequestowner",
Repository: "pushrequestrepository",
SHA: "shacommitinfo",
},
pushChanges: []*gitlab.Diff{
{
NewPath: "modified.yaml",
},
{
NewPath: "added.doc",
NewFile: true,
},
{
NewPath: "removed.yaml",
DeletedFile: true,
},
{
NewPath: "renamed.doc",
RenamedFile: true,
},
},
wantAddedFilesCount: 1,
wantDeletedFilesCount: 1,
wantModifiedFilesCount: 1,
wantRenamedFilesCount: 1,
sourceProjectID: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
fakeclient, mux, teardown := thelp.Setup(t)
defer teardown()
mergeFileChanges := []*gitlab.MergeRequestDiff{
{
NewPath: "modified.yaml",
},
{
NewPath: "added.doc",
NewFile: true,
},
{
NewPath: "removed.yaml",
DeletedFile: true,
},
{
NewPath: "renamed.doc",
RenamedFile: true,
},
}
if tt.event.TriggerTarget == "pull_request" {
mux.HandleFunc(fmt.Sprintf("/projects/10/merge_requests/%d/diffs",
tt.event.PullRequestNumber), func(rw http.ResponseWriter, _ *http.Request) {
jeez, err := json.Marshal(mergeFileChanges)
assert.NilError(t, err)
_, _ = rw.Write(jeez)
})
}
pushFileChanges := []*gitlab.Diff{
{
NewPath: "modified.yaml",
},
{
NewPath: "added.doc",
NewFile: true,
},
{
NewPath: "removed.yaml",
DeletedFile: true,
},
{
NewPath: "renamed.doc",
RenamedFile: true,
},
}
if tt.event.TriggerTarget == "push" {
mux.HandleFunc(fmt.Sprintf("/projects/0/repository/commits/%s/diff", tt.event.SHA),
func(rw http.ResponseWriter, _ *http.Request) {
jeez, err := json.Marshal(pushFileChanges)
assert.NilError(t, err)
_, _ = rw.Write(jeez)
})
}
providerInfo := &Provider{gitlabClient: fakeclient, sourceProjectID: tt.sourceProjectID, targetProjectID: tt.targetProjectID}
changedFiles, err := providerInfo.GetFiles(ctx, tt.event)
if tt.wantError != true {
assert.NilError(t, err, nil)
}
assert.Equal(t, tt.wantAddedFilesCount, len(changedFiles.Added))
assert.Equal(t, tt.wantDeletedFilesCount, len(changedFiles.Deleted))
assert.Equal(t, tt.wantModifiedFilesCount, len(changedFiles.Modified))
assert.Equal(t, tt.wantRenamedFilesCount, len(changedFiles.Renamed))
if tt.event.TriggerTarget == "pull_request" {
for i := range changedFiles.All {
assert.Equal(t, tt.mrchanges[i].NewPath, changedFiles.All[i])
}
}
if tt.event.TriggerTarget == "push" {
for i := range changedFiles.All {
assert.Equal(t, tt.pushChanges[i].NewPath, changedFiles.All[i])
}
}
})
}
}
func TestIsHeadCommitOfBranch(t *testing.T) {
tests := []struct {
name string
event *info.Event
branchName string
wantClient bool
errStatusCode int