-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain_test.go
381 lines (342 loc) · 16 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
package main
import (
"encoding/json"
"fmt"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type Payloads struct {
CheckSuiteEvent []byte
IssueCommentEvent []byte
WorkflowRunEvent []byte
PullRequestResponse []byte
CheckSuiteResponse []byte
MultipleCheckSuiteResponse []byte
MultipleWithEmptyCheckSuiteResponse []byte
SingleWithEmptyCheckSuiteResponse []byte
StatusResponse []byte
NewCommentResponse []byte
NoPipelinesComment []byte
HelpComment []byte
}
func getPayloads() (Payloads, error) {
payloads := Payloads{}
var err error
payloads.CheckSuiteEvent, err = ioutil.ReadFile("./testpayloads/check_suite_event.json")
if err != nil {
return Payloads{}, err
}
payloads.IssueCommentEvent, err = ioutil.ReadFile("./testpayloads/issue_comment_event.json")
if err != nil {
return Payloads{}, err
}
payloads.WorkflowRunEvent, err = ioutil.ReadFile("./testpayloads/workflow_run_event.json")
if err != nil {
return Payloads{}, err
}
payloads.PullRequestResponse, err = ioutil.ReadFile("./testpayloads/pull_request_response.json")
if err != nil {
return Payloads{}, err
}
payloads.CheckSuiteResponse, err = ioutil.ReadFile("./testpayloads/check_suite_response.json")
if err != nil {
return Payloads{}, err
}
payloads.MultipleCheckSuiteResponse, err = ioutil.ReadFile("./testpayloads/multiple_check_suite_response.json")
if err != nil {
return Payloads{}, err
}
payloads.MultipleWithEmptyCheckSuiteResponse, err = ioutil.ReadFile("./testpayloads/multiple_with_empty_check_suite_response.json")
if err != nil {
return Payloads{}, err
}
payloads.SingleWithEmptyCheckSuiteResponse, err = ioutil.ReadFile("./testpayloads/single_with_empty_check_suite_response.json")
if err != nil {
return Payloads{}, err
}
payloads.StatusResponse, err = ioutil.ReadFile("./testpayloads/status_response.json")
if err != nil {
return Payloads{}, err
}
payloads.StatusResponse, err = ioutil.ReadFile("./testpayloads/new_comment_response.json")
if err != nil {
return Payloads{}, err
}
payloads.NoPipelinesComment, err = ioutil.ReadFile("./comments/no_pipelines.txt")
if err != nil {
return Payloads{}, err
}
payloads.HelpComment, err = ioutil.ReadFile("./comments/help.txt")
if err != nil {
return Payloads{}, err
}
return payloads, nil
}
func getStatusBody(assert *assert.Assertions, req *http.Request) StatusBody {
body, err := ioutil.ReadAll(req.Body)
assert.NoError(err)
status := StatusBody{}
assert.NoError(json.Unmarshal(body, &status))
return status
}
type TestCheckSuiteCase struct {
Description string
AppTargets []string
InjectConclusion1 CheckSuiteConclusion
InjectConclusion2 CheckSuiteConclusion
ShouldPostStatus bool
ExpectedState CommitState
Event []byte
}
func NewCheckSuiteTestServer(
assert *assert.Assertions,
payloads Payloads,
conclusion1 CheckSuiteConclusion,
conclusion2 CheckSuiteConclusion,
postedState *CommitState,
postedStatus *bool,
description string,
) *httptest.Server {
checkSuite := NewCheckSuiteWebhook(payloads.CheckSuiteEvent)
assert.NotEmpty(checkSuite)
fn := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
response := []byte{}
if strings.Contains(checkSuite.GetCheckSuiteUrl(), req.URL.String()) && req.Method == "GET" {
assert.Contains(req.URL.Path, checkSuite.CheckSuite.HeadSha, description)
response = payloads.MultipleCheckSuiteResponse
response = []byte(strings.Replace(string(response),
`"conclusion": "neutral"`, fmt.Sprintf("\"conclusion\": \"%s\"", conclusion1), 1))
if conclusion2 != "" {
response = []byte(strings.Replace(string(response),
`"conclusion": "neutral"`, fmt.Sprintf("\"conclusion\": \"%s\"", conclusion2), 1))
}
} else if strings.Contains(checkSuite.GetStatusesUrl(), req.URL.String()) && req.Method == "POST" {
assert.Contains(req.URL.Path, checkSuite.CheckSuite.HeadSha)
status := getStatusBody(assert, req)
*postedState = status.State
*postedStatus = true
response = payloads.StatusResponse
} else {
assert.Fail("%s: Unexpected %s request to '%s'", description, req.Method, req.URL.String())
}
w.Write(response)
})
return httptest.NewServer(fn)
}
func TestCheckSuite(t *testing.T) {
assert := assert.New(t)
payloads, err := getPayloads()
assert.NoError(err)
var zeroCommitState CommitState
singleAppTarget := []string{"octocoders-linter"}
multiAppTargetExcludeEvent := []string{"Octocat App", "Hexacat App"}
multiAppTarget := []string{"octocoders-linter", "Octocat App", "Hexacat App"}
noMatchAppTarget := []string{"no-match"}
servers := []*httptest.Server{}
for i, tc := range []TestCheckSuiteCase{
{"POST pending for single suite unfinished", singleAppTarget, "", "", true, CommitStatePending,
[]byte(strings.ReplaceAll(string(payloads.CheckSuiteEvent), `"conclusion": "success"`, fmt.Sprintf("\"conclusion\": \"%s\"", CommitStatePending)))},
{"POST pending for single suite failure", singleAppTarget, "", "", true, CommitStatePending,
[]byte(strings.ReplaceAll(string(payloads.CheckSuiteEvent), `"conclusion": "success"`, fmt.Sprintf("\"conclusion\": \"%s\"", CommitStateFailure)))},
{"POST success for single suite", singleAppTarget, "", "", true, CommitStateSuccess, payloads.CheckSuiteEvent},
{"POST pending for no match, single suite", noMatchAppTarget, "", "", true, CommitStatePending, payloads.CheckSuiteEvent},
{"POST pending for no match, multiple suite", multiAppTargetExcludeEvent, CheckSuiteConclusionSuccess, CheckSuiteConclusionSuccess,
true, CommitStatePending, payloads.CheckSuiteEvent},
{"POST pending for multiple suites pending", multiAppTarget, CheckSuiteConclusionSuccess, CheckSuiteConclusionEmpty,
true, CommitStatePending, payloads.CheckSuiteEvent},
{"POST pending for multiple suites pending 2", multiAppTarget, CheckSuiteConclusionEmpty, CheckSuiteConclusionSuccess,
true, CommitStatePending, payloads.CheckSuiteEvent},
{"POST pending for multiple suites failure", multiAppTarget, CheckSuiteConclusionSuccess, CheckSuiteConclusionFailure,
true, CommitStatePending, payloads.CheckSuiteEvent},
{"POST success for multiple suites", multiAppTarget, CheckSuiteConclusionSuccess, CheckSuiteConclusionSuccess,
true, CommitStateSuccess, payloads.CheckSuiteEvent},
{"skip for main branch", singleAppTarget, CheckSuiteConclusionSuccess, "", false, zeroCommitState,
[]byte(strings.ReplaceAll(string(payloads.CheckSuiteEvent), `"head_branch": "changes"`, `"head_branch": "main"`))},
} {
var postedStatus bool
var postedState CommitState
server := NewCheckSuiteTestServer(assert, payloads, tc.InjectConclusion1, tc.InjectConclusion2, &postedState, &postedStatus, tc.Description)
gh, err := NewGithubClient(server.URL, "", tc.AppTargets...)
assert.NoError(err, tc.Description)
servers = append(servers, server)
defer servers[i].Close()
fmt.Println(fmt.Sprintf("\n\n========= %s =========", tc.Description))
err = handleEvent(gh, tc.Event)
assert.NoError(err, tc.Description)
assert.Equal(tc.ShouldPostStatus, postedStatus, tc.Description)
assert.Equal(tc.ExpectedState, postedState, tc.Description)
}
}
type TestCommentCase struct {
Description string
InputComment string
InjectConclusion CheckSuiteConclusion
ExpectedState CommitState
ShouldPostStatus bool
ShouldPostComment bool
ExpectedComment string
AppTargets []string
}
func NewCommentTestServer(
assert *assert.Assertions,
payloads Payloads,
inputComment string,
injectConclusion CheckSuiteConclusion,
expectedState CommitState,
postedStatus *bool,
postedComment *bool,
expectedComment string,
description string,
) *httptest.Server {
issueCommentEvent := NewIssueCommentWebhook(payloads.IssueCommentEvent)
assert.NotEmpty(issueCommentEvent)
pullRequestResponse := NewPullRequest(payloads.PullRequestResponse)
assert.NotEmpty(pullRequestResponse)
fn := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
response := []byte{}
if strings.Contains(issueCommentEvent.GetPullsUrl(), req.URL.String()) && req.Method == "GET" {
response = payloads.PullRequestResponse
} else if strings.Contains(pullRequestResponse.GetCheckSuiteUrl(), req.URL.String()) && req.Method == "GET" {
response = []byte(strings.ReplaceAll(
string(payloads.CheckSuiteResponse),
`"conclusion": "neutral"`,
fmt.Sprintf("\"conclusion\": \"%s\"", injectConclusion)))
} else if strings.Contains(pullRequestResponse.StatusesUrl, req.URL.String()) && req.Method == "POST" {
*postedStatus = true
response = payloads.StatusResponse
status := getStatusBody(assert, req)
assert.Equal(expectedState, status.State, description)
} else if strings.Contains(issueCommentEvent.GetCommentsUrl(), req.URL.String()) && req.Method == "POST" {
*postedComment = true
response = payloads.NewCommentResponse
body, err := ioutil.ReadAll(req.Body)
assert.NoError(err, description)
assert.Equal(expectedComment, string(body), "%s: Comment body for command '%s'", description, inputComment)
} else {
assert.Fail("%s: Unexpected %s request to '%s'", description, req.Method, req.URL.String())
}
w.Write(response)
})
return httptest.NewServer(fn)
}
func TestComments(t *testing.T) {
assert := assert.New(t)
payloads, err := getPayloads()
assert.NoError(err)
issueCommentEvent := NewIssueCommentWebhook(payloads.IssueCommentEvent)
assert.NotEmpty(issueCommentEvent)
pullRequestResponse := NewPullRequest(payloads.PullRequestResponse)
assert.NotEmpty(pullRequestResponse)
noPipelinesComment, err := NewIssueCommentBody(string(payloads.NoPipelinesComment))
assert.NoError(err)
helpComment, err := NewIssueCommentBody(string(payloads.HelpComment))
assert.NoError(err)
servers := []*httptest.Server{}
apps := []string{"Octocat App"}
noMatchAppTarget := []string{"no-match"}
cases := []TestCommentCase{
{"override+success", "/check-enforcer override", CheckSuiteConclusionSuccess, CommitStateSuccess, true, false, "", apps},
{"override+failure", "/check-enforcer override", CheckSuiteConclusionFailure, CommitStateSuccess, true, false, "", apps},
{"comment spaces", " /check-enforcer override ", CheckSuiteConclusionFailure, CommitStateSuccess, true, false, "", apps},
{"reset+success", "/check-enforcer reset", CheckSuiteConclusionSuccess, CommitStateSuccess, true, false, "", apps},
{"reset+failure", "/check-enforcer reset", CheckSuiteConclusionFailure, CommitStatePending, true, false, "", apps},
{"evaluate+success", "/check-enforcer evaluate", CheckSuiteConclusionSuccess, CommitStateSuccess, true, false, "", apps},
{"evaluate+failure", "/check-enforcer evaluate", CheckSuiteConclusionFailure, CommitStatePending, true, false, "", apps},
{"evaluate+timeout", "/check-enforcer evaluate", CheckSuiteConclusionTimedOut, CommitStatePending, true, false, "", apps},
{"evaluate+neutral", "/check-enforcer evaluate", CheckSuiteConclusionNeutral, CommitStatePending, true, false, "", apps},
{"evaluate+stale", "/check-enforcer evaluate", CheckSuiteConclusionStale, CommitStatePending, true, false, "", apps},
{"evaluate+nopipelinematches", "/check-enforcer evaluate", CheckSuiteConclusionSuccess, CommitStatePending, true, true, string(noPipelinesComment), noMatchAppTarget},
{"reset+nopipelinematches", "/check-enforcer reset", CheckSuiteConclusionSuccess, CommitStatePending, true, true, string(noPipelinesComment), noMatchAppTarget},
{"help", "/check-enforcer help", "", "", false, true, string(helpComment), apps},
{"missing space", "/check-enforcerevaluate", "", "", false, true, string(helpComment), apps},
{"invalid command", "/check-enforcer foobar", "", "", false, true, string(helpComment), apps},
{"invalid command+args", "/check-enforcer foobar bar bar", "", "", false, true, string(helpComment), apps},
{"different command", "/azp run", "", "", false, false, "", apps},
{"semicolons", ";;;;;;;;;;;;;;;;;;;;;;;;;;;", "", "", false, false, "", apps},
}
for i, tc := range cases {
var postedStatus bool
var postedComment bool
server := NewCommentTestServer(assert, payloads, tc.InputComment, tc.InjectConclusion, tc.ExpectedState,
&postedStatus, &postedComment, tc.ExpectedComment, tc.Description)
servers = append(servers, server)
defer servers[i].Close()
gh, err := NewGithubClient(server.URL, "", tc.AppTargets...)
assert.NoError(err, tc.Description)
replaced := strings.ReplaceAll(string(payloads.IssueCommentEvent), "You are totally right! I'll get this fixed right away.", tc.InputComment)
err = handleEvent(gh, []byte(replaced))
assert.NoError(err)
assert.Equal(tc.ShouldPostStatus, postedStatus, "%s: Should POST status for command '%s'", tc.Description, tc.InputComment)
assert.Equal(tc.ShouldPostComment, postedComment, "%s: Should POST comment for command '%s'", tc.Description, tc.InputComment)
}
}
type WorkflowRunCase struct {
Description string
Event []byte
CheckSuiteResponse []byte
ExpectedState CommitState
AppTargets []string
}
func NewWorkflowRunTestServer(
assert *assert.Assertions,
payloads Payloads,
checkSuiteResponse []byte,
postedState *CommitState,
description string,
) *httptest.Server {
workflowRun := NewWorkflowRunWebhook(payloads.WorkflowRunEvent)
assert.NotEmpty(workflowRun)
fn := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
response := []byte{}
if strings.Contains(workflowRun.WorkflowRun.GetCheckSuiteUrl(), req.URL.String()) && req.Method == "GET" {
response = checkSuiteResponse
} else if strings.Contains(workflowRun.WorkflowRun.GetStatusesUrl(), req.URL.String()) && req.Method == "POST" {
assert.Contains(req.URL.Path, workflowRun.WorkflowRun.HeadSha)
status := getStatusBody(assert, req)
*postedState = status.State
response = payloads.StatusResponse
} else {
assert.Fail("%s: Unexpected %s request to '%s'", description, req.Method, req.URL.String())
}
w.Write(response)
})
return httptest.NewServer(fn)
}
func TestWorkflowRun(t *testing.T) {
assert := assert.New(t)
payloads, err := getPayloads()
assert.NoError(err)
servers := []*httptest.Server{}
singleCheckSuiteResponse := []byte(strings.ReplaceAll(
string(payloads.CheckSuiteResponse), `"conclusion": "neutral"`, fmt.Sprintf("\"conclusion\": \"%s\"", CommitStateSuccess)))
multipleCheckSuiteResponse := []byte(strings.ReplaceAll(string(payloads.MultipleCheckSuiteResponse),
`"conclusion": "neutral"`, fmt.Sprintf("\"conclusion\": \"%s\"", CommitStateSuccess)))
multipleCheckSuiteResponsePending := []byte(strings.Replace(string(multipleCheckSuiteResponse),
fmt.Sprintf("\"conclusion\": \"%s\"", CommitStateSuccess), fmt.Sprintf("\"conclusion\": \"%s\"", CommitStatePending), 1))
for i, tc := range []WorkflowRunCase{
{"Workflow run success", payloads.WorkflowRunEvent, singleCheckSuiteResponse, CommitStateSuccess, []string{"Octocat App"}},
{"Workflow run multiple success", payloads.WorkflowRunEvent, multipleCheckSuiteResponse, CommitStateSuccess, []string{"Octocat App"}},
{"Workflow run multiple pending", payloads.WorkflowRunEvent, multipleCheckSuiteResponsePending, CommitStatePending, []string{"Octocat App"}},
{"Workflow run with empty check run suite", payloads.WorkflowRunEvent, payloads.MultipleWithEmptyCheckSuiteResponse,
CommitStateSuccess, []string{"GitHub Actions", "Azure Pipelines"}},
{"Workflow run single pending", payloads.WorkflowRunEvent, payloads.SingleWithEmptyCheckSuiteResponse,
CommitStatePending, []string{"Azure Pipelines"}},
{"Workflow run push event",
[]byte(strings.ReplaceAll(string(payloads.WorkflowRunEvent), `"event": "pull_request"`, `"event": "push"`)),
[]byte{}, "", []string{"Octocat App"}},
} {
var postedState CommitState
server := NewWorkflowRunTestServer(assert, payloads, tc.CheckSuiteResponse, &postedState, tc.Description)
gh, err := NewGithubClient(server.URL, "", tc.AppTargets...)
assert.NoError(err)
servers = append(servers, server)
defer servers[i].Close()
err = handleEvent(gh, tc.Event)
assert.NoError(err)
assert.Equal(tc.ExpectedState, postedState, tc.Description)
}
}