forked from opendevstack/ods-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain_test.go
662 lines (620 loc) · 17.1 KB
/
main_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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"reflect"
"strings"
"testing"
"text/template"
)
// SETUP
func TestMain(m *testing.M) {
log.SetOutput(ioutil.Discard)
os.Exit(m.Run())
}
func TestMakePipelineName(t *testing.T) {
tests := []struct {
project string
component string
branch string
expected string
}{
{
"PRJ",
"comp",
"bugfix/PRJ-529-bar-6-baz",
"comp-529",
},
{ // also allow a bare ticket id.
"PRJ",
"comp",
"bugfix/PRJ-529",
"comp-529",
},
{
// case insensitive comparison of project
"pRJ",
"comp",
"bugfix/Prj-529-bar-6-baz",
"comp-529",
},
{
// case insensitive comparison of component
// component appears in lowercase in pipeline
"PRJ",
"ComP",
"bugfix/PRJ-529-bar-6-baz",
"comp-529",
},
{
// missing - project in request
"",
"comp",
"bugfix/PRJ-529-bar-6-baz",
"comp-6",
},
{
"PRJ",
"comp",
"bugfix/äü",
"comp-bugfix-",
},
{
// assert current behavior, but could be changed in the future.
"PRJ",
"comp",
"bugfix/PRJ-529-PRJ-777-bar-6-baz",
"comp-777",
},
{
// assert current behavior, but could be changed in the future.
"PRJ",
"comp",
"bugfix/PRJ-529/PRJ-777-bar-6-baz",
"comp-777",
},
// Cases which leads to pipeline string of
// {comp}-{sanitized(branch)}
{
// project is a prefix or project in branch
"PR",
"comp",
"bugfix/PRJ-529-bar-6-baz",
"comp-bugfix-prj-529-bar-6-baz",
},
{
// project in branch is a prefix of project
"PRJL",
"comp",
"bugfix/PRJ-529-bar-6-baz",
"comp-bugfix-prj-529-bar-6-baz",
},
{
// missing '-' between project and number
"PRJ",
"comp",
"bugfix/PRJ529-bar-6-baz",
"comp-bugfix-prj529-bar-6-baz",
},
}
for _, tt := range tests {
pipeline := makePipelineName(tt.project, tt.component, tt.branch)
if tt.expected != pipeline {
t.Errorf(
"Expected '%s' but '%s' returned by makePipeline(project='%s', component='%s', branch='%s')",
tt.expected,
pipeline,
tt.project,
tt.component,
tt.branch,
)
}
}
}
func TestIsProtectedBranch(t *testing.T) {
tests := []struct {
protectedBranchs []string
branch string
expected bool
}{
{
[]string{"master"},
"develop",
false,
},
{
[]string{"master", "develop"},
"develop",
true,
},
{
[]string{"*"},
"develop",
true,
},
{
[]string{"master", "release/"},
"release/v1",
true,
},
{
[]string{"master", "release/"},
"release",
false,
},
{
[]string{"hotfix/"},
"feature/v2",
false,
},
}
for _, tt := range tests {
actual := isProtectedBranch(tt.protectedBranchs, tt.branch)
if tt.expected != actual {
t.Errorf(
"Expected '%v' but '%v' returned by isProtectedBranch(protectedBranchs='%s', branch='%s')",
tt.expected,
actual,
tt.protectedBranchs,
tt.branch,
)
}
}
}
type mockClient struct {
Event *Event
}
func (c *mockClient) Forward(e *Event, triggerSecret string) ([]byte, error) {
c.Event = e
return nil, nil
}
func (c *mockClient) CreatePipelineIfRequired(tmpl *template.Template, e *Event, data BuildConfigData) (int, error) {
c.Event = e
return 0, nil
}
func (c *mockClient) DeletePipeline(e *Event) error {
c.Event = e
return nil
}
func testServer() (*httptest.Server, *mockClient) {
mc := &mockClient{}
server := &Server{
Client: mc,
Namespace: "bar-cd",
Project: "bar",
TriggerSecret: "s3cr3t",
ProtectedBranches: []string{"baz"},
AllowedExternalProjects: []string{"opendevstack"},
RepoBase: "https://domain.com",
}
return httptest.NewServer(server.HandleRoot()), mc
}
func TestHandleRootRequiresTriggerSecret(t *testing.T) {
ts, mc := testServer()
defer ts.Close()
tests := map[string]struct {
URL string
}{
"without trigger_secret param:": {ts.URL},
"with empty trigger_secret param": {ts.URL + "?trigger_secret="},
"with wrong trigger_secret param": {ts.URL + "?trigger_secret=abc"},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
f, err := os.Open("test/fixtures/repo-refs-changed-payload.json")
if err != nil {
t.Error(err)
return
}
res, err := http.Post(tc.URL, "application/json", f)
if err != nil {
t.Error(err)
return
}
expected := http.StatusUnauthorized
actual := res.StatusCode
if expected != actual {
t.Fatalf("Got status %v, want %v", actual, expected)
}
if mc.Event != nil {
t.Fatalf("Event was %v, want nil", mc.Event)
}
})
}
}
func TestHandleRootReadsRequests(t *testing.T) {
ts, mc := testServer()
defer ts.Close()
// The expected events depend on the values in the payload files.
tests := map[string]struct {
payloadFile string
expectedEvent *Event
}{
"Refs changed": {
payloadFile: "repo-refs-changed-payload.json",
expectedEvent: &Event{
Kind: "forward",
Namespace: "bar-cd",
Repo: "repository",
Component: "repository",
Branch: "master",
Pipeline: "repository-master",
},
},
"PR merged": {
payloadFile: "pr-merged-payload.json",
expectedEvent: &Event{
Kind: "delete",
Namespace: "bar-cd",
Repo: "repository",
Component: "repository",
Branch: "admin/file-1505781548644",
Pipeline: "repository-admin-file-1505781548644",
},
},
"PR declined": {
payloadFile: "pr-declined-payload.json",
expectedEvent: &Event{
Kind: "delete",
Namespace: "bar-cd",
Repo: "repository",
Component: "repository",
Branch: "decline-me",
Pipeline: "repository-decline-me",
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
f, err := os.Open("test/fixtures/" + tc.payloadFile)
if err != nil {
t.Fatal(err)
}
// Use secret defined in fake server.
res, err := http.Post(ts.URL+"?trigger_secret=s3cr3t", "application/json", f)
if err != nil {
t.Fatal(err)
}
_, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
}
expected := http.StatusOK
actual := res.StatusCode
if expected != actual {
t.Fatalf("Got status: %v, want: %v", actual, expected)
}
// RequestID cannot be known in advance, so set it now from actual value.
tc.expectedEvent.RequestID = mc.Event.RequestID
if !reflect.DeepEqual(tc.expectedEvent, mc.Event) {
t.Fatalf("Got event: %v, want: %v", mc.Event, tc.expectedEvent)
}
})
}
}
func TestNamespaceRestriction(t *testing.T) {
tests := map[string]struct {
payloadFile string
project string
allowedExternalProjects []string
expectedPipeline string
expectedStatusCode int
}{
"Prov App": {
payloadFile: "prov-app-changed-payload.json",
project: "prov",
allowedExternalProjects: []string{"opendevstack"},
expectedPipeline: "prov-app-pipeline.json",
expectedStatusCode: 200,
},
"Other": {
payloadFile: "prov-app-changed-payload.json",
project: "foo",
allowedExternalProjects: []string{"baz"},
expectedPipeline: "",
expectedStatusCode: 400,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var expectedOpenshiftPayload []byte
var err error
if len(tc.expectedPipeline) > 0 {
expectedOpenshiftPayload, err = ioutil.ReadFile("test/golden/" + tc.expectedPipeline)
if err != nil {
t.Fatal(err)
}
}
var actualOpenshiftPayload []byte
// Create OpenShift stub: Returns 404 when asked for a pipeline,
// and writes the body of the request to +actual+ when pipeline
// is to be created.
apiStub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/buildconfigs") && r.Method == "POST" {
actualOpenshiftPayload, _ = ioutil.ReadAll(r.Body)
}
if strings.Contains(r.URL.Path, "/buildconfigs/") && r.Method == "GET" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
w.WriteHeader(200)
_, err := w.Write([]byte(""))
if err != nil {
t.Fatal(err)
}
}))
// Client pointing to the API stub created above
c := &ocClient{
HTTPClient: &http.Client{},
OpenShiftAPIBaseURL: apiStub.URL,
Token: "foo",
}
// Server using the special client
fakeSecret := "s3cr3t"
s := &Server{
Client: c,
Namespace: tc.project + "-cd",
Project: tc.project,
TriggerSecret: fakeSecret,
ProtectedBranches: []string{"baz"},
AllowedExternalProjects: tc.allowedExternalProjects,
RepoBase: "https://domain.com",
}
ts := httptest.NewServer(s.HandleRoot())
defer ts.Close()
f, err := os.Open("test/fixtures/" + tc.payloadFile)
if err != nil {
t.Fatal(err)
}
res, err := http.Post(ts.URL+"?trigger_secret="+fakeSecret, "application/json", f)
if err != nil {
t.Fatal(err)
}
_, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
}
if res.StatusCode != tc.expectedStatusCode {
t.Fatalf("Got response %d, want: %d", res.StatusCode, tc.expectedStatusCode)
}
if len(expectedOpenshiftPayload) > 0 && string(actualOpenshiftPayload) != string(expectedOpenshiftPayload) {
t.Fatalf("Got request body: %s, want: %s", actualOpenshiftPayload, expectedOpenshiftPayload)
}
})
}
}
func TestForward(t *testing.T) {
// Sample response from OpenShift
expected, err := ioutil.ReadFile("test/fixtures/webhook-triggered-payload.json")
if err != nil {
t.Error(err)
}
// Create a stub that returns the fixed response
apiStub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write(expected)
if err != nil {
t.Fatal(err)
}
}))
// Client pointing to the API stub created above
c := &ocClient{
HTTPClient: &http.Client{},
OpenShiftAPIBaseURL: apiStub.URL,
Token: "foo",
}
event := &Event{
Kind: "forward",
Namespace: "bar-cd",
Repo: "repository",
Component: "repository",
Branch: "master",
Pipeline: "repository-master",
}
// Ensure the response from OpenShift is forwarded as-is to the client
actual, err := c.Forward(event, "s3cr3t")
if err != nil {
t.Error(err)
}
if string(actual) != string(expected) {
t.Errorf("Got response: %s, want: %s", actual, expected)
}
}
func TestBuildEndpoint(t *testing.T) {
tests := map[string]struct {
whpPath string
whpPayload string
whpExpectedResponseStatus int
whpExpectedResponseBody string
openshiftExpectedPayload string
openshiftResponseBody string
openshiftResponseStatus int
}{
"request without trigger secret": {
whpPath: "/build",
whpPayload: "test/fixtures/build-payload.json",
whpExpectedResponseStatus: 401,
whpExpectedResponseBody: "",
openshiftExpectedPayload: "",
openshiftResponseBody: "",
openshiftResponseStatus: 0,
},
"valid payload": {
whpPath: "/build?trigger_secret=s3cr3t",
whpPayload: "test/fixtures/build-payload.json",
whpExpectedResponseStatus: 200,
whpExpectedResponseBody: "",
openshiftExpectedPayload: "test/golden/build-pipeline.json",
openshiftResponseBody: "",
openshiftResponseStatus: 201,
},
"valid payload with param": {
whpPath: "/build?component=baz&trigger_secret=s3cr3t",
whpPayload: "test/fixtures/build-payload.json",
whpExpectedResponseStatus: 200,
whpExpectedResponseBody: "",
openshiftExpectedPayload: "test/golden/build-component-pipeline.json",
openshiftResponseBody: "",
openshiftResponseStatus: 201,
},
"broken payload": {
whpPath: "/build?trigger_secret=s3cr3t",
whpPayload: "test/fixtures/build-broken-payload.txt",
whpExpectedResponseStatus: 400,
whpExpectedResponseBody: "Cannot parse JSON\n",
openshiftExpectedPayload: "",
openshiftResponseBody: "",
openshiftResponseStatus: 0,
},
"invalid payload": {
whpPath: "/build?trigger_secret=s3cr3t",
whpPayload: "test/fixtures/build-invalid-payload.json",
whpExpectedResponseStatus: 400,
whpExpectedResponseBody: "Invalid input\n",
openshiftExpectedPayload: "",
openshiftResponseBody: "",
openshiftResponseStatus: 0,
},
"accepted payload rejected by OpenShift": {
whpPath: "/build?trigger_secret=s3cr3t",
whpPayload: "test/fixtures/build-rejected-payload.json",
whpExpectedResponseStatus: 422,
whpExpectedResponseBody: "Could not create pipeline\n",
openshiftExpectedPayload: "",
openshiftResponseBody: "test/fixtures/build-rejected-openshift-response.json",
openshiftResponseStatus: 422,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// Expected payload to create the BuildConfig
expectedOpenshiftPayload := []byte{}
if tc.openshiftExpectedPayload != "" {
e, err := ioutil.ReadFile(tc.openshiftExpectedPayload)
if err != nil {
t.Fatal(err)
}
expectedOpenshiftPayload = e
}
openshiftResponseBody := []byte{}
if tc.openshiftResponseBody != "" {
or, err := ioutil.ReadFile(tc.openshiftResponseBody)
if err != nil {
t.Fatal(err)
}
openshiftResponseBody = or
}
var actualOpenshiftPayload []byte
// Create OpenShift stub: Returns 404 when asked for a pipeline,
// and writes the body of the request to +actual+ when pipeline
// is to be created.
apiStub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/buildconfigs") && r.Method == "POST" {
actualOpenshiftPayload, _ = ioutil.ReadAll(r.Body)
}
if strings.Contains(r.URL.Path, "/buildconfigs/") && r.Method == "GET" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
w.WriteHeader(tc.openshiftResponseStatus)
_, err := w.Write(openshiftResponseBody)
if err != nil {
t.Fatal(err)
}
}))
// Client pointing to the API stub created above
c := &ocClient{
HTTPClient: &http.Client{},
OpenShiftAPIBaseURL: apiStub.URL,
Token: "foo",
}
// Server using the special client
s := &Server{
Client: c,
Namespace: "bar-cd",
Project: "bar",
TriggerSecret: "s3cr3t",
ProtectedBranches: []string{"baz"},
AllowedExternalProjects: []string{"opendevstack"},
RepoBase: "https://domain.com",
}
server := httptest.NewServer(s.HandleRoot())
// Make request to /build with payload
f, err := os.Open(tc.whpPayload)
if err != nil {
t.Fatal(err)
}
res, err := http.Post(server.URL+tc.whpPath, "application/json", f)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != tc.whpExpectedResponseStatus {
t.Fatalf("Got response %d, want: %d", res.StatusCode, tc.whpExpectedResponseStatus)
}
if len(expectedOpenshiftPayload) > 0 && string(actualOpenshiftPayload) != string(expectedOpenshiftPayload) {
t.Fatalf("Got request body: %s, want: %s", actualOpenshiftPayload, expectedOpenshiftPayload)
}
actualBody, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if len(tc.whpExpectedResponseBody) > 0 && string(actualBody) != tc.whpExpectedResponseBody {
t.Fatalf("Got response body: %s, want: %s", actualBody, tc.whpExpectedResponseBody)
}
})
}
}
func TestNotFound(t *testing.T) {
// Server using a mocked client
s := &Server{
Client: &mockClient{},
Namespace: "bar-cd",
Project: "bar",
TriggerSecret: "s3cr3t",
ProtectedBranches: []string{"baz"},
AllowedExternalProjects: []string{"opendevstack"},
RepoBase: "https://domain.com",
}
server := httptest.NewServer(s.HandleRoot())
res, err := http.Post(server.URL+"/foo?trigger_secret=s3cr3t", "application/json", nil)
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Fatalf("Got status %d, want: %d", res.StatusCode, http.StatusNotFound)
}
}
func TestGetBuildConfig(t *testing.T) {
tmpl, err := template.ParseFiles(pipelineConfigFilename)
if err != nil {
t.Error(err)
}
e := []EnvPair{EnvPair{Name: "FOO", Value: "bar"}}
env, _ := json.Marshal(e)
data := BuildConfigData{
Name: "repository-master",
TriggerSecret: "s3cr3t",
GitURI: "https://domain.com/proj/repository.git",
Branch: "master",
JenkinsfilePath: "foo/Jenkinsfile",
Env: string(env),
}
b, err := getBuildConfig(tmpl, data)
if err != nil {
t.Error(err)
}
configBytes, err := ioutil.ReadFile("test/golden/pipeline.json")
if err != nil {
t.Error(err)
}
actual := b.String()
expected := string(configBytes)
if actual != expected {
t.Errorf("Not the same, have: %s, want: %s", actual, expected)
}
}