-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathgithub_test.go
More file actions
2641 lines (2491 loc) · 79.2 KB
/
github_test.go
File metadata and controls
2641 lines (2491 loc) · 79.2 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 github
import (
"context"
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"net/http"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/go-github/v85/github"
"github.com/jonboulle/clockwork"
"github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/keys"
"github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1"
"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"
prmetrics "github.com/openshift-pipelines/pipelines-as-code/pkg/pipelinerunmetrics"
testclient "github.com/openshift-pipelines/pipelines-as-code/pkg/test/clients"
ghtesthelper "github.com/openshift-pipelines/pipelines-as-code/pkg/test/github"
"github.com/openshift-pipelines/pipelines-as-code/pkg/test/logger"
"go.opentelemetry.io/otel"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
"go.uber.org/zap"
zapobserver "go.uber.org/zap/zaptest/observer"
"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/ptr"
rtesting "knative.dev/pkg/reconciler/testing"
)
func TestGetTaskURI(t *testing.T) {
tests := []struct {
name string
wantErr bool
disallowed bool
eventURL string
uri string
ret string
}{
{
name: "Get Task URI",
eventURL: "https://foo.com/owner/repo/pull/1",
uri: "https://foo.com/owner/repo/blob/main/file",
wantErr: false,
ret: "hello world",
},
{
name: "not comparable host",
eventURL: "https://foo/owner/repo/pull/1",
uri: "https://bar/owner/repo/blob/main/file",
disallowed: true,
},
{
name: "bad uri",
eventURL: "https://foo/owner/repo/pull/1",
uri: "https://foo/owner/aooaooadoodao",
disallowed: true,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sha := "sha"
content := base64.StdEncoding.EncodeToString([]byte(tt.ret))
ctx, _ := rtesting.SetupFakeContext(t)
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
provider := &Provider{ghClient: fakeclient}
event := info.NewEvent()
event.HeadBranch = "main"
event.URL = tt.eventURL
mux.HandleFunc("/repos/owner/repo/contents/file", func(rw http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(rw, `{"sha": "%s"}`, sha)
})
mux.HandleFunc(fmt.Sprintf("/repos/%s/%s/git/blobs/%s", "owner", "repo", sha), func(rw http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(rw, `{"content": "%s"}`, content)
})
allowed, content, err := provider.GetTaskURI(ctx, event, tt.uri)
if (err != nil) != tt.wantErr {
t.Errorf("GetTaskURI() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.disallowed && allowed {
t.Errorf("GetTaskURI() is allowed and we want it to be disallowed")
return
} else if !tt.disallowed {
return
}
if content != tt.ret {
t.Errorf("GetTaskURI() got = %v, want %v", content, tt.ret)
}
})
}
}
func TestGithubSplitURL(t *testing.T) {
tests := []struct {
name string
url string
wantOrg string
wantRepo string
wantRef string
wantPath string
gheURL string
wantErr bool
}{
{
name: "Split URL",
url: "https://github.com/openshift-pipelines/pipelines-as-code/blob/main/testdatas/remote_task.yaml",
wantOrg: "openshift-pipelines",
wantRepo: "pipelines-as-code",
wantRef: "main",
wantPath: "testdatas/remote_task.yaml",
},
{
name: "Split URL with slash in branch",
url: "https://github.com/openshift-pipelines/pipelines-as-code/blob/feature%2Fbranch/testdatas/remote_task.yaml",
wantOrg: "openshift-pipelines",
wantRepo: "pipelines-as-code",
wantRef: "feature/branch",
wantPath: "testdatas/remote_task.yaml",
},
{
name: "Split URL with encoding emoji in branch",
url: "https://github.com/openshift-pipelines/pipelines-as-code/blob/%F0%9F%99%83/filename.yaml",
wantOrg: "openshift-pipelines",
wantRepo: "pipelines-as-code",
wantRef: "🙃",
wantPath: "filename.yaml",
},
{
name: "Split URL with url encoding emoji in filename",
url: "https://github.com/openshift-pipelines/pipelines-as-code/blob/branch/anemoji%F0%9F%99%83.yaml",
wantOrg: "openshift-pipelines",
wantRepo: "pipelines-as-code",
wantRef: "branch",
wantPath: "anemoji🙃.yaml",
},
{
name: "Split raw URL",
url: "https://raw.githubusercontent.com/openshift-pipelines/pipelines-as-code/main/testdatas/remote_task.yaml",
wantOrg: "openshift-pipelines",
wantRepo: "pipelines-as-code",
wantRef: "main",
wantPath: "testdatas/remote_task.yaml",
},
{
name: "Split raw URL2",
url: "https://raw.githubusercontent.com/openshift-pipelines/pipelines-as-code/main/remote_task.yaml",
wantOrg: "openshift-pipelines",
wantRepo: "pipelines-as-code",
wantRef: "main",
wantPath: "remote_task.yaml",
},
{
name: "Too small URL",
url: "https://raw.githubusercontent.com/openshift-pipelines/pipelines-as-code",
wantErr: true,
},
{
name: "Invalid no path URL",
url: "https://raw.githubusercontent.com/openshift-pipelines/pipelines-as-code/main",
wantErr: true,
},
{
name: "raw GHE URL",
url: "https://raw.ghe.domain.com/owner/repo/branch/file?token=TOKEN",
gheURL: "https://ghe.domain.com",
wantOrg: "owner",
wantRepo: "repo",
wantRef: "branch",
wantPath: "file",
},
{
name: "not matching ghe but allowed from public gh",
url: fmt.Sprintf("https://%s/owner/repo/branch/file?token=TOKEN", publicRawURLHost),
gheURL: "https://foo.com",
wantOrg: "owner",
wantRepo: "repo",
wantRef: "branch",
wantPath: "file",
},
{
name: "not matching raw",
url: "https://bar.com/owner/repo/branch/file?token=TOKEN",
gheURL: "https://foo.com",
wantErr: true,
},
{
name: "not a full direct url",
url: "https://raw.ghe/owner/repo/branch?token=TOKEN",
gheURL: "https://raw.ghe",
wantErr: true,
},
{
name: "bad formatted ghe url",
url: "https://raw.ghe/owner/repo/branch?token=TOKEN",
gheURL: "https:raw.ghe",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event := info.NewEvent()
event.GHEURL = tt.gheURL
org, repo, path, ref, err := splitGithubURL(event, tt.url)
if (err != nil) != tt.wantErr {
t.Errorf("SplitURL() error = %v, wantErr %v", err, tt.wantErr)
return
}
assert.Equal(t, tt.wantOrg, org)
assert.Equal(t, tt.wantRepo, repo)
assert.Equal(t, tt.wantRef, ref)
assert.Equal(t, tt.wantPath, path)
})
}
}
func TestGetTektonDir(t *testing.T) {
testGetTektonDir := []struct {
treepath string
event *info.Event
name string
expectedString string
provenance string
filterMessageSnippet string
wantErr string
expectedGHApiCalls int64
}{
{
name: "test no subtree on pull request",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
SHA: "123",
TriggerTarget: triggertype.PullRequest,
},
expectedString: "PipelineRun",
treepath: "testdata/tree/simple",
filterMessageSnippet: "Using PipelineRun definition from source pull_request tekton/cat#0",
// 1. Single GraphQL call fetches tekton tree + inline blobs
expectedGHApiCalls: 1,
},
{
name: "test no subtree on push",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
SHA: "123",
TriggerTarget: triggertype.Push,
},
expectedString: "PipelineRun",
treepath: "testdata/tree/simple",
filterMessageSnippet: "Using PipelineRun definition from source push",
// 1. Single GraphQL call fetches tekton tree + inline blobs
expectedGHApiCalls: 1,
},
{
name: "test provenance default_branch ",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
DefaultBranch: "main",
},
expectedString: "FROMDEFAULTBRANCH",
treepath: "testdata/tree/defaultbranch",
provenance: "default_branch",
filterMessageSnippet: "Using PipelineRun definition from default_branch: main",
// 1. Resolve default branch to a commit SHA
// 2. Single GraphQL call fetches tekton tree + inline blobs
expectedGHApiCalls: 2,
},
{
name: "test with subtree",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
SHA: "123",
},
expectedString: "FROMSUBTREE",
treepath: "testdata/tree/subdir",
// 1. Single GraphQL call fetches tekton tree + inline blobs (including subdirs)
expectedGHApiCalls: 1,
},
{
name: "test with badly formatted yaml",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
SHA: "123",
},
expectedString: "FROMSUBTREE",
treepath: "testdata/tree/badyaml",
wantErr: "error unmarshalling yaml file badyaml.yaml: yaml: line 2: did not find expected key",
// 1. Single GraphQL call fetches tekton tree + inline blobs
// Error occurs during YAML validation after fetch
expectedGHApiCalls: 1,
},
{
name: "test no tekton directory",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
SHA: "123",
TriggerTarget: triggertype.PullRequest,
},
expectedString: "",
treepath: "testdata/tree/notektondir",
filterMessageSnippet: "Using PipelineRun definition from source pull_request tekton/cat#0",
// 1. Get Repo root objects
// _. No tekton dir to fetch
expectedGHApiCalls: 1,
},
{
name: "test tekton directory path is file",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
SHA: "123",
},
treepath: "testdata/tree/tektondirisfile",
wantErr: ".tekton has been found but is not a directory",
// 1. Get Repo root objects
// _. Tekton dir is file, no directory to fetch
expectedGHApiCalls: 1,
},
}
for _, tt := range testGetTektonDir {
t.Run(tt.name, func(t *testing.T) {
prmetrics.ResetRecorder()
reader := sdkmetric.NewManualReader()
provider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
otel.SetMeterProvider(provider)
observer, exporter := zapobserver.New(zap.InfoLevel)
fakelogger := zap.New(observer).Sugar()
ctx, _ := rtesting.SetupFakeContext(t)
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
gvcs := Provider{
ghClient: fakeclient,
providerName: "github",
Logger: fakelogger,
}
shaDir := fmt.Sprintf("%x", sha256.Sum256([]byte(tt.treepath)))
tt.event.SHA = shaDir
if tt.provenance == "default_branch" {
mux.HandleFunc(fmt.Sprintf("/repos/%s/%s/branches/%s",
tt.event.Organization, tt.event.Repository, tt.event.DefaultBranch),
func(rw http.ResponseWriter, _ *http.Request) {
branch := &github.Branch{
Name: github.Ptr(tt.event.DefaultBranch),
Commit: &github.RepositoryCommit{
SHA: github.Ptr(shaDir),
},
}
b, _ := json.Marshal(branch)
fmt.Fprint(rw, string(b))
})
}
ghtesthelper.SetupGitTree(t, mux, tt.treepath, tt.event, false)
got, err := gvcs.GetTektonDir(ctx, tt.event, ".tekton", tt.provenance)
if tt.wantErr != "" {
assert.Assert(t, err != nil, "we should have get an error here")
assert.ErrorContains(t, err, tt.wantErr)
return
}
assert.NilError(t, err)
var rm metricdata.ResourceMetrics
err = reader.Collect(ctx, &rm)
assert.NilError(t, err, "error collecting metrics")
assert.Equal(t, len(rm.ScopeMetrics), 1)
assert.Equal(t, len(rm.ScopeMetrics[0].Metrics), 1)
assert.Equal(t, rm.ScopeMetrics[0].Metrics[0].Name, "pipelines_as_code_git_provider_api_request_count")
count, ok := rm.ScopeMetrics[0].Metrics[0].Data.(metricdata.Sum[int64])
assert.Assert(t, ok)
assert.Equal(t, count.DataPoints[0].Value, int64(tt.expectedGHApiCalls))
var gotMatch bool
if tt.expectedString == "" {
gotMatch = got == tt.expectedString
} else {
gotMatch = strings.Contains(got, tt.expectedString)
}
assert.Assert(t, gotMatch, "expected %s, got %s", tt.expectedString, 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 TestGetTektonDirGraphQL(t *testing.T) {
tests := []struct {
name string
event *info.Event
treepath string
provenance string
setup func(t *testing.T, mux *http.ServeMux, event *info.Event)
wantErr string
wantLogSnippet string
expectedAPICount int64
skipSetupGitTree bool
}{
{
name: "graphql fetch tekton dir with inline blobs",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
TriggerTarget: triggertype.PullRequest,
},
skipSetupGitTree: true,
setup: func(t *testing.T, mux *http.ServeMux, event *info.Event) {
t.Helper()
shaDir := fmt.Sprintf("%x", sha256.Sum256([]byte("testdata/tree/simple")))
event.SHA = shaDir
// Setup GraphQL endpoint with inline blob contents
mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"repository": map[string]any{
"tektonTree": map[string]any{
"entries": []map[string]any{
{
"name": "pipeline.yaml",
"type": "blob",
"path": "pipeline.yaml",
"oid": "pipeline-sha",
"object": map[string]any{"text": "kind: Pipeline\nmetadata:\n name: test\n"},
},
{
"name": "task.yaml",
"type": "blob",
"path": "task.yaml",
"oid": "task-sha",
"object": map[string]any{"text": "kind: Task\nmetadata:\n name: test\n"},
},
},
},
},
},
})
})
},
wantLogSnippet: "GitHub API call completed",
expectedAPICount: 1, // Single GraphQL call fetches tree + blobs
},
{
name: "graphql error handling",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
TriggerTarget: triggertype.PullRequest,
},
skipSetupGitTree: true,
setup: func(t *testing.T, mux *http.ServeMux, event *info.Event) {
t.Helper()
shaDir := fmt.Sprintf("%x", sha256.Sum256([]byte("testdata/tree/simple")))
event.SHA = shaDir
// Setup tree endpoints manually
mux.HandleFunc(fmt.Sprintf("/repos/%v/%v/git/trees/%v", event.Organization, event.Repository, event.SHA),
func(rw http.ResponseWriter, _ *http.Request) {
tree := &github.Tree{
SHA: &event.SHA,
Entries: []*github.TreeEntry{
{
Path: github.Ptr(".tekton"),
Type: github.Ptr("tree"),
SHA: github.Ptr("tektondirsha"),
},
},
}
b, _ := json.Marshal(tree)
fmt.Fprint(rw, string(b))
})
// Set up .tekton directory tree
tektonDirSha := "tektondirsha"
mux.HandleFunc(fmt.Sprintf("/repos/%v/%v/git/trees/%v", event.Organization, event.Repository, tektonDirSha),
func(rw http.ResponseWriter, _ *http.Request) {
tree := &github.Tree{
SHA: &tektonDirSha,
Entries: []*github.TreeEntry{
{
Path: github.Ptr("pipeline.yaml"),
Type: github.Ptr("blob"),
SHA: github.Ptr("pipelinesha"),
},
{
Path: github.Ptr("pipelinerun.yaml"),
Type: github.Ptr("blob"),
SHA: github.Ptr("pipelinerunsha"),
},
},
}
b, _ := json.Marshal(tree)
fmt.Fprint(rw, string(b))
})
// Error handler for /api/graphql
mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "GraphQL endpoint not available", http.StatusNotFound)
})
},
wantErr: "GraphQL request failed with status 404",
},
{
name: "default branch uses resolved sha for graphql",
event: &info.Event{
Organization: "tekton",
Repository: "cat",
DefaultBranch: "main",
},
provenance: "default_branch",
skipSetupGitTree: true,
setup: func(t *testing.T, mux *http.ServeMux, _ *info.Event) {
t.Helper()
resolvedSHA := "resolved-default-branch-sha"
mux.HandleFunc("/repos/tekton/cat/branches/main", func(rw http.ResponseWriter, _ *http.Request) {
branch := &github.Branch{
Name: github.Ptr("main"),
Commit: &github.RepositoryCommit{
SHA: github.Ptr(resolvedSHA),
},
}
b, _ := json.Marshal(branch)
fmt.Fprint(rw, string(b))
})
mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) {
var graphQLReq struct {
Query string `json:"query"`
Variables map[string]any `json:"variables"`
}
assert.NilError(t, json.NewDecoder(r.Body).Decode(&graphQLReq))
// New implementation uses tektonExpr variable: "resolvedSHA:.tekton"
assert.Assert(t, strings.Contains(graphQLReq.Query, "tektonTree:"), graphQLReq.Query)
assert.Assert(t, graphQLReq.Variables["tektonExpr"] == resolvedSHA+":.tekton", "expected tektonExpr=%s:.tekton, got %v", resolvedSHA, graphQLReq.Variables["tektonExpr"])
// Return tree structure with inline blob contents
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"repository": map[string]any{
"tektonTree": map[string]any{
"entries": []map[string]any{
{
"name": "pipeline.yaml",
"type": "blob",
"path": "pipeline.yaml",
"oid": "pipeline-sha",
"object": map[string]any{"text": "kind: Pipeline\nmetadata:\n name: pipeline\n"},
},
{
"name": "pipelinerun.yaml",
"type": "blob",
"path": "pipelinerun.yaml",
"oid": "pipelinerun-sha",
"object": map[string]any{"text": "kind: PipelineRun\nmetadata:\n name: run\n"},
},
},
},
},
},
})
})
},
expectedAPICount: 2, // 1 for get_default_branch + 1 for GraphQL
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Common setup
prmetrics.ResetRecorder()
reader := sdkmetric.NewManualReader()
provider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
otel.SetMeterProvider(provider)
observer, exporter := zapobserver.New(zap.DebugLevel)
fakelogger := zap.New(observer).Sugar()
ctx, _ := rtesting.SetupFakeContext(t)
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
gvcs := Provider{
ghClient: fakeclient,
providerName: "github",
Logger: fakelogger,
}
// Custom setup if provided
if tt.setup != nil {
tt.setup(t, mux, tt.event)
}
// Standard tree setup unless skipped
if !tt.skipSetupGitTree && tt.treepath != "" {
shaDir := fmt.Sprintf("%x", sha256.Sum256([]byte(tt.treepath)))
tt.event.SHA = shaDir
ghtesthelper.SetupGitTree(t, mux, tt.treepath, tt.event, false)
}
// Execute test
got, err := gvcs.GetTektonDir(ctx, tt.event, ".tekton", tt.provenance)
// Validate error
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
return
}
assert.NilError(t, err)
// Validate logs if specified
if tt.wantLogSnippet != "" {
logs := exporter.FilterMessageSnippet(tt.wantLogSnippet)
assert.Assert(t, logs.Len() > 0, "expected log message: %s", tt.wantLogSnippet)
}
// Validate metrics if specified
if tt.expectedAPICount > 0 {
var rm metricdata.ResourceMetrics
err = reader.Collect(ctx, &rm)
assert.NilError(t, err)
count, ok := rm.ScopeMetrics[0].Metrics[0].Data.(metricdata.Sum[int64])
assert.Assert(t, ok)
assert.Equal(t, count.DataPoints[0].Value, tt.expectedAPICount)
}
// Validate content
assert.Assert(t, len(got) > 0, "expected non-empty GetTektonDir output")
})
}
}
func TestGetFileInsideRepo(t *testing.T) {
testGetTektonDir := []struct {
name string
rets map[string]func(w http.ResponseWriter, r *http.Request)
filepath string
wantErrStr string
}{
{
name: "fail/trying to get a subdir",
filepath: "retdir",
rets: map[string]func(w http.ResponseWriter, r *http.Request){
"/repos/tekton/thecat/contents/retdir": func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `[{"name": "directory", "path": "a/directory"}]`)
},
},
wantErrStr: "referenced file inside the Github Repository retdir is a directory",
},
{
name: "fail/bad json",
filepath: "retfile",
rets: map[string]func(w http.ResponseWriter, r *http.Request){
"/repos/tekton/thecat/contents/retfile": func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `nonono`)
},
},
wantErrStr: "invalid character",
},
{
name: "fail/bad encoding",
filepath: "retfile",
rets: map[string]func(w http.ResponseWriter, r *http.Request){
"/repos/tekton/thecat/contents/retfile": func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `{"name": "file", "path": "a/file", "sha": "shafile"}`)
},
"/repos/tekton/thecat/git/blobs/shafile": func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `{"content": "xxxxxx", "sha": "shafile"}`)
},
},
wantErrStr: "illegal base64 data",
},
{
name: "error/cannot get blob",
filepath: "retfile",
rets: map[string]func(w http.ResponseWriter, r *http.Request){
"/repos/tekton/thecat/contents/retfile": func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `{"name": "file", "path": "a/file", "sha": "shafile"}`)
},
},
wantErrStr: "404",
},
}
for _, tt := range testGetTektonDir {
t.Run(tt.name, func(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
gvcs := Provider{
ghClient: fakeclient,
}
for s, f := range tt.rets {
mux.HandleFunc(s, f)
}
event := &info.Event{
Organization: "tekton",
Repository: "thecat",
SHA: "123",
}
got, err := gvcs.GetFileInsideRepo(ctx, event, tt.filepath, "")
if tt.wantErrStr != "" {
assert.Assert(t, err != nil, "we should have get an error here")
assert.Assert(t, strings.Contains(err.Error(), tt.wantErrStr), err.Error(), tt.wantErrStr)
return
}
assert.NilError(t, err)
assert.Assert(t, got != "")
})
}
}
func TestGetFileInsideRepoRefSelection(t *testing.T) {
fileContent := base64.StdEncoding.EncodeToString([]byte("valid owners file"))
tests := []struct {
name string
event *info.Event
target string
provenance string
expectedRef string
}{
{
name: "uses SHA when target is empty",
event: &info.Event{
Organization: "org",
Repository: "repo",
SHA: "sha123",
BaseBranch: "main",
DefaultBranch: "main",
},
target: "",
expectedRef: "sha123",
},
{
name: "uses target ref when target is provided",
event: &info.Event{
Organization: "org",
Repository: "repo",
SHA: "sha123",
BaseBranch: "main",
DefaultBranch: "main",
},
target: "refs/heads/release-1.0",
expectedRef: "refs/heads/release-1.0",
},
{
name: "uses DefaultBranch when target is empty and provenance is default_branch",
event: &info.Event{
Organization: "org",
Repository: "repo",
SHA: "sha123",
BaseBranch: "develop",
DefaultBranch: "main",
},
target: "",
provenance: "default_branch",
expectedRef: "main",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, _ := rtesting.SetupFakeContext(t)
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
gvcs := Provider{
ghClient: fakeclient,
provenance: tt.provenance,
}
mux.HandleFunc("/repos/org/repo/contents/OWNERS", func(w http.ResponseWriter, r *http.Request) {
gotRef := r.URL.Query().Get("ref")
assert.Equal(t, gotRef, tt.expectedRef)
fmt.Fprintf(w, `{"name": "OWNERS", "path": "OWNERS", "sha": "ownersha"}`)
})
mux.HandleFunc("/repos/org/repo/git/blobs/ownersha", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, `{"content": %q, "sha": "ownersha"}`, fileContent)
})
got, err := gvcs.GetFileInsideRepo(ctx, tt.event, "OWNERS", tt.target)
assert.NilError(t, err)
assert.Equal(t, got, "valid owners file")
})
}
}
func TestCheckSenderOrgMembership(t *testing.T) {
tests := []struct {
name string
apiReturn string
allowed bool
wantErr bool
runevent info.Event
}{
{
name: "Check Sender Org Membership",
runevent: info.Event{
Organization: "organization",
Sender: "me",
},
apiReturn: `[{"login": "me"}]`,
allowed: true,
wantErr: false,
},
{
name: "Check Sender not in Org Membership",
runevent: info.Event{
Organization: "organization",
Sender: "me",
},
apiReturn: `[{"login": "not"}]`,
allowed: false,
},
{
name: "Not found on organization",
runevent: info.Event{
Organization: "notfound",
Sender: "me",
},
allowed: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
ctx, _ := rtesting.SetupFakeContext(t)
gprovider := Provider{
ghClient: fakeclient,
}
mux.HandleFunc(fmt.Sprintf("/orgs/%s/members", tt.runevent.Organization), func(rw http.ResponseWriter, _ *http.Request) {
fmt.Fprint(rw, tt.apiReturn)
})
allowed, err := gprovider.checkSenderOrgMembership(ctx, &tt.runevent)
if tt.wantErr && err == nil {
t.Error("We didn't get an error when we wanted one")
}
if !tt.wantErr && err != nil {
t.Errorf("We got an error when we didn't want it: %s", err)
}
assert.Equal(t, tt.allowed, allowed)
})
}
}
func TestGetStringPullRequestComment(t *testing.T) {
tests := []struct {
name, apiReturn string
wantErr bool
runevent info.Event
wantRet bool
}{
{
name: "Get String from comments",
runevent: info.Event{URL: "http://1", PullRequestNumber: 1},
apiReturn: `[{"body": "/ok-to-test"}]`,
wantRet: true,
},
{
name: "Not matching string in comments",
runevent: info.Event{URL: "http://1", PullRequestNumber: 1},
apiReturn: `[{"body": ""}]`,
wantRet: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakeclient, mux, _, teardown := ghtesthelper.SetupGH()
defer teardown()
ctx, _ := rtesting.SetupFakeContext(t)
repo := &v1alpha1.Repository{
Spec: v1alpha1.RepositorySpec{
Settings: &v1alpha1.Settings{},
},
}
gprovider := Provider{
ghClient: fakeclient,
repo: repo,
}
mux.HandleFunc(fmt.Sprintf("/repos/issues/%s/comments", filepath.Base(tt.runevent.URL)), func(rw http.ResponseWriter, _ *http.Request) {
fmt.Fprint(rw, tt.apiReturn)
})
ret, err := gprovider.GetStringPullRequestComment(ctx, &tt.runevent)
if tt.wantErr && err == nil {
t.Error("We didn't get an error when we wanted one")
}
if !tt.wantErr && err != nil {
t.Errorf("We got an error when we didn't want it: %s", err)
}
if tt.wantRet {
assert.Assert(t, ret != nil)
}
})
}
}
func TestGithubGetCommitInfo(t *testing.T) {
tests := []struct {
name string
event *info.Event
noclient bool
apiReply, wantErr string
shaurl, shatitle, message string
authorName, authorEmail string
committerName, committerEmail string
authorDate, committerDate string
checkExtendedFields bool
wantHasSkipCmd bool
}{
{
name: "good with full commit info",
event: &info.Event{
Organization: "owner",
Repository: "repository",
SHA: "shacommitinfo",
},
shaurl: "https://git.provider/commit/info",
shatitle: "My beautiful pony",
message: "My beautiful pony\n\nThis is the full commit message with details.",
authorName: "John Doe",
authorEmail: "john@example.com",
committerName: "GitHub",
committerEmail: "noreply@github.com",
authorDate: "2024-01-15T10:30:00Z",
committerDate: "2024-01-15T10:31:00Z",
checkExtendedFields: true,
},
{
name: "basic fields only",
event: &info.Event{
Organization: "owner",
Repository: "repository",
SHA: "shacommitinfo",
},
shaurl: "https://git.provider/commit/info",
shatitle: "My beautiful pony",
message: "My beautiful pony",
wantHasSkipCmd: false,
},
{
name: "commit with skip ci command",
event: &info.Event{
Organization: "owner",
Repository: "repository",
SHA: "shacommitinfo",
},
shaurl: "https://git.provider/commit/info",
shatitle: "fix: some bug",
message: "fix: some bug\n\n[skip ci]",
wantHasSkipCmd: true,
},
{
name: "commit with ci skip command in title",
event: &info.Event{
Organization: "owner",
Repository: "repository",
SHA: "shacommitinfo",
},
shaurl: "https://git.provider/commit/info",
shatitle: "feat: new feature [ci skip]",
message: "feat: new feature [ci skip]",
wantHasSkipCmd: true,
},
{
name: "commit with skip tkn command in title",
event: &info.Event{
Organization: "owner",
Repository: "repository",
SHA: "shacommitinfo",
},
shaurl: "https://git.provider/commit/info",