forked from tektoncd/pipeline
/
fake_github.go
299 lines (256 loc) · 8 KB
/
fake_github.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
/*
Copyright 2019 The Tekton Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/google/go-github/github"
"github.com/gorilla/mux"
)
const (
// ErrorKeyword is a magic const used to denote PRs/Comments that should
// return errors to the client to simulate issues communicating with GitHub.
ErrorKeyword = "~~ERROR~~"
)
// key defines keys for associating data to PRs/issues in the fake server.
type key struct {
owner string
repo string
id int64
}
// FakeGitHub is a fake GitHub server for use in tests.
type FakeGitHub struct {
*mux.Router
pr map[key]*github.PullRequest
// GitHub references comments in 2 ways:
// 1) List by issue (PR) ID.
// 2) Get by comment ID.
// We need to store references to both to emulate the API properly.
prComments map[key][]*github.IssueComment
comments map[key]*github.IssueComment
status map[statusKey]map[string]*github.RepoStatus
}
// NewFakeGitHub returns a new FakeGitHub.
func NewFakeGitHub() *FakeGitHub {
s := &FakeGitHub{
Router: mux.NewRouter(),
pr: make(map[key]*github.PullRequest),
prComments: make(map[key][]*github.IssueComment),
comments: make(map[key]*github.IssueComment),
status: make(map[statusKey]map[string]*github.RepoStatus),
}
s.HandleFunc("/repos/{owner}/{repo}/pulls/{number}", s.getPullRequest).Methods(http.MethodGet)
s.HandleFunc("/repos/{owner}/{repo}/issues/{number}/comments", s.getComments).Methods(http.MethodGet)
s.HandleFunc("/repos/{owner}/{repo}/issues/{number}/comments", s.createComment).Methods(http.MethodPost)
s.HandleFunc("/repos/{owner}/{repo}/issues/comments/{number}", s.updateComment).Methods(http.MethodPatch)
s.HandleFunc("/repos/{owner}/{repo}/issues/comments/{number}", s.deleteComment).Methods(http.MethodDelete)
s.HandleFunc("/repos/{owner}/{repo}/issues/{number}/labels", s.updateLabels).Methods(http.MethodPut)
s.HandleFunc("/repos/{owner}/{repo}/statuses/{revision}", s.createStatus).Methods(http.MethodPost)
s.HandleFunc("/repos/{owner}/{repo}/commits/{revision}/status", s.getStatuses).Methods(http.MethodGet)
return s
}
func prKey(r *http.Request) (key, error) {
pr, err := strconv.ParseInt(mux.Vars(r)["number"], 10, 64)
if err != nil {
return key{}, err
}
return key{
owner: mux.Vars(r)["owner"],
repo: mux.Vars(r)["repo"],
id: pr,
}, nil
}
// AddPullRequest adds the given pull request to the fake GitHub server.
// This is done as a convenience over implementing PullReqests.Create in the
// GitHub server since that method takes in a different type (NewPullRequest).
func (g *FakeGitHub) AddPullRequest(pr *github.PullRequest) {
key := key{
owner: pr.GetBase().GetUser().GetLogin(),
repo: pr.GetBase().GetRepo().GetName(),
id: pr.GetID(),
}
g.pr[key] = pr
}
func (g *FakeGitHub) getPullRequest(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pr, ok := g.pr[key]
if !ok {
http.Error(w, fmt.Sprintf("%v not found", key), http.StatusNotFound)
return
}
if err := json.NewEncoder(w).Encode(pr); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (g *FakeGitHub) getComments(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
comments, ok := g.prComments[key]
if !ok {
comments = []*github.IssueComment{}
}
if err := json.NewEncoder(w).Encode(comments); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (g *FakeGitHub) createComment(w http.ResponseWriter, r *http.Request) {
prKey, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
c := new(github.IssueComment)
if err := json.NewDecoder(r.Body).Decode(c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if strings.Contains(c.GetBody(), ErrorKeyword) {
http.Error(w, "intentional error", http.StatusInternalServerError)
return
}
c.ID = github.Int64(int64(len(g.comments) + 1))
if _, ok := g.prComments[prKey]; !ok {
g.prComments[prKey] = []*github.IssueComment{}
}
g.prComments[prKey] = append(g.prComments[prKey], c)
commentKey := key{
owner: prKey.owner,
repo: prKey.repo,
id: c.GetID(),
}
g.comments[commentKey] = c
if err := json.NewEncoder(w).Encode(c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (g *FakeGitHub) updateComment(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
update := new(github.IssueComment)
if err := json.NewDecoder(r.Body).Decode(update); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if strings.Contains(update.GetBody(), ErrorKeyword) {
http.Error(w, "intentional error", http.StatusInternalServerError)
return
}
existing, ok := g.comments[key]
if !ok {
http.Error(w, fmt.Sprintf("comment %+v not found", key), http.StatusNotFound)
return
}
*existing = *update
w.WriteHeader(http.StatusOK)
}
func (g *FakeGitHub) deleteComment(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if _, ok := g.comments[key]; !ok {
http.Error(w, fmt.Sprintf("comment %+v not found", key), http.StatusNotFound)
return
}
// Remove comment from PR storage. Not particularly efficient, but we don't
// generally expect this to be used for large number of comments in unit
// tests.
for k := range g.prComments {
for i, c := range g.prComments[k] {
if c.GetID() == key.id {
g.prComments[k] = append(g.prComments[k][:i], g.prComments[k][i+1:]...)
break
}
}
}
delete(g.comments, key)
w.WriteHeader(http.StatusOK)
}
func (g *FakeGitHub) updateLabels(w http.ResponseWriter, r *http.Request) {
key, err := prKey(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
pr, ok := g.pr[key]
if !ok {
http.Error(w, "pull request not found", http.StatusNotFound)
return
}
payload := []string{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pr.Labels = make([]*github.Label, 0, len(payload))
for _, l := range payload {
pr.Labels = append(pr.Labels, &github.Label{
Name: github.String(l),
})
}
w.WriteHeader(http.StatusOK)
}
type statusKey struct {
owner string
repo string
revision string
}
func getStatusKey(r *http.Request) statusKey {
return statusKey{
owner: mux.Vars(r)["owner"],
repo: mux.Vars(r)["repo"],
revision: mux.Vars(r)["revision"],
}
}
func (g *FakeGitHub) createStatus(w http.ResponseWriter, r *http.Request) {
k := getStatusKey(r)
rs := new(github.RepoStatus)
if err := json.NewDecoder(r.Body).Decode(rs); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, ok := g.status[k]; !ok {
g.status[k] = make(map[string]*github.RepoStatus)
}
g.status[k][rs.GetContext()] = rs
}
func (g *FakeGitHub) getStatuses(w http.ResponseWriter, r *http.Request) {
k := getStatusKey(r)
s := make([]github.RepoStatus, 0, len(g.status[k]))
for _, v := range g.status[k] {
s = append(s, *v)
}
cs := &github.CombinedStatus{
TotalCount: github.Int(len(s)),
Statuses: s,
}
if err := json.NewEncoder(w).Encode(cs); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}