forked from google/go-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_test.go
More file actions
508 lines (428 loc) · 13 KB
/
github_test.go
File metadata and controls
508 lines (428 loc) · 13 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
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"time"
)
var (
// mux is the HTTP request multiplexer used with the test server.
mux *http.ServeMux
// client is the GitHub client being tested.
client *Client
// server is a test HTTP server used to provide mock API responses.
server *httptest.Server
)
// setup sets up a test HTTP server along with a github.Client that is
// configured to talk to that test server. Tests should register handlers on
// mux which provide mock responses for the API method being tested.
func setup() {
// test server
mux = http.NewServeMux()
server = httptest.NewServer(mux)
// github client configured to use test server
client = NewClient(nil)
client.BaseURL, _ = url.Parse(server.URL)
}
// teardown closes the test HTTP server.
func teardown() {
server.Close()
}
func testMethod(t *testing.T, r *http.Request, want string) {
if want != r.Method {
t.Errorf("Request method = %v, want %v", r.Method, want)
}
}
type values map[string]string
func testFormValues(t *testing.T, r *http.Request, values values) {
for key, want := range values {
if v := r.FormValue(key); v != want {
t.Errorf("Request parameter %v = %v, want %v", key, v, want)
}
}
}
func testHeader(t *testing.T, r *http.Request, header string, want string) {
if value := r.Header.Get(header); want != value {
t.Errorf("Header %s = %s, want: %s", header, value, want)
}
}
func testURLParseError(t *testing.T, err error) {
if err == nil {
t.Errorf("Expected error to be returned")
}
if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
t.Errorf("Expected URL parse error, got %+v", err)
}
}
func TestNewClient(t *testing.T) {
c := NewClient(nil)
if c.BaseURL.String() != defaultBaseURL {
t.Errorf("NewClient BaseURL = %v, want %v", c.BaseURL.String(), defaultBaseURL)
}
if c.UserAgent != userAgent {
t.Errorf("NewClient UserAgent = %v, want %v", c.UserAgent, userAgent)
}
}
func TestNewRequest(t *testing.T) {
c := NewClient(nil)
inURL, outURL := "/foo", defaultBaseURL+"foo"
inBody, outBody := &User{Login: "l"}, `{"login":"l"}`+"\n"
req, _ := c.NewRequest("GET", inURL, inBody)
// test that relative URL was expanded
if req.URL.String() != outURL {
t.Errorf("NewRequest(%v) URL = %v, want %v", inURL, req.URL, outURL)
}
// test that body was JSON encoded
body, _ := ioutil.ReadAll(req.Body)
if string(body) != outBody {
t.Errorf("NewRequest(%v) Body = %v, want %v", inBody, string(body), outBody)
}
// test that default user-agent is attached to the request
userAgent := req.Header.Get("User-Agent")
if c.UserAgent != userAgent {
t.Errorf("NewRequest() User-Agent = %v, want %v", userAgent, c.UserAgent)
}
}
func TestNewRequest_invalidJSON(t *testing.T) {
c := NewClient(nil)
type T struct {
A map[int]interface{}
}
_, err := c.NewRequest("GET", "/", &T{})
if err == nil {
t.Error("Expected error to be returned.")
}
if err, ok := err.(*json.UnsupportedTypeError); !ok {
t.Errorf("Expected a JSON error; got %#v.", err)
}
}
func TestNewRequest_badURL(t *testing.T) {
c := NewClient(nil)
_, err := c.NewRequest("GET", ":", nil)
testURLParseError(t, err)
}
func TestResponse_populatePageValues(t *testing.T) {
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?page=1>; rel="first",` +
` <https://api.github.com/?page=2>; rel="prev",` +
` <https://api.github.com/?page=4>; rel="next",` +
` <https://api.github.com/?page=5>; rel="last"`,
},
},
}
response := newResponse(&r)
if want, got := 1, response.FirstPage; want != got {
t.Errorf("response.FirstPage: %v, want %v", want, got)
}
if want, got := 2, response.PrevPage; want != got {
t.Errorf("response.PrevPage: %v, want %v", want, got)
}
if want, got := 4, response.NextPage; want != got {
t.Errorf("response.NextPage: %v, want %v", want, got)
}
if want, got := 5, response.LastPage; want != got {
t.Errorf("response.LastPage: %v, want %v", want, got)
}
}
func TestResponse_populatePageValues_invalid(t *testing.T) {
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?page=1>,` +
`<https://api.github.com/?page=abc>; rel="first",` +
`https://api.github.com/?page=2; rel="prev",` +
`<https://api.github.com/>; rel="next",` +
`<https://api.github.com/?page=>; rel="last"`,
},
},
}
response := newResponse(&r)
if want, got := 0, response.FirstPage; want != got {
t.Errorf("response.FirstPage: %v, want %v", want, got)
}
if want, got := 0, response.PrevPage; want != got {
t.Errorf("response.PrevPage: %v, want %v", want, got)
}
if want, got := 0, response.NextPage; want != got {
t.Errorf("response.NextPage: %v, want %v", want, got)
}
if want, got := 0, response.LastPage; want != got {
t.Errorf("response.LastPage: %v, want %v", want, got)
}
}
func TestDo(t *testing.T) {
setup()
defer teardown()
type foo struct {
A string
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if m := "GET"; m != r.Method {
t.Errorf("Request method = %v, want %v", r.Method, m)
}
fmt.Fprint(w, `{"A":"a"}`)
})
req, _ := client.NewRequest("GET", "/", nil)
body := new(foo)
client.Do(req, body)
want := &foo{"a"}
if !reflect.DeepEqual(body, want) {
t.Errorf("Response body = %v, want %v", body, want)
}
}
func TestDo_httpError(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Bad Request", 400)
})
req, _ := client.NewRequest("GET", "/", nil)
_, err := client.Do(req, nil)
if err == nil {
t.Error("Expected HTTP 400 error.")
}
}
// Test handling of an error caused by the internal http client's Do()
// function. A redirect loop is pretty unlikely to occur within the GitHub
// API, but does allow us to exercise the right code path.
func TestDo_redirectLoop(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
})
req, _ := client.NewRequest("GET", "/", nil)
_, err := client.Do(req, nil)
if err == nil {
t.Error("Expected error to be returned.")
}
if err, ok := err.(*url.Error); !ok {
t.Errorf("Expected a URL error; got %#v.", err)
}
}
func TestDo_rateLimit(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(headerRateLimit, "60")
w.Header().Add(headerRateRemaining, "59")
w.Header().Add(headerRateReset, "1372700873")
})
var want int
if want = 0; client.Rate.Limit != want {
t.Errorf("Client rate limit = %v, want %v", client.Rate.Limit, want)
}
if want = 0; client.Rate.Limit != want {
t.Errorf("Client rate remaining = %v, got %v", client.Rate.Remaining, want)
}
if !client.Rate.Reset.IsZero() {
t.Errorf("Client rate reset not initialized to zero value")
}
req, _ := client.NewRequest("GET", "/", nil)
client.Do(req, nil)
if want = 60; client.Rate.Limit != want {
t.Errorf("Client rate limit = %v, want %v", client.Rate.Limit, want)
}
if want = 59; client.Rate.Remaining != want {
t.Errorf("Client rate remaining = %v, want %v", client.Rate.Remaining, want)
}
reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC)
if client.Rate.Reset.UTC() != reset {
t.Errorf("Client rate reset = %v, want %v", client.Rate.Reset, reset)
}
}
func TestDo_rateLimit_errorResponse(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(headerRateLimit, "60")
w.Header().Add(headerRateRemaining, "59")
w.Header().Add(headerRateReset, "1372700873")
http.Error(w, "Bad Request", 400)
})
var want int
req, _ := client.NewRequest("GET", "/", nil)
client.Do(req, nil)
if want = 60; client.Rate.Limit != want {
t.Errorf("Client rate limit = %v, want %v", client.Rate.Limit, want)
}
if want = 59; client.Rate.Remaining != want {
t.Errorf("Client rate remaining = %v, want %v", client.Rate.Remaining, want)
}
reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC)
if client.Rate.Reset.UTC() != reset {
t.Errorf("Client rate reset = %v, want %v", client.Rate.Reset, reset)
}
}
func TestCheckResponse(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader(`{"message":"m",
"errors": [{"resource": "r", "field": "f", "code": "c"}]}`)),
}
err := CheckResponse(res).(*ErrorResponse)
if err == nil {
t.Errorf("Expected error response.")
}
want := &ErrorResponse{
Response: res,
Message: "m",
Errors: []Error{Error{Resource: "r", Field: "f", Code: "c"}},
}
if !reflect.DeepEqual(err, want) {
t.Errorf("Error = %#v, want %#v", err, want)
}
}
// ensure that we properly handle API errors that do not contain a response
// body
func TestCheckResponse_noBody(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader("")),
}
err := CheckResponse(res).(*ErrorResponse)
if err == nil {
t.Errorf("Expected error response.")
}
want := &ErrorResponse{
Response: res,
}
if !reflect.DeepEqual(err, want) {
t.Errorf("Error = %#v, want %#v", err, want)
}
}
func TestParseBooleanResponse_true(t *testing.T) {
result, err := parseBoolResponse(nil)
if err != nil {
t.Errorf("parseBoolResponse returned error: %+v", err)
}
if want := true; result != want {
t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
}
}
func TestParseBooleanResponse_false(t *testing.T) {
v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusNotFound}}
result, err := parseBoolResponse(v)
if err != nil {
t.Errorf("parseBoolResponse returned error: %+v", err)
}
if want := false; result != want {
t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
}
}
func TestParseBooleanResponse_error(t *testing.T) {
v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusBadRequest}}
result, err := parseBoolResponse(v)
if err == nil {
t.Errorf("Expected error to be returned.")
}
if want := false; result != want {
t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
}
}
func TestErrorResponse_Error(t *testing.T) {
res := &http.Response{Request: &http.Request{}}
err := ErrorResponse{Message: "m", Response: res}
if err.Error() == "" {
t.Errorf("Expected non-empty ErrorResponse.Error()")
}
}
func TestError_Error(t *testing.T) {
err := Error{}
if err.Error() == "" {
t.Errorf("Expected non-empty Error.Error()")
}
}
func TestRateLimit(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/rate_limit", func(w http.ResponseWriter, r *http.Request) {
if m := "GET"; m != r.Method {
t.Errorf("Request method = %v, want %v", r.Method, m)
}
fmt.Fprint(w, `{"rate":{"limit":2,"remaining":1,"reset":1372700873}}`)
})
rate, _, err := client.RateLimit()
if err != nil {
t.Errorf("Rate limit returned error: %v", err)
}
want := &Rate{
Limit: 2,
Remaining: 1,
Reset: time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC).Local(),
}
if !reflect.DeepEqual(rate, want) {
t.Errorf("RateLimit returned %+v, want %+v", rate, want)
}
}
func TestUnauthenticatedRateLimitedTransport(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var v, want string
q := r.URL.Query()
if v, want = q.Get("client_id"), "id"; v != want {
t.Errorf("OAuth Client ID = %v, want %v", v, want)
}
if v, want = q.Get("client_secret"), "secret"; v != want {
t.Errorf("OAuth Client Secret = %v, want %v", v, want)
}
})
tp := &UnauthenticatedRateLimitedTransport{
ClientID: "id",
ClientSecret: "secret",
}
unauthedClient := NewClient(tp.Client())
unauthedClient.BaseURL = client.BaseURL
req, _ := unauthedClient.NewRequest("GET", "/", nil)
unauthedClient.Do(req, nil)
}
func TestUnauthenticatedRateLimitedTransport_missingFields(t *testing.T) {
// missing ClientID
tp := &UnauthenticatedRateLimitedTransport{
ClientSecret: "secret",
}
_, err := tp.RoundTrip(nil)
if err == nil {
t.Errorf("Expected error to be returned")
}
// missing ClientSecret
tp = &UnauthenticatedRateLimitedTransport{
ClientID: "id",
}
_, err = tp.RoundTrip(nil)
if err == nil {
t.Errorf("Expected error to be returned")
}
}
func TestUnauthenticatedRateLimitedTransport_transport(t *testing.T) {
// default transport
tp := &UnauthenticatedRateLimitedTransport{
ClientID: "id",
ClientSecret: "secret",
}
if tp.transport() != http.DefaultTransport {
t.Errorf("Expected http.DefaultTransport to be used.")
}
// custom transport
tp = &UnauthenticatedRateLimitedTransport{
ClientID: "id",
ClientSecret: "secret",
Transport: &http.Transport{},
}
if tp.transport() == http.DefaultTransport {
t.Errorf("Expected custom transport to be used.")
}
}