Debian Codegraph @

github/github_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2013 The go-github AUTHORS. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package github
7
8 import (
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "net/http"
15 "net/http/httptest"
16 "net/url"
17 "os"
18 "path"
19 "reflect"
20 "strconv"
21 "strings"
22 "testing"
23 "time"
24
25 "github.com/google/go-cmp/cmp"
26 )
27
28 const (
29 // baseURLPath is a non-empty Client.BaseURL path to use during tests,
30 // to ensure relative URLs are used for all endpoints. See issue #752.
31 baseURLPath = "/api-v3"
32 )
33
34 // setup sets up a test HTTP server along with a github.Client that is
35 // configured to talk to that test server. Tests should register handlers on
36 // mux which provide mock responses for the API method being tested.
37 func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {
38 // mux is the HTTP request multiplexer used with the test server.
39 mux = http.NewServeMux()
40
41 // We want to ensure that tests catch mistakes where the endpoint URL is
42 // specified as absolute rather than relative. It only makes a difference
43 // when there's a non-empty base URL path. So, use that. See issue #752.
44 apiHandler := http.NewServeMux()
45 apiHandler.Handle(baseURLPath+"/", http.StripPrefix(baseURLPath, mux))
46 apiHandler.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
47 fmt.Fprintln(os.Stderr, "FAIL: Client.BaseURL path prefix is not preserved in the request URL:")
48 fmt.Fprintln(os.Stderr)
49 fmt.Fprintln(os.Stderr, "\t"+req.URL.String())
50 fmt.Fprintln(os.Stderr)
51 fmt.Fprintln(os.Stderr, "\tDid you accidentally use an absolute endpoint URL rather than relative?")
52 fmt.Fprintln(os.Stderr, "\tSee https://github.com/google/go-github/issues/752 for information.")
53 http.Error(w, "Client.BaseURL path prefix is not preserved in the request URL.", http.StatusInternalServerError)
54 })
55
56 // server is a test HTTP server used to provide mock API responses.
57 server := httptest.NewServer(apiHandler)
58
59 // client is the GitHub client being tested and is
60 // configured to use test server.
61 client = NewClient(nil)
62 url, _ := url.Parse(server.URL + baseURLPath + "/")
63 client.BaseURL = url
64 client.UploadURL = url
65
66 return client, mux, server.URL, server.Close
67 }
68
69 // openTestFile creates a new file with the given name and content for testing.
70 // In order to ensure the exact file name, this function will create a new temp
71 // directory, and create the file in that directory. It is the caller's
72 // responsibility to remove the directory and its contents when no longer needed.
73 func openTestFile(name, content string) (file *os.File, dir string, err error) {
74 dir, err = os.MkdirTemp("", "go-github")
75 if err != nil {
76 return nil, dir, err
77 }
78
79 file, err = os.OpenFile(path.Join(dir, name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
80 if err != nil {
81 return nil, dir, err
82 }
83
84 fmt.Fprint(file, content)
85
86 // close and re-open the file to keep file.Stat() happy
87 file.Close()
88 file, err = os.Open(file.Name())
89 if err != nil {
90 return nil, dir, err
91 }
92
93 return file, dir, err
94 }
95
96 func testMethod(t *testing.T, r *http.Request, want string) {
97 t.Helper()
98 if got := r.Method; got != want {
99 t.Errorf("Request method: %v, want %v", got, want)
100 }
101 }
102
103 type values map[string]string
104
105 func testFormValues(t *testing.T, r *http.Request, values values) {
106 t.Helper()
107 want := url.Values{}
108 for k, v := range values {
109 want.Set(k, v)
110 }
111
112 assertNilError(t, r.ParseForm())
113 if got := r.Form; !cmp.Equal(got, want) {
114 t.Errorf("Request parameters: %v, want %v", got, want)
115 }
116 }
117
118 func testHeader(t *testing.T, r *http.Request, header string, want string) {
119 t.Helper()
120 if got := r.Header.Get(header); got != want {
121 t.Errorf("Header.Get(%q) returned %q, want %q", header, got, want)
122 }
123 }
124
125 func testURLParseError(t *testing.T, err error) {
126 t.Helper()
127 if err == nil {
128 t.Errorf("Expected error to be returned")
129 }
130 if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
131 t.Errorf("Expected URL parse error, got %+v", err)
132 }
133 }
134
135 func testBody(t *testing.T, r *http.Request, want string) {
136 t.Helper()
137 b, err := io.ReadAll(r.Body)
138 if err != nil {
139 t.Errorf("Error reading request body: %v", err)
140 }
141 if got := string(b); got != want {
142 t.Errorf("request Body is %s, want %s", got, want)
143 }
144 }
145
146 // Test whether the marshaling of v produces JSON that corresponds
147 // to the want string.
148 func testJSONMarshal(t *testing.T, v interface{}, want string) {
149 t.Helper()
150 // Unmarshal the wanted JSON, to verify its correctness, and marshal it back
151 // to sort the keys.
152 u := reflect.New(reflect.TypeOf(v)).Interface()
153 if err := json.Unmarshal([]byte(want), &u); err != nil {
154 t.Errorf("Unable to unmarshal JSON for %v: %v", want, err)
155 }
156 w, err := json.MarshalIndent(u, "", " ")
157 if err != nil {
158 t.Errorf("Unable to marshal JSON for %#v", u)
159 }
160
161 // Marshal the target value.
162 got, err := json.MarshalIndent(v, "", " ")
163 if err != nil {
164 t.Errorf("Unable to marshal JSON for %#v", v)
165 }
166
167 if diff := cmp.Diff(string(w), string(got)); diff != "" {
168 t.Errorf("json.Marshal returned:\n%s\nwant:\n%s\ndiff:\n%v", got, w, diff)
169 }
170 }
171
172 // Test whether the v fields have the url tag and the parsing of v
173 // produces query parameters that corresponds to the want string.
174 func testAddURLOptions(t *testing.T, url string, v interface{}, want string) {
175 t.Helper()
176
177 vt := reflect.Indirect(reflect.ValueOf(v)).Type()
178 for i := 0; i < vt.NumField(); i++ {
179 field := vt.Field(i)
180 if alias, ok := field.Tag.Lookup("url"); ok {
181 if alias == "" {
182 t.Errorf("The field %+v has a blank url tag", field)
183 }
184 } else {
185 t.Errorf("The field %+v has no url tag specified", field)
186 }
187 }
188
189 got, err := addOptions(url, v)
190 if err != nil {
191 t.Errorf("Unable to add %#v as query parameters", v)
192 }
193
194 if got != want {
195 t.Errorf("addOptions(%q, %#v) returned %v, want %v", url, v, got, want)
196 }
197 }
198
199 // Test how bad options are handled. Method f under test should
200 // return an error.
201 func testBadOptions(t *testing.T, methodName string, f func() error) {
202 t.Helper()
203 if methodName == "" {
204 t.Error("testBadOptions: must supply method methodName")
205 }
206 if err := f(); err == nil {
207 t.Errorf("bad options %v err = nil, want error", methodName)
208 }
209 }
210
211 // Test function under NewRequest failure and then s.client.Do failure.
212 // Method f should be a regular call that would normally succeed, but
213 // should return an error when NewRequest or s.client.Do fails.
214 func testNewRequestAndDoFailure(t *testing.T, methodName string, client *Client, f func() (*Response, error)) {
215 testNewRequestAndDoFailureCategory(t, methodName, client, coreCategory, f)
216 }
217
218 // testNewRequestAndDoFailureCategory works Like testNewRequestAndDoFailure, but allows setting the category
219 func testNewRequestAndDoFailureCategory(t *testing.T, methodName string, client *Client, category rateLimitCategory, f func() (*Response, error)) {
220 t.Helper()
221 if methodName == "" {
222 t.Error("testNewRequestAndDoFailure: must supply method methodName")
223 }
224
225 client.BaseURL.Path = ""
226 resp, err := f()
227 if resp != nil {
228 t.Errorf("client.BaseURL.Path='' %v resp = %#v, want nil", methodName, resp)
229 }
230 if err == nil {
231 t.Errorf("client.BaseURL.Path='' %v err = nil, want error", methodName)
232 }
233
234 client.BaseURL.Path = "/api-v3/"
235 client.rateLimits[category].Reset.Time = time.Now().Add(10 * time.Minute)
236 resp, err = f()
237 if bypass := resp.Request.Context().Value(bypassRateLimitCheck); bypass != nil {
238 return
239 }
240 if want := http.StatusForbidden; resp == nil || resp.Response.StatusCode != want {
241 if resp != nil {
242 t.Errorf("rate.Reset.Time > now %v resp = %#v, want StatusCode=%v", methodName, resp.Response, want)
243 } else {
244 t.Errorf("rate.Reset.Time > now %v resp = nil, want StatusCode=%v", methodName, want)
245 }
246 }
247 if err == nil {
248 t.Errorf("rate.Reset.Time > now %v err = nil, want error", methodName)
249 }
250 }
251
252 // Test that all error response types contain the status code.
253 func testErrorResponseForStatusCode(t *testing.T, code int) {
254 t.Helper()
255 client, mux, _, teardown := setup()
256 defer teardown()
257
258 mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) {
259 testMethod(t, r, "GET")
260 w.WriteHeader(code)
261 })
262
263 ctx := context.Background()
264 _, _, err := client.Repositories.ListHooks(ctx, "o", "r", nil)
265
266 switch e := err.(type) {
267 case *ErrorResponse:
268 case *RateLimitError:
269 case *AbuseRateLimitError:
270 if code != e.Response.StatusCode {
271 t.Error("Error response does not contain status code")
272 }
273 default:
274 t.Error("Unknown error response type")
275 }
276 }
277
278 func assertNoDiff(t *testing.T, want, got interface{}) {
279 t.Helper()
280 if diff := cmp.Diff(want, got); diff != "" {
281 t.Errorf("diff mismatch (-want +got):\n%v", diff)
282 }
283 }
284
285 func assertNilError(t *testing.T, err error) {
286 t.Helper()
287 if err != nil {
288 t.Errorf("unexpected error: %v", err)
289 }
290 }
291
292 func assertWrite(t *testing.T, w io.Writer, data []byte) {
293 t.Helper()
294 _, err := w.Write(data)
295 assertNilError(t, err)
296 }
297
298 func TestNewClient(t *testing.T) {
299 c := NewClient(nil)
300
301 if got, want := c.BaseURL.String(), defaultBaseURL; got != want {
302 t.Errorf("NewClient BaseURL is %v, want %v", got, want)
303 }
304 if got, want := c.UserAgent, defaultUserAgent; got != want {
305 t.Errorf("NewClient UserAgent is %v, want %v", got, want)
306 }
307
308 c2 := NewClient(nil)
309 if c.client == c2.client {
310 t.Error("NewClient returned same http.Clients, but they should differ")
311 }
312 }
313
314 func TestNewClientWithEnvProxy(t *testing.T) {
315 client := NewClientWithEnvProxy()
316 if got, want := client.BaseURL.String(), defaultBaseURL; got != want {
317 t.Errorf("NewClient BaseURL is %v, want %v", got, want)
318 }
319 }
320
321 func TestClient(t *testing.T) {
322 c := NewClient(nil)
323 c2 := c.Client()
324 if c.client == c2 {
325 t.Error("Client returned same http.Client, but should be different")
326 }
327 }
328
329 func TestWithAuthToken(t *testing.T) {
330 token := "gh_test_token"
331
332 validate := func(t *testing.T, c *http.Client, token string) {
333 t.Helper()
334 want := token
335 if want != "" {
336 want = "Bearer " + want
337 }
338 gotReq := false
339 headerVal := ""
340 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
341 gotReq = true
342 headerVal = r.Header.Get("Authorization")
343 }))
344 _, err := c.Get(srv.URL)
345 assertNilError(t, err)
346 if !gotReq {
347 t.Error("request not sent")
348 }
349 if headerVal != want {
350 t.Errorf("Authorization header is %v, want %v", headerVal, want)
351 }
352 }
353
354 t.Run("zero-value Client", func(t *testing.T) {
355 c := new(Client).WithAuthToken(token)
356 validate(t, c.Client(), token)
357 })
358
359 t.Run("NewClient", func(t *testing.T) {
360 httpClient := &http.Client{}
361 client := NewClient(httpClient).WithAuthToken(token)
362 validate(t, client.Client(), token)
363 // make sure the original client isn't setting auth headers now
364 validate(t, httpClient, "")
365 })
366
367 t.Run("NewTokenClient", func(t *testing.T) {
368 validate(t, NewTokenClient(context.Background(), token).Client(), token)
369 })
370 }
371
372 func TestWithEnterpriseURLs(t *testing.T) {
373 for _, test := range []struct {
374 name string
375 baseURL string
376 wantBaseURL string
377 uploadURL string
378 wantUploadURL string
379 wantErr string
380 }{
381 {
382 name: "does not modify properly formed URLs",
383 baseURL: "https://custom-url/api/v3/",
384 wantBaseURL: "https://custom-url/api/v3/",
385 uploadURL: "https://custom-upload-url/api/uploads/",
386 wantUploadURL: "https://custom-upload-url/api/uploads/",
387 },
388 {
389 name: "adds trailing slash",
390 baseURL: "https://custom-url/api/v3",
391 wantBaseURL: "https://custom-url/api/v3/",
392 uploadURL: "https://custom-upload-url/api/uploads",
393 wantUploadURL: "https://custom-upload-url/api/uploads/",
394 },
395 {
396 name: "adds enterprise suffix",
397 baseURL: "https://custom-url/",
398 wantBaseURL: "https://custom-url/api/v3/",
399 uploadURL: "https://custom-upload-url/",
400 wantUploadURL: "https://custom-upload-url/api/uploads/",
401 },
402 {
403 name: "adds enterprise suffix and trailing slash",
404 baseURL: "https://custom-url",
405 wantBaseURL: "https://custom-url/api/v3/",
406 uploadURL: "https://custom-upload-url",
407 wantUploadURL: "https://custom-upload-url/api/uploads/",
408 },
409 {
410 name: "bad base URL",
411 baseURL: "bogus\nbase\nURL",
412 uploadURL: "https://custom-upload-url/api/uploads/",
413 wantErr: `invalid control character in URL`,
414 },
415 {
416 name: "bad upload URL",
417 baseURL: "https://custom-url/api/v3/",
418 uploadURL: "bogus\nupload\nURL",
419 wantErr: `invalid control character in URL`,
420 },
421 {
422 name: "URL has existing API prefix, adds trailing slash",
423 baseURL: "https://api.custom-url",
424 wantBaseURL: "https://api.custom-url/",
425 uploadURL: "https://api.custom-upload-url",
426 wantUploadURL: "https://api.custom-upload-url/",
427 },
428 {
429 name: "URL has existing API prefix and trailing slash",
430 baseURL: "https://api.custom-url/",
431 wantBaseURL: "https://api.custom-url/",
432 uploadURL: "https://api.custom-upload-url/",
433 wantUploadURL: "https://api.custom-upload-url/",
434 },
435 {
436 name: "URL has API subdomain, adds trailing slash",
437 baseURL: "https://catalog.api.custom-url",
438 wantBaseURL: "https://catalog.api.custom-url/",
439 uploadURL: "https://catalog.api.custom-upload-url",
440 wantUploadURL: "https://catalog.api.custom-upload-url/",
441 },
442 {
443 name: "URL has API subdomain and trailing slash",
444 baseURL: "https://catalog.api.custom-url/",
445 wantBaseURL: "https://catalog.api.custom-url/",
446 uploadURL: "https://catalog.api.custom-upload-url/",
447 wantUploadURL: "https://catalog.api.custom-upload-url/",
448 },
449 {
450 name: "URL is not a proper API subdomain, adds enterprise suffix and slash",
451 baseURL: "https://cloud-api.custom-url",
452 wantBaseURL: "https://cloud-api.custom-url/api/v3/",
453 uploadURL: "https://cloud-api.custom-upload-url",
454 wantUploadURL: "https://cloud-api.custom-upload-url/api/uploads/",
455 },
456 {
457 name: "URL is not a proper API subdomain, adds enterprise suffix",
458 baseURL: "https://cloud-api.custom-url/",
459 wantBaseURL: "https://cloud-api.custom-url/api/v3/",
460 uploadURL: "https://cloud-api.custom-upload-url/",
461 wantUploadURL: "https://cloud-api.custom-upload-url/api/uploads/",
462 },
463 } {
464 t.Run(test.name, func(t *testing.T) {
465 validate := func(c *Client, err error) {
466 t.Helper()
467 if test.wantErr != "" {
468 if err == nil || !strings.Contains(err.Error(), test.wantErr) {
469 t.Fatalf("error does not contain expected string %q: %v", test.wantErr, err)
470 }
471 return
472 }
473 if err != nil {
474 t.Fatalf("got unexpected error: %v", err)
475 }
476 if c.BaseURL.String() != test.wantBaseURL {
477 t.Errorf("BaseURL is %v, want %v", c.BaseURL.String(), test.wantBaseURL)
478 }
479 if c.UploadURL.String() != test.wantUploadURL {
480 t.Errorf("UploadURL is %v, want %v", c.UploadURL.String(), test.wantUploadURL)
481 }
482 }
483 validate(NewClient(nil).WithEnterpriseURLs(test.baseURL, test.uploadURL))
484 validate(new(Client).WithEnterpriseURLs(test.baseURL, test.uploadURL))
485 validate(NewEnterpriseClient(test.baseURL, test.uploadURL, nil))
486 })
487 }
488 }
489
490 // Ensure that length of Client.rateLimits is the same as number of fields in RateLimits struct.
491 func TestClient_rateLimits(t *testing.T) {
492 if got, want := len(Client{}.rateLimits), reflect.TypeOf(RateLimits{}).NumField(); got != want {
493 t.Errorf("len(Client{}.rateLimits) is %v, want %v", got, want)
494 }
495 }
496
497 func TestNewRequest(t *testing.T) {
498 c := NewClient(nil)
499
500 inURL, outURL := "/foo", defaultBaseURL+"foo"
501 inBody, outBody := &User{Login: String("l")}, `{"login":"l"}`+"\n"
502 req, _ := c.NewRequest("GET", inURL, inBody)
503
504 // test that relative URL was expanded
505 if got, want := req.URL.String(), outURL; got != want {
506 t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want)
507 }
508
509 // test that body was JSON encoded
510 body, _ := io.ReadAll(req.Body)
511 if got, want := string(body), outBody; got != want {
512 t.Errorf("NewRequest(%q) Body is %v, want %v", inBody, got, want)
513 }
514
515 userAgent := req.Header.Get("User-Agent")
516
517 // test that default user-agent is attached to the request
518 if got, want := userAgent, c.UserAgent; got != want {
519 t.Errorf("NewRequest() User-Agent is %v, want %v", got, want)
520 }
521
522 if !strings.Contains(userAgent, Version) {
523 t.Errorf("NewRequest() User-Agent should contain %v, found %v", Version, userAgent)
524 }
525
526 apiVersion := req.Header.Get(headerAPIVersion)
527 if got, want := apiVersion, defaultAPIVersion; got != want {
528 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
529 }
530
531 req, _ = c.NewRequest("GET", inURL, inBody, WithVersion("2022-11-29"))
532 apiVersion = req.Header.Get(headerAPIVersion)
533 if got, want := apiVersion, "2022-11-29"; got != want {
534 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
535 }
536 }
537
538 func TestNewRequest_invalidJSON(t *testing.T) {
539 c := NewClient(nil)
540
541 type T struct {
•542 F func()
543 }
544 _, err := c.NewRequest("GET", ".", &T{})
545
546 if err == nil {
547 t.Error("Expected error to be returned.")
548 }
549 }
550
551 func TestNewRequest_badURL(t *testing.T) {
552 c := NewClient(nil)
553 _, err := c.NewRequest("GET", ":", nil)
554 testURLParseError(t, err)
555 }
556
557 func TestNewRequest_badMethod(t *testing.T) {
558 c := NewClient(nil)
559 if _, err := c.NewRequest("BOGUS\nMETHOD", ".", nil); err == nil {
560 t.Fatal("NewRequest returned nil; expected error")
561 }
562 }
563
564 // ensure that no User-Agent header is set if the client's UserAgent is empty.
565 // This caused a problem with Google's internal http client.
566 func TestNewRequest_emptyUserAgent(t *testing.T) {
567 c := NewClient(nil)
568 c.UserAgent = ""
569 req, err := c.NewRequest("GET", ".", nil)
570 if err != nil {
571 t.Fatalf("NewRequest returned unexpected error: %v", err)
572 }
573 if _, ok := req.Header["User-Agent"]; ok {
574 t.Fatal("constructed request contains unexpected User-Agent header")
575 }
576 }
577
578 // If a nil body is passed to github.NewRequest, make sure that nil is also
579 // passed to http.NewRequest. In most cases, passing an io.Reader that returns
580 // no content is fine, since there is no difference between an HTTP request
581 // body that is an empty string versus one that is not set at all. However in
582 // certain cases, intermediate systems may treat these differently resulting in
583 // subtle errors.
584 func TestNewRequest_emptyBody(t *testing.T) {
585 c := NewClient(nil)
586 req, err := c.NewRequest("GET", ".", nil)
587 if err != nil {
588 t.Fatalf("NewRequest returned unexpected error: %v", err)
589 }
590 if req.Body != nil {
591 t.Fatalf("constructed request contains a non-nil Body")
592 }
593 }
594
595 func TestNewRequest_errorForNoTrailingSlash(t *testing.T) {
596 tests := []struct {
597 rawurl string
598 wantError bool
599 }{
600 {rawurl: "https://example.com/api/v3", wantError: true},
601 {rawurl: "https://example.com/api/v3/", wantError: false},
602 }
603 c := NewClient(nil)
604 for _, test := range tests {
605 u, err := url.Parse(test.rawurl)
606 if err != nil {
607 t.Fatalf("url.Parse returned unexpected error: %v.", err)
608 }
609 c.BaseURL = u
610 if _, err := c.NewRequest(http.MethodGet, "test", nil); test.wantError && err == nil {
611 t.Fatalf("Expected error to be returned.")
612 } else if !test.wantError && err != nil {
613 t.Fatalf("NewRequest returned unexpected error: %v.", err)
614 }
615 }
616 }
617
618 func TestNewFormRequest(t *testing.T) {
619 c := NewClient(nil)
620
621 inURL, outURL := "/foo", defaultBaseURL+"foo"
622 form := url.Values{}
623 form.Add("login", "l")
624 inBody, outBody := strings.NewReader(form.Encode()), "login=l"
625 req, _ := c.NewFormRequest(inURL, inBody)
626
627 // test that relative URL was expanded
628 if got, want := req.URL.String(), outURL; got != want {
629 t.Errorf("NewFormRequest(%q) URL is %v, want %v", inURL, got, want)
630 }
631
632 // test that body was form encoded
633 body, _ := io.ReadAll(req.Body)
634 if got, want := string(body), outBody; got != want {
635 t.Errorf("NewFormRequest(%q) Body is %v, want %v", inBody, got, want)
636 }
637
638 // test that default user-agent is attached to the request
639 if got, want := req.Header.Get("User-Agent"), c.UserAgent; got != want {
640 t.Errorf("NewFormRequest() User-Agent is %v, want %v", got, want)
641 }
642
643 apiVersion := req.Header.Get(headerAPIVersion)
644 if got, want := apiVersion, defaultAPIVersion; got != want {
645 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
646 }
647
648 req, _ = c.NewFormRequest(inURL, inBody, WithVersion("2022-11-29"))
649 apiVersion = req.Header.Get(headerAPIVersion)
650 if got, want := apiVersion, "2022-11-29"; got != want {
651 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
652 }
653 }
654
655 func TestNewFormRequest_badURL(t *testing.T) {
656 c := NewClient(nil)
657 _, err := c.NewFormRequest(":", nil)
658 testURLParseError(t, err)
659 }
660
661 func TestNewFormRequest_emptyUserAgent(t *testing.T) {
662 c := NewClient(nil)
663 c.UserAgent = ""
664 req, err := c.NewFormRequest(".", nil)
665 if err != nil {
666 t.Fatalf("NewFormRequest returned unexpected error: %v", err)
667 }
668 if _, ok := req.Header["User-Agent"]; ok {
669 t.Fatal("constructed request contains unexpected User-Agent header")
670 }
671 }
672
673 func TestNewFormRequest_emptyBody(t *testing.T) {
674 c := NewClient(nil)
675 req, err := c.NewFormRequest(".", nil)
676 if err != nil {
677 t.Fatalf("NewFormRequest returned unexpected error: %v", err)
678 }
679 if req.Body != nil {
680 t.Fatalf("constructed request contains a non-nil Body")
681 }
682 }
683
684 func TestNewFormRequest_errorForNoTrailingSlash(t *testing.T) {
685 tests := []struct {
686 rawURL string
687 wantError bool
688 }{
689 {rawURL: "https://example.com/api/v3", wantError: true},
690 {rawURL: "https://example.com/api/v3/", wantError: false},
691 }
692 c := NewClient(nil)
693 for _, test := range tests {
694 u, err := url.Parse(test.rawURL)
695 if err != nil {
696 t.Fatalf("url.Parse returned unexpected error: %v.", err)
697 }
698 c.BaseURL = u
699 if _, err := c.NewFormRequest("test", nil); test.wantError && err == nil {
700 t.Fatalf("Expected error to be returned.")
701 } else if !test.wantError && err != nil {
702 t.Fatalf("NewFormRequest returned unexpected error: %v.", err)
703 }
704 }
705 }
706
707 func TestNewUploadRequest_WithVersion(t *testing.T) {
708 c := NewClient(nil)
709 req, _ := c.NewUploadRequest("https://example.com/", nil, 0, "")
710
711 apiVersion := req.Header.Get(headerAPIVersion)
712 if got, want := apiVersion, defaultAPIVersion; got != want {
713 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
714 }
715
716 req, _ = c.NewUploadRequest("https://example.com/", nil, 0, "", WithVersion("2022-11-29"))
717 apiVersion = req.Header.Get(headerAPIVersion)
718 if got, want := apiVersion, "2022-11-29"; got != want {
719 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
720 }
721 }
722
723 func TestNewUploadRequest_badURL(t *testing.T) {
724 c := NewClient(nil)
725 _, err := c.NewUploadRequest(":", nil, 0, "")
726 testURLParseError(t, err)
727
728 const methodName = "NewUploadRequest"
729 testBadOptions(t, methodName, func() (err error) {
730 _, err = c.NewUploadRequest("\n", nil, -1, "\n")
731 return err
732 })
733 }
734
735 func TestNewUploadRequest_errorForNoTrailingSlash(t *testing.T) {
736 tests := []struct {
737 rawurl string
738 wantError bool
739 }{
740 {rawurl: "https://example.com/api/uploads", wantError: true},
741 {rawurl: "https://example.com/api/uploads/", wantError: false},
742 }
743 c := NewClient(nil)
744 for _, test := range tests {
745 u, err := url.Parse(test.rawurl)
746 if err != nil {
747 t.Fatalf("url.Parse returned unexpected error: %v.", err)
748 }
749 c.UploadURL = u
750 if _, err = c.NewUploadRequest("test", nil, 0, ""); test.wantError && err == nil {
751 t.Fatalf("Expected error to be returned.")
752 } else if !test.wantError && err != nil {
753 t.Fatalf("NewUploadRequest returned unexpected error: %v.", err)
754 }
755 }
756 }
757
758 func TestResponse_populatePageValues(t *testing.T) {
759 r := http.Response{
760 Header: http.Header{
761 "Link": {`<https://api.github.com/?page=1>; rel="first",` +
762 ` <https://api.github.com/?page=2>; rel="prev",` +
763 ` <https://api.github.com/?page=4>; rel="next",` +
764 ` <https://api.github.com/?page=5>; rel="last"`,
765 },
766 },
767 }
768
769 response := newResponse(&r)
770 if got, want := response.FirstPage, 1; got != want {
771 t.Errorf("response.FirstPage: %v, want %v", got, want)
772 }
773 if got, want := response.PrevPage, 2; want != got {
774 t.Errorf("response.PrevPage: %v, want %v", got, want)
775 }
776 if got, want := response.NextPage, 4; want != got {
777 t.Errorf("response.NextPage: %v, want %v", got, want)
778 }
779 if got, want := response.LastPage, 5; want != got {
780 t.Errorf("response.LastPage: %v, want %v", got, want)
781 }
782 if got, want := response.NextPageToken, ""; want != got {
783 t.Errorf("response.NextPageToken: %v, want %v", got, want)
784 }
785 }
786
787 func TestResponse_populateSinceValues(t *testing.T) {
788 r := http.Response{
789 Header: http.Header{
790 "Link": {`<https://api.github.com/?since=1>; rel="first",` +
791 ` <https://api.github.com/?since=2>; rel="prev",` +
792 ` <https://api.github.com/?since=4>; rel="next",` +
793 ` <https://api.github.com/?since=5>; rel="last"`,
794 },
795 },
796 }
797
798 response := newResponse(&r)
799 if got, want := response.FirstPage, 1; got != want {
800 t.Errorf("response.FirstPage: %v, want %v", got, want)
801 }
802 if got, want := response.PrevPage, 2; want != got {
803 t.Errorf("response.PrevPage: %v, want %v", got, want)
804 }
805 if got, want := response.NextPage, 4; want != got {
806 t.Errorf("response.NextPage: %v, want %v", got, want)
807 }
808 if got, want := response.LastPage, 5; want != got {
809 t.Errorf("response.LastPage: %v, want %v", got, want)
810 }
811 if got, want := response.NextPageToken, ""; want != got {
812 t.Errorf("response.NextPageToken: %v, want %v", got, want)
813 }
814 }
815
816 func TestResponse_SinceWithPage(t *testing.T) {
817 r := http.Response{
818 Header: http.Header{
819 "Link": {`<https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=1>; rel="first",` +
820 ` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=2>; rel="prev",` +
821 ` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=4>; rel="next",` +
822 ` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=5>; rel="last"`,
823 },
824 },
825 }
826
827 response := newResponse(&r)
828 if got, want := response.FirstPage, 1; got != want {
829 t.Errorf("response.FirstPage: %v, want %v", got, want)
830 }
831 if got, want := response.PrevPage, 2; want != got {
832 t.Errorf("response.PrevPage: %v, want %v", got, want)
833 }
834 if got, want := response.NextPage, 4; want != got {
835 t.Errorf("response.NextPage: %v, want %v", got, want)
836 }
837 if got, want := response.LastPage, 5; want != got {
838 t.Errorf("response.LastPage: %v, want %v", got, want)
839 }
840 if got, want := response.NextPageToken, ""; want != got {
841 t.Errorf("response.NextPageToken: %v, want %v", got, want)
842 }
843 }
844
845 func TestResponse_cursorPagination(t *testing.T) {
846 r := http.Response{
847 Header: http.Header{
848 "Status": {"200 OK"},
849 "Link": {`<https://api.github.com/resource?per_page=2&page=url-encoded-next-page-token>; rel="next"`},
850 },
851 }
852
853 response := newResponse(&r)
854 if got, want := response.FirstPage, 0; got != want {
855 t.Errorf("response.FirstPage: %v, want %v", got, want)
856 }
857 if got, want := response.PrevPage, 0; want != got {
858 t.Errorf("response.PrevPage: %v, want %v", got, want)
859 }
860 if got, want := response.NextPage, 0; want != got {
861 t.Errorf("response.NextPage: %v, want %v", got, want)
862 }
863 if got, want := response.LastPage, 0; want != got {
864 t.Errorf("response.LastPage: %v, want %v", got, want)
865 }
866 if got, want := response.NextPageToken, "url-encoded-next-page-token"; want != got {
867 t.Errorf("response.NextPageToken: %v, want %v", got, want)
868 }
869
870 // cursor-based pagination with "cursor" param
871 r = http.Response{
872 Header: http.Header{
873 "Link": {
874 `<https://api.github.com/?cursor=v1_12345678>; rel="next"`,
875 },
876 },
877 }
878
879 response = newResponse(&r)
880 if got, want := response.Cursor, "v1_12345678"; got != want {
881 t.Errorf("response.Cursor: %v, want %v", got, want)
882 }
883 }
884
885 func TestResponse_beforeAfterPagination(t *testing.T) {
886 r := http.Response{
887 Header: http.Header{
888 "Link": {`<https://api.github.com/?after=a1b2c3&before=>; rel="next",` +
889 ` <https://api.github.com/?after=&before=>; rel="first",` +
890 ` <https://api.github.com/?after=&before=d4e5f6>; rel="prev",`,
891 },
892 },
893 }
894
895 response := newResponse(&r)
896 if got, want := response.Before, "d4e5f6"; got != want {
897 t.Errorf("response.Before: %v, want %v", got, want)
898 }
899 if got, want := response.After, "a1b2c3"; got != want {
900 t.Errorf("response.After: %v, want %v", got, want)
901 }
902 if got, want := response.FirstPage, 0; got != want {
903 t.Errorf("response.FirstPage: %v, want %v", got, want)
904 }
905 if got, want := response.PrevPage, 0; want != got {
906 t.Errorf("response.PrevPage: %v, want %v", got, want)
907 }
908 if got, want := response.NextPage, 0; want != got {
909 t.Errorf("response.NextPage: %v, want %v", got, want)
910 }
911 if got, want := response.LastPage, 0; want != got {
912 t.Errorf("response.LastPage: %v, want %v", got, want)
913 }
914 if got, want := response.NextPageToken, ""; want != got {
915 t.Errorf("response.NextPageToken: %v, want %v", got, want)
916 }
917 }
918
919 func TestResponse_populatePageValues_invalid(t *testing.T) {
920 r := http.Response{
921 Header: http.Header{
922 "Link": {`<https://api.github.com/?page=1>,` +
923 `<https://api.github.com/?page=abc>; rel="first",` +
924 `https://api.github.com/?page=2; rel="prev",` +
925 `<https://api.github.com/>; rel="next",` +
926 `<https://api.github.com/?page=>; rel="last"`,
927 },
928 },
929 }
930
931 response := newResponse(&r)
932 if got, want := response.FirstPage, 0; got != want {
933 t.Errorf("response.FirstPage: %v, want %v", got, want)
934 }
935 if got, want := response.PrevPage, 0; got != want {
936 t.Errorf("response.PrevPage: %v, want %v", got, want)
937 }
938 if got, want := response.NextPage, 0; got != want {
939 t.Errorf("response.NextPage: %v, want %v", got, want)
940 }
941 if got, want := response.LastPage, 0; got != want {
942 t.Errorf("response.LastPage: %v, want %v", got, want)
943 }
944
945 // more invalid URLs
946 r = http.Response{
947 Header: http.Header{
948 "Link": {`<https://api.github.com/%?page=2>; rel="first"`},
949 },
950 }
951
952 response = newResponse(&r)
953 if got, want := response.FirstPage, 0; got != want {
954 t.Errorf("response.FirstPage: %v, want %v", got, want)
955 }
956 }
957
958 func TestResponse_populateSinceValues_invalid(t *testing.T) {
959 r := http.Response{
960 Header: http.Header{
961 "Link": {`<https://api.github.com/?since=1>,` +
962 `<https://api.github.com/?since=abc>; rel="first",` +
963 `https://api.github.com/?since=2; rel="prev",` +
964 `<https://api.github.com/>; rel="next",` +
965 `<https://api.github.com/?since=>; rel="last"`,
966 },
967 },
968 }
969
970 response := newResponse(&r)
971 if got, want := response.FirstPage, 0; got != want {
972 t.Errorf("response.FirstPage: %v, want %v", got, want)
973 }
974 if got, want := response.PrevPage, 0; got != want {
975 t.Errorf("response.PrevPage: %v, want %v", got, want)
976 }
977 if got, want := response.NextPage, 0; got != want {
978 t.Errorf("response.NextPage: %v, want %v", got, want)
979 }
980 if got, want := response.LastPage, 0; got != want {
981 t.Errorf("response.LastPage: %v, want %v", got, want)
982 }
983
984 // more invalid URLs
985 r = http.Response{
986 Header: http.Header{
987 "Link": {`<https://api.github.com/%?since=2>; rel="first"`},
988 },
989 }
990
991 response = newResponse(&r)
992 if got, want := response.FirstPage, 0; got != want {
993 t.Errorf("response.FirstPage: %v, want %v", got, want)
994 }
995 }
996
997 func TestDo(t *testing.T) {
998 client, mux, _, teardown := setup()
999 defer teardown()
1000
1001 type foo struct {
1002 A string
1003 }
1004
1005 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1006 testMethod(t, r, "GET")
1007 fmt.Fprint(w, `{"A":"a"}`)
1008 })
1009
1010 req, _ := client.NewRequest("GET", ".", nil)
1011 body := new(foo)
1012 ctx := context.Background()
1013 _, err := client.Do(ctx, req, body)
1014 assertNilError(t, err)
1015
1016 want := &foo{"a"}
1017 if !cmp.Equal(body, want) {
1018 t.Errorf("Response body = %v, want %v", body, want)
1019 }
1020 }
1021
1022 func TestDo_nilContext(t *testing.T) {
1023 client, _, _, teardown := setup()
1024 defer teardown()
1025
1026 req, _ := client.NewRequest("GET", ".", nil)
1027 _, err := client.Do(nil, req, nil)
1028
1029 if !errors.Is(err, errNonNilContext) {
1030 t.Errorf("Expected context must be non-nil error")
1031 }
1032 }
1033
1034 func TestDo_httpError(t *testing.T) {
1035 client, mux, _, teardown := setup()
1036 defer teardown()
1037
1038 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1039 http.Error(w, "Bad Request", 400)
1040 })
1041
1042 req, _ := client.NewRequest("GET", ".", nil)
1043 ctx := context.Background()
1044 resp, err := client.Do(ctx, req, nil)
1045
1046 if err == nil {
1047 t.Fatal("Expected HTTP 400 error, got no error.")
1048 }
1049 if resp.StatusCode != 400 {
1050 t.Errorf("Expected HTTP 400 error, got %d status code.", resp.StatusCode)
1051 }
1052 }
1053
1054 // Test handling of an error caused by the internal http client's Do()
1055 // function. A redirect loop is pretty unlikely to occur within the GitHub
1056 // API, but does allow us to exercise the right code path.
1057 func TestDo_redirectLoop(t *testing.T) {
1058 client, mux, _, teardown := setup()
1059 defer teardown()
1060
1061 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1062 http.Redirect(w, r, baseURLPath, http.StatusFound)
1063 })
1064
1065 req, _ := client.NewRequest("GET", ".", nil)
1066 ctx := context.Background()
1067 _, err := client.Do(ctx, req, nil)
1068
1069 if err == nil {
1070 t.Error("Expected error to be returned.")
1071 }
1072 if err, ok := err.(*url.Error); !ok {
1073 t.Errorf("Expected a URL error; got %#v.", err)
1074 }
1075 }
1076
1077 // Test that an error caused by the internal http client's Do() function
1078 // does not leak the client secret.
1079 func TestDo_sanitizeURL(t *testing.T) {
1080 tp := &UnauthenticatedRateLimitedTransport{
1081 ClientID: "id",
1082 ClientSecret: "secret",
1083 }
1084 unauthedClient := NewClient(tp.Client())
1085 unauthedClient.BaseURL = &url.URL{Scheme: "http", Host: "127.0.0.1:0", Path: "/"} // Use port 0 on purpose to trigger a dial TCP error, expect to get "dial tcp 127.0.0.1:0: connect: can't assign requested address".
1086 req, err := unauthedClient.NewRequest("GET", ".", nil)
1087 if err != nil {
1088 t.Fatalf("NewRequest returned unexpected error: %v", err)
1089 }
1090 ctx := context.Background()
1091 _, err = unauthedClient.Do(ctx, req, nil)
1092 if err == nil {
1093 t.Fatal("Expected error to be returned.")
1094 }
1095 if strings.Contains(err.Error(), "client_secret=secret") {
1096 t.Errorf("Do error contains secret, should be redacted:\n%q", err)
1097 }
1098 }
1099
1100 func TestDo_rateLimit(t *testing.T) {
1101 client, mux, _, teardown := setup()
1102 defer teardown()
1103
1104 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1105 w.Header().Set(headerRateLimit, "60")
1106 w.Header().Set(headerRateRemaining, "59")
1107 w.Header().Set(headerRateReset, "1372700873")
1108 })
1109
1110 req, _ := client.NewRequest("GET", ".", nil)
1111 ctx := context.Background()
1112 resp, err := client.Do(ctx, req, nil)
1113 if err != nil {
1114 t.Errorf("Do returned unexpected error: %v", err)
1115 }
1116 if got, want := resp.Rate.Limit, 60; got != want {
1117 t.Errorf("Client rate limit = %v, want %v", got, want)
1118 }
1119 if got, want := resp.Rate.Remaining, 59; got != want {
1120 t.Errorf("Client rate remaining = %v, want %v", got, want)
1121 }
1122 reset := time.Date(2013, time.July, 1, 17, 47, 53, 0, time.UTC)
1123 if resp.Rate.Reset.UTC() != reset {
1124 t.Errorf("Client rate reset = %v, want %v", resp.Rate.Reset, reset)
1125 }
1126 }
1127
1128 func TestDo_rateLimitCategory(t *testing.T) {
1129 tests := []struct {
1130 method string
1131 url string
1132 category rateLimitCategory
1133 }{
1134 {
1135 method: http.MethodGet,
1136 url: "/",
1137 category: coreCategory,
1138 },
1139 {
1140 method: http.MethodGet,
1141 url: "/search/issues?q=rate",
1142 category: searchCategory,
1143 },
1144 {
1145 method: http.MethodGet,
1146 url: "/graphql",
1147 category: graphqlCategory,
1148 },
1149 {
1150 method: http.MethodPost,
1151 url: "/app-manifests/code/conversions",
1152 category: integrationManifestCategory,
1153 },
1154 {
1155 method: http.MethodGet,
1156 url: "/app-manifests/code/conversions",
1157 category: coreCategory, // only POST requests are in the integration manifest category
1158 },
1159 {
1160 method: http.MethodPut,
1161 url: "/repos/google/go-github/import",
1162 category: sourceImportCategory,
1163 },
1164 {
1165 method: http.MethodGet,
1166 url: "/repos/google/go-github/import",
1167 category: coreCategory, // only PUT requests are in the source import category
1168 },
1169 {
1170 method: http.MethodPost,
1171 url: "/repos/google/go-github/code-scanning/sarifs",
1172 category: codeScanningUploadCategory,
1173 },
1174 {
1175 method: http.MethodGet,
1176 url: "/scim/v2/organizations/ORG/Users",
1177 category: scimCategory,
1178 },
1179 {
1180 method: http.MethodPost,
1181 url: "/repos/google/go-github/dependency-graph/snapshots",
1182 category: dependencySnapshotsCategory,
1183 },
1184 {
1185 method: http.MethodGet,
1186 url: "/search/code?q=rate",
1187 category: codeSearchCategory,
1188 },
1189 // missing a check for actionsRunnerRegistrationCategory: API not found
1190 }
1191
1192 for _, tt := range tests {
1193 if got, want := category(tt.method, tt.url), tt.category; got != want {
1194 t.Errorf("expecting category %v, found %v", got, want)
1195 }
1196 }
1197 }
1198
1199 // ensure rate limit is still parsed, even for error responses
1200 func TestDo_rateLimit_errorResponse(t *testing.T) {
1201 client, mux, _, teardown := setup()
1202 defer teardown()
1203
1204 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1205 w.Header().Set(headerRateLimit, "60")
1206 w.Header().Set(headerRateRemaining, "59")
1207 w.Header().Set(headerRateReset, "1372700873")
1208 http.Error(w, "Bad Request", 400)
1209 })
1210
1211 req, _ := client.NewRequest("GET", ".", nil)
1212 ctx := context.Background()
1213 resp, err := client.Do(ctx, req, nil)
1214 if err == nil {
1215 t.Error("Expected error to be returned.")
1216 }
1217 if _, ok := err.(*RateLimitError); ok {
1218 t.Errorf("Did not expect a *RateLimitError error; got %#v.", err)
1219 }
1220 if got, want := resp.Rate.Limit, 60; got != want {
1221 t.Errorf("Client rate limit = %v, want %v", got, want)
1222 }
1223 if got, want := resp.Rate.Remaining, 59; got != want {
1224 t.Errorf("Client rate remaining = %v, want %v", got, want)
1225 }
1226 reset := time.Date(2013, time.July, 1, 17, 47, 53, 0, time.UTC)
1227 if resp.Rate.Reset.UTC() != reset {
1228 t.Errorf("Client rate reset = %v, want %v", resp.Rate.Reset, reset)
1229 }
1230 }
1231
1232 // Ensure *RateLimitError is returned when API rate limit is exceeded.
1233 func TestDo_rateLimit_rateLimitError(t *testing.T) {
1234 client, mux, _, teardown := setup()
1235 defer teardown()
1236
1237 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1238 w.Header().Set(headerRateLimit, "60")
1239 w.Header().Set(headerRateRemaining, "0")
1240 w.Header().Set(headerRateReset, "1372700873")
1241 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1242 w.WriteHeader(http.StatusForbidden)
1243 fmt.Fprintln(w, `{
1244 "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
1245 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1246 }`)
1247 })
1248
1249 req, _ := client.NewRequest("GET", ".", nil)
1250 ctx := context.Background()
1251 _, err := client.Do(ctx, req, nil)
1252
1253 if err == nil {
1254 t.Error("Expected error to be returned.")
1255 }
1256 rateLimitErr, ok := err.(*RateLimitError)
1257 if !ok {
1258 t.Fatalf("Expected a *RateLimitError error; got %#v.", err)
1259 }
1260 if got, want := rateLimitErr.Rate.Limit, 60; got != want {
1261 t.Errorf("rateLimitErr rate limit = %v, want %v", got, want)
1262 }
1263 if got, want := rateLimitErr.Rate.Remaining, 0; got != want {
1264 t.Errorf("rateLimitErr rate remaining = %v, want %v", got, want)
1265 }
1266 reset := time.Date(2013, time.July, 1, 17, 47, 53, 0, time.UTC)
1267 if rateLimitErr.Rate.Reset.UTC() != reset {
1268 t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset)
1269 }
1270 }
1271
1272 // Ensure a network call is not made when it's known that API rate limit is still exceeded.
1273 func TestDo_rateLimit_noNetworkCall(t *testing.T) {
1274 client, mux, _, teardown := setup()
1275 defer teardown()
1276
1277 reset := time.Now().UTC().Add(time.Minute).Round(time.Second) // Rate reset is a minute from now, with 1 second precision.
1278
1279 mux.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) {
1280 w.Header().Set(headerRateLimit, "60")
1281 w.Header().Set(headerRateRemaining, "0")
1282 w.Header().Set(headerRateReset, fmt.Sprint(reset.Unix()))
1283 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1284 w.WriteHeader(http.StatusForbidden)
1285 fmt.Fprintln(w, `{
1286 "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
1287 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1288 }`)
1289 })
1290
1291 madeNetworkCall := false
1292 mux.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) {
1293 madeNetworkCall = true
1294 })
1295
1296 // First request is made, and it makes the client aware of rate reset time being in the future.
1297 req, _ := client.NewRequest("GET", "first", nil)
1298 ctx := context.Background()
1299 _, err := client.Do(ctx, req, nil)
1300 if err == nil {
1301 t.Error("Expected error to be returned.")
1302 }
1303
1304 // Second request should not cause a network call to be made, since client can predict a rate limit error.
1305 req, _ = client.NewRequest("GET", "second", nil)
1306 _, err = client.Do(ctx, req, nil)
1307
1308 if madeNetworkCall {
1309 t.Fatal("Network call was made, even though rate limit is known to still be exceeded.")
1310 }
1311
1312 if err == nil {
1313 t.Error("Expected error to be returned.")
1314 }
1315 rateLimitErr, ok := err.(*RateLimitError)
1316 if !ok {
1317 t.Fatalf("Expected a *RateLimitError error; got %#v.", err)
1318 }
1319 if got, want := rateLimitErr.Rate.Limit, 60; got != want {
1320 t.Errorf("rateLimitErr rate limit = %v, want %v", got, want)
1321 }
1322 if got, want := rateLimitErr.Rate.Remaining, 0; got != want {
1323 t.Errorf("rateLimitErr rate remaining = %v, want %v", got, want)
1324 }
1325 if rateLimitErr.Rate.Reset.UTC() != reset {
1326 t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset)
1327 }
1328 }
1329
1330 // Ignore rate limit headers if the response was served from cache.
1331 func TestDo_rateLimit_ignoredFromCache(t *testing.T) {
1332 client, mux, _, teardown := setup()
1333 defer teardown()
1334
1335 reset := time.Now().UTC().Add(time.Minute).Round(time.Second) // Rate reset is a minute from now, with 1 second precision.
1336
1337 // By adding the X-From-Cache header we pretend this is served from a cache.
1338 mux.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) {
1339 w.Header().Set("X-From-Cache", "1")
1340 w.Header().Set(headerRateLimit, "60")
1341 w.Header().Set(headerRateRemaining, "0")
1342 w.Header().Set(headerRateReset, fmt.Sprint(reset.Unix()))
1343 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1344 w.WriteHeader(http.StatusForbidden)
1345 fmt.Fprintln(w, `{
1346 "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
1347 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1348 }`)
1349 })
1350
1351 madeNetworkCall := false
1352 mux.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) {
1353 madeNetworkCall = true
1354 })
1355
1356 // First request is made so afterwards we can check the returned rate limit headers were ignored.
1357 req, _ := client.NewRequest("GET", "first", nil)
1358 ctx := context.Background()
1359 _, err := client.Do(ctx, req, nil)
1360 if err == nil {
1361 t.Error("Expected error to be returned.")
1362 }
1363
1364 // Second request should not by hindered by rate limits.
1365 req, _ = client.NewRequest("GET", "second", nil)
1366 _, err = client.Do(ctx, req, nil)
1367
1368 if err != nil {
1369 t.Fatalf("Second request failed, even though the rate limits from the cache should've been ignored: %v", err)
1370 }
1371 if !madeNetworkCall {
1372 t.Fatal("Network call was not made, even though the rate limits from the cache should've been ignored")
1373 }
1374 }
1375
1376 // Ensure *AbuseRateLimitError is returned when the response indicates that
1377 // the client has triggered an abuse detection mechanism.
1378 func TestDo_rateLimit_abuseRateLimitError(t *testing.T) {
1379 client, mux, _, teardown := setup()
1380 defer teardown()
1381
1382 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1383 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1384 w.WriteHeader(http.StatusForbidden)
1385 // When the abuse rate limit error is of the "temporarily blocked from content creation" type,
1386 // there is no "Retry-After" header.
1387 fmt.Fprintln(w, `{
1388 "message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.",
1389 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1390 }`)
1391 })
1392
1393 req, _ := client.NewRequest("GET", ".", nil)
1394 ctx := context.Background()
1395 _, err := client.Do(ctx, req, nil)
1396
1397 if err == nil {
1398 t.Error("Expected error to be returned.")
1399 }
1400 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1401 if !ok {
1402 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1403 }
1404 if got, want := abuseRateLimitErr.RetryAfter, (*time.Duration)(nil); got != want {
1405 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1406 }
1407 }
1408
1409 // Ensure *AbuseRateLimitError is returned when the response indicates that
1410 // the client has triggered an abuse detection mechanism on GitHub Enterprise.
1411 func TestDo_rateLimit_abuseRateLimitErrorEnterprise(t *testing.T) {
1412 client, mux, _, teardown := setup()
1413 defer teardown()
1414
1415 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1416 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1417 w.WriteHeader(http.StatusForbidden)
1418 // When the abuse rate limit error is of the "temporarily blocked from content creation" type,
1419 // there is no "Retry-After" header.
1420 // This response returns a documentation url like the one returned for GitHub Enterprise, this
1421 // url changes between versions but follows roughly the same format.
1422 fmt.Fprintln(w, `{
1423 "message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.",
1424 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1425 }`)
1426 })
1427
1428 req, _ := client.NewRequest("GET", ".", nil)
1429 ctx := context.Background()
1430 _, err := client.Do(ctx, req, nil)
1431
1432 if err == nil {
1433 t.Error("Expected error to be returned.")
1434 }
1435 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1436 if !ok {
1437 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1438 }
1439 if got, want := abuseRateLimitErr.RetryAfter, (*time.Duration)(nil); got != want {
1440 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1441 }
1442 }
1443
1444 // Ensure *AbuseRateLimitError.RetryAfter is parsed correctly for the Retry-After header.
1445 func TestDo_rateLimit_abuseRateLimitError_retryAfter(t *testing.T) {
1446 client, mux, _, teardown := setup()
1447 defer teardown()
1448
1449 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1450 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1451 w.Header().Set(headerRetryAfter, "123") // Retry after value of 123 seconds.
1452 w.WriteHeader(http.StatusForbidden)
1453 fmt.Fprintln(w, `{
1454 "message": "You have triggered an abuse detection mechanism ...",
1455 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1456 }`)
1457 })
1458
1459 req, _ := client.NewRequest("GET", ".", nil)
1460 ctx := context.Background()
1461 _, err := client.Do(ctx, req, nil)
1462
1463 if err == nil {
1464 t.Error("Expected error to be returned.")
1465 }
1466 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1467 if !ok {
1468 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1469 }
1470 if abuseRateLimitErr.RetryAfter == nil {
1471 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1472 }
1473 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; got != want {
1474 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1475 }
1476
1477 // expect prevention of a following request
1478 if _, err = client.Do(ctx, req, nil); err == nil {
1479 t.Error("Expected error to be returned.")
1480 }
1481 abuseRateLimitErr, ok = err.(*AbuseRateLimitError)
1482 if !ok {
1483 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1484 }
1485 if abuseRateLimitErr.RetryAfter == nil {
1486 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1487 }
1488 // the saved duration might be a bit smaller than Retry-After because the duration is calculated from the expected end-of-cooldown time
1489 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; want-got > 1*time.Second {
1490 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1491 }
1492 if got, wantSuffix := abuseRateLimitErr.Message, "not making remote request."; !strings.HasSuffix(got, wantSuffix) {
1493 t.Errorf("Expected request to be prevented because of secondary rate limit, got: %v.", got)
1494 }
1495 }
1496
1497 // Ensure *AbuseRateLimitError.RetryAfter is parsed correctly for the x-ratelimit-reset header.
1498 func TestDo_rateLimit_abuseRateLimitError_xRateLimitReset(t *testing.T) {
1499 client, mux, _, teardown := setup()
1500 defer teardown()
1501
1502 // x-ratelimit-reset value of 123 seconds into the future.
1503 blockUntil := time.Now().Add(time.Duration(123) * time.Second).Unix()
1504
1505 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1506 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1507 w.Header().Set(headerRateReset, strconv.Itoa(int(blockUntil)))
1508 w.Header().Set(headerRateRemaining, "1") // set remaining to a value > 0 to distinct from a primary rate limit
1509 w.WriteHeader(http.StatusForbidden)
1510 fmt.Fprintln(w, `{
1511 "message": "You have triggered an abuse detection mechanism ...",
1512 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1513 }`)
1514 })
1515
1516 req, _ := client.NewRequest("GET", ".", nil)
1517 ctx := context.Background()
1518 _, err := client.Do(ctx, req, nil)
1519
1520 if err == nil {
1521 t.Error("Expected error to be returned.")
1522 }
1523 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1524 if !ok {
1525 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1526 }
1527 if abuseRateLimitErr.RetryAfter == nil {
1528 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1529 }
1530 // the retry after value might be a bit smaller than the original duration because the duration is calculated from the expected end-of-cooldown time
1531 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; want-got > 1*time.Second {
1532 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1533 }
1534
1535 // expect prevention of a following request
1536 if _, err = client.Do(ctx, req, nil); err == nil {
1537 t.Error("Expected error to be returned.")
1538 }
1539 abuseRateLimitErr, ok = err.(*AbuseRateLimitError)
1540 if !ok {
1541 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1542 }
1543 if abuseRateLimitErr.RetryAfter == nil {
1544 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1545 }
1546 // the saved duration might be a bit smaller than Retry-After because the duration is calculated from the expected end-of-cooldown time
1547 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; want-got > 1*time.Second {
1548 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1549 }
1550 if got, wantSuffix := abuseRateLimitErr.Message, "not making remote request."; !strings.HasSuffix(got, wantSuffix) {
1551 t.Errorf("Expected request to be prevented because of secondary rate limit, got: %v.", got)
1552 }
1553 }
1554
1555 func TestDo_noContent(t *testing.T) {
1556 client, mux, _, teardown := setup()
1557 defer teardown()
1558
1559 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1560 w.WriteHeader(http.StatusNoContent)
1561 })
1562
1563 var body json.RawMessage
1564
1565 req, _ := client.NewRequest("GET", ".", nil)
1566 ctx := context.Background()
1567 _, err := client.Do(ctx, req, &body)
1568 if err != nil {
1569 t.Fatalf("Do returned unexpected error: %v", err)
1570 }
1571 }
1572
1573 func TestSanitizeURL(t *testing.T) {
1574 tests := []struct {
1575 in, want string
1576 }{
1577 {"/?a=b", "/?a=b"},
1578 {"/?a=b&client_secret=secret", "/?a=b&client_secret=REDACTED"},
1579 {"/?a=b&client_id=id&client_secret=secret", "/?a=b&client_id=id&client_secret=REDACTED"},
1580 }
1581
1582 for _, tt := range tests {
1583 inURL, _ := url.Parse(tt.in)
1584 want, _ := url.Parse(tt.want)
1585
1586 if got := sanitizeURL(inURL); !cmp.Equal(got, want) {
1587 t.Errorf("sanitizeURL(%v) returned %v, want %v", tt.in, got, want)
1588 }
1589 }
1590 }
1591
1592 func TestCheckResponse(t *testing.T) {
1593 res := &http.Response{
1594 Request: &http.Request{},
1595 StatusCode: http.StatusBadRequest,
1596 Body: io.NopCloser(strings.NewReader(`{"message":"m",
1597 "errors": [{"resource": "r", "field": "f", "code": "c"}],
1598 "block": {"reason": "dmca", "created_at": "2016-03-17T15:39:46Z"}}`)),
1599 }
1600 err := CheckResponse(res).(*ErrorResponse)
1601
1602 if err == nil {
1603 t.Errorf("Expected error response.")
1604 }
1605
1606 want := &ErrorResponse{
1607 Response: res,
1608 Message: "m",
1609 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1610 Block: &ErrorBlock{
1611 Reason: "dmca",
1612 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1613 },
1614 }
1615 if !errors.Is(err, want) {
1616 t.Errorf("Error = %#v, want %#v", err, want)
1617 }
1618 }
1619
1620 func TestCheckResponse_RateLimit(t *testing.T) {
1621 res := &http.Response{
1622 Request: &http.Request{},
1623 StatusCode: http.StatusForbidden,
1624 Header: http.Header{},
1625 Body: io.NopCloser(strings.NewReader(`{"message":"m",
1626 "documentation_url": "url"}`)),
1627 }
1628 res.Header.Set(headerRateLimit, "60")
1629 res.Header.Set(headerRateRemaining, "0")
1630 res.Header.Set(headerRateReset, "243424")
1631
1632 err := CheckResponse(res).(*RateLimitError)
1633
1634 if err == nil {
1635 t.Errorf("Expected error response.")
1636 }
1637
1638 want := &RateLimitError{
1639 Rate: parseRate(res),
1640 Response: res,
1641 Message: "m",
1642 }
1643 if !errors.Is(err, want) {
1644 t.Errorf("Error = %#v, want %#v", err, want)
1645 }
1646 }
1647
1648 func TestCheckResponse_AbuseRateLimit(t *testing.T) {
1649 res := &http.Response{
1650 Request: &http.Request{},
1651 StatusCode: http.StatusForbidden,
1652 Body: io.NopCloser(strings.NewReader(`{"message":"m",
1653 "documentation_url": "docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"}`)),
1654 }
1655 err := CheckResponse(res).(*AbuseRateLimitError)
1656
1657 if err == nil {
1658 t.Errorf("Expected error response.")
1659 }
1660
1661 want := &AbuseRateLimitError{
1662 Response: res,
1663 Message: "m",
1664 }
1665 if !errors.Is(err, want) {
1666 t.Errorf("Error = %#v, want %#v", err, want)
1667 }
1668 }
1669
1670 func TestCompareHttpResponse(t *testing.T) {
1671 testcases := map[string]struct {
1672 h1 *http.Response
1673 h2 *http.Response
1674 expected bool
1675 }{
1676 "both are nil": {
1677 expected: true,
1678 },
1679 "both are non nil - same StatusCode": {
1680 expected: true,
1681 h1: &http.Response{StatusCode: 200},
1682 h2: &http.Response{StatusCode: 200},
1683 },
1684 "both are non nil - different StatusCode": {
1685 expected: false,
1686 h1: &http.Response{StatusCode: 200},
1687 h2: &http.Response{StatusCode: 404},
1688 },
1689 "one is nil, other is not": {
1690 expected: false,
1691 h2: &http.Response{},
1692 },
1693 }
1694
1695 for name, tc := range testcases {
1696 t.Run(name, func(t *testing.T) {
1697 v := compareHTTPResponse(tc.h1, tc.h2)
1698 if tc.expected != v {
1699 t.Errorf("Expected %t, got %t for (%#v, %#v)", tc.expected, v, tc.h1, tc.h2)
1700 }
1701 })
1702 }
1703 }
1704
1705 func TestErrorResponse_Is(t *testing.T) {
1706 err := &ErrorResponse{
1707 Response: &http.Response{},
1708 Message: "m",
1709 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1710 Block: &ErrorBlock{
1711 Reason: "r",
1712 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1713 },
1714 DocumentationURL: "https://github.com",
1715 }
1716 testcases := map[string]struct {
1717 wantSame bool
1718 otherError error
1719 }{
1720 "errors are same": {
1721 wantSame: true,
1722 otherError: &ErrorResponse{
1723 Response: &http.Response{},
1724 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1725 Message: "m",
1726 Block: &ErrorBlock{
1727 Reason: "r",
1728 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1729 },
1730 DocumentationURL: "https://github.com",
1731 },
1732 },
1733 "errors have different values - Message": {
1734 wantSame: false,
1735 otherError: &ErrorResponse{
1736 Response: &http.Response{},
1737 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1738 Message: "m1",
1739 Block: &ErrorBlock{
1740 Reason: "r",
1741 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1742 },
1743 DocumentationURL: "https://github.com",
1744 },
1745 },
1746 "errors have different values - DocumentationURL": {
1747 wantSame: false,
1748 otherError: &ErrorResponse{
1749 Response: &http.Response{},
1750 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1751 Message: "m",
1752 Block: &ErrorBlock{
1753 Reason: "r",
1754 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1755 },
1756 DocumentationURL: "https://google.com",
1757 },
1758 },
1759 "errors have different values - Response is nil": {
1760 wantSame: false,
1761 otherError: &ErrorResponse{
1762 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1763 Message: "m",
1764 Block: &ErrorBlock{
1765 Reason: "r",
1766 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1767 },
1768 DocumentationURL: "https://github.com",
1769 },
1770 },
1771 "errors have different values - Errors": {
1772 wantSame: false,
1773 otherError: &ErrorResponse{
1774 Response: &http.Response{},
1775 Errors: []Error{{Resource: "r1", Field: "f1", Code: "c1"}},
1776 Message: "m",
1777 Block: &ErrorBlock{
1778 Reason: "r",
1779 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1780 },
1781 DocumentationURL: "https://github.com",
1782 },
1783 },
1784 "errors have different values - Errors have different length": {
1785 wantSame: false,
1786 otherError: &ErrorResponse{
1787 Response: &http.Response{},
1788 Errors: []Error{},
1789 Message: "m",
1790 Block: &ErrorBlock{
1791 Reason: "r",
1792 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1793 },
1794 DocumentationURL: "https://github.com",
1795 },
1796 },
1797 "errors have different values - Block - one is nil, other is not": {
1798 wantSame: false,
1799 otherError: &ErrorResponse{
1800 Response: &http.Response{},
1801 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1802 Message: "m",
1803 DocumentationURL: "https://github.com",
1804 },
1805 },
1806 "errors have different values - Block - different Reason": {
1807 wantSame: false,
1808 otherError: &ErrorResponse{
1809 Response: &http.Response{},
1810 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1811 Message: "m",
1812 Block: &ErrorBlock{
1813 Reason: "r1",
1814 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1815 },
1816 DocumentationURL: "https://github.com",
1817 },
1818 },
1819 "errors have different values - Block - different CreatedAt #1": {
1820 wantSame: false,
1821 otherError: &ErrorResponse{
1822 Response: &http.Response{},
1823 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1824 Message: "m",
1825 Block: &ErrorBlock{
1826 Reason: "r",
1827 CreatedAt: nil,
1828 },
1829 DocumentationURL: "https://github.com",
1830 },
1831 },
1832 "errors have different values - Block - different CreatedAt #2": {
1833 wantSame: false,
1834 otherError: &ErrorResponse{
1835 Response: &http.Response{},
1836 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1837 Message: "m",
1838 Block: &ErrorBlock{
1839 Reason: "r",
1840 CreatedAt: &Timestamp{time.Date(2017, time.March, 17, 15, 39, 46, 0, time.UTC)},
1841 },
1842 DocumentationURL: "https://github.com",
1843 },
1844 },
1845 "errors have different types": {
1846 wantSame: false,
1847 otherError: errors.New("Github"),
1848 },
1849 }
1850
1851 for name, tc := range testcases {
1852 t.Run(name, func(t *testing.T) {
1853 if tc.wantSame != err.Is(tc.otherError) {
1854 t.Errorf("Error = %#v, want %#v", err, tc.otherError)
1855 }
1856 })
1857 }
1858 }
1859
1860 func TestRateLimitError_Is(t *testing.T) {
1861 err := &RateLimitError{
1862 Response: &http.Response{},
1863 Message: "Github",
1864 }
1865 testcases := map[string]struct {
1866 wantSame bool
1867 err *RateLimitError
1868 otherError error
1869 }{
1870 "errors are same": {
1871 wantSame: true,
1872 err: err,
1873 otherError: &RateLimitError{
1874 Response: &http.Response{},
1875 Message: "Github",
1876 },
1877 },
1878 "errors are same - Response is nil": {
1879 wantSame: true,
1880 err: &RateLimitError{
1881 Message: "Github",
1882 },
1883 otherError: &RateLimitError{
1884 Message: "Github",
1885 },
1886 },
1887 "errors have different values - Rate": {
1888 wantSame: false,
1889 err: err,
1890 otherError: &RateLimitError{
1891 Rate: Rate{Limit: 10},
1892 Response: &http.Response{},
1893 Message: "Gitlab",
1894 },
1895 },
1896 "errors have different values - Response is nil": {
1897 wantSame: false,
1898 err: err,
1899 otherError: &RateLimitError{
1900 Message: "Github",
1901 },
1902 },
1903 "errors have different values - StatusCode": {
1904 wantSame: false,
1905 err: err,
1906 otherError: &RateLimitError{
1907 Response: &http.Response{StatusCode: 200},
1908 Message: "Github",
1909 },
1910 },
1911 "errors have different types": {
1912 wantSame: false,
1913 err: err,
1914 otherError: errors.New("Github"),
1915 },
1916 }
1917
1918 for name, tc := range testcases {
1919 t.Run(name, func(t *testing.T) {
1920 if tc.wantSame != tc.err.Is(tc.otherError) {
1921 t.Errorf("Error = %#v, want %#v", tc.err, tc.otherError)
1922 }
1923 })
1924 }
1925 }
1926
1927 func TestAbuseRateLimitError_Is(t *testing.T) {
1928 t1 := 1 * time.Second
1929 t2 := 2 * time.Second
1930 err := &AbuseRateLimitError{
1931 Response: &http.Response{},
1932 Message: "Github",
1933 RetryAfter: &t1,
1934 }
1935 testcases := map[string]struct {
1936 wantSame bool
1937 err *AbuseRateLimitError
1938 otherError error
1939 }{
1940 "errors are same": {
1941 wantSame: true,
1942 err: err,
1943 otherError: &AbuseRateLimitError{
1944 Response: &http.Response{},
1945 Message: "Github",
1946 RetryAfter: &t1,
1947 },
1948 },
1949 "errors are same - Response is nil": {
1950 wantSame: true,
1951 err: &AbuseRateLimitError{
1952 Message: "Github",
1953 RetryAfter: &t1,
1954 },
1955 otherError: &AbuseRateLimitError{
1956 Message: "Github",
1957 RetryAfter: &t1,
1958 },
1959 },
1960 "errors have different values - Message": {
1961 wantSame: false,
1962 err: err,
1963 otherError: &AbuseRateLimitError{
1964 Response: &http.Response{},
1965 Message: "Gitlab",
1966 RetryAfter: nil,
1967 },
1968 },
1969 "errors have different values - RetryAfter": {
1970 wantSame: false,
1971 err: err,
1972 otherError: &AbuseRateLimitError{
1973 Response: &http.Response{},
1974 Message: "Github",
1975 RetryAfter: &t2,
1976 },
1977 },
1978 "errors have different values - Response is nil": {
1979 wantSame: false,
1980 err: err,
1981 otherError: &AbuseRateLimitError{
1982 Message: "Github",
1983 RetryAfter: &t1,
1984 },
1985 },
1986 "errors have different values - StatusCode": {
1987 wantSame: false,
1988 err: err,
1989 otherError: &AbuseRateLimitError{
1990 Response: &http.Response{StatusCode: 200},
1991 Message: "Github",
1992 RetryAfter: &t1,
1993 },
1994 },
1995 "errors have different types": {
1996 wantSame: false,
1997 err: err,
1998 otherError: errors.New("Github"),
1999 },
2000 }
2001
2002 for name, tc := range testcases {
2003 t.Run(name, func(t *testing.T) {
2004 if tc.wantSame != tc.err.Is(tc.otherError) {
2005 t.Errorf("Error = %#v, want %#v", tc.err, tc.otherError)
2006 }
2007 })
2008 }
2009 }
2010
2011 func TestAcceptedError_Is(t *testing.T) {
2012 err := &AcceptedError{Raw: []byte("Github")}
2013 testcases := map[string]struct {
2014 wantSame bool
2015 otherError error
2016 }{
2017 "errors are same": {
2018 wantSame: true,
2019 otherError: &AcceptedError{Raw: []byte("Github")},
2020 },
2021 "errors have different values": {
2022 wantSame: false,
2023 otherError: &AcceptedError{Raw: []byte("Gitlab")},
2024 },
2025 "errors have different types": {
2026 wantSame: false,
2027 otherError: errors.New("Github"),
2028 },
2029 }
2030
2031 for name, tc := range testcases {
2032 t.Run(name, func(t *testing.T) {
2033 if tc.wantSame != err.Is(tc.otherError) {
2034 t.Errorf("Error = %#v, want %#v", err, tc.otherError)
2035 }
2036 })
2037 }
2038 }
2039
2040 // ensure that we properly handle API errors that do not contain a response body
2041 func TestCheckResponse_noBody(t *testing.T) {
2042 res := &http.Response{
2043 Request: &http.Request{},
2044 StatusCode: http.StatusBadRequest,
2045 Body: io.NopCloser(strings.NewReader("")),
2046 }
2047 err := CheckResponse(res).(*ErrorResponse)
2048
2049 if err == nil {
2050 t.Errorf("Expected error response.")
2051 }
2052
2053 want := &ErrorResponse{
2054 Response: res,
2055 }
2056 if !errors.Is(err, want) {
2057 t.Errorf("Error = %#v, want %#v", err, want)
2058 }
2059 }
2060
2061 func TestCheckResponse_unexpectedErrorStructure(t *testing.T) {
2062 httpBody := `{"message":"m", "errors": ["error 1"]}`
2063 res := &http.Response{
2064 Request: &http.Request{},
2065 StatusCode: http.StatusBadRequest,
2066 Body: io.NopCloser(strings.NewReader(httpBody)),
2067 }
2068 err := CheckResponse(res).(*ErrorResponse)
2069
2070 if err == nil {
2071 t.Errorf("Expected error response.")
2072 }
2073
2074 want := &ErrorResponse{
2075 Response: res,
2076 Message: "m",
2077 Errors: []Error{{Message: "error 1"}},
2078 }
2079 if !errors.Is(err, want) {
2080 t.Errorf("Error = %#v, want %#v", err, want)
2081 }
2082 data, err2 := io.ReadAll(err.Response.Body)
2083 if err2 != nil {
2084 t.Fatalf("failed to read response body: %v", err)
2085 }
2086 if got := string(data); got != httpBody {
2087 t.Errorf("ErrorResponse.Response.Body = %q, want %q", got, httpBody)
2088 }
2089 }
2090
2091 func TestParseBooleanResponse_true(t *testing.T) {
2092 result, err := parseBoolResponse(nil)
2093 if err != nil {
2094 t.Errorf("parseBoolResponse returned error: %+v", err)
2095 }
2096
2097 if want := true; result != want {
2098 t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
2099 }
2100 }
2101
2102 func TestParseBooleanResponse_false(t *testing.T) {
2103 v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusNotFound}}
2104 result, err := parseBoolResponse(v)
2105 if err != nil {
2106 t.Errorf("parseBoolResponse returned error: %+v", err)
2107 }
2108
2109 if want := false; result != want {
2110 t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
2111 }
2112 }
2113
2114 func TestParseBooleanResponse_error(t *testing.T) {
2115 v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusBadRequest}}
2116 result, err := parseBoolResponse(v)
2117
2118 if err == nil {
2119 t.Errorf("Expected error to be returned.")
2120 }
2121
2122 if want := false; result != want {
2123 t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
2124 }
2125 }
2126
2127 func TestErrorResponse_Error(t *testing.T) {
2128 res := &http.Response{Request: &http.Request{}}
2129 err := ErrorResponse{Message: "m", Response: res}
2130 if err.Error() == "" {
2131 t.Errorf("Expected non-empty ErrorResponse.Error()")
2132 }
2133
2134 //dont panic if request is nil
2135 res = &http.Response{}
2136 err = ErrorResponse{Message: "m", Response: res}
2137 if err.Error() == "" {
2138 t.Errorf("Expected non-empty ErrorResponse.Error()")
2139 }
2140
2141 //dont panic if response is nil
2142 err = ErrorResponse{Message: "m"}
2143 if err.Error() == "" {
2144 t.Errorf("Expected non-empty ErrorResponse.Error()")
2145 }
2146 }
2147
2148 func TestError_Error(t *testing.T) {
2149 err := Error{}
2150 if err.Error() == "" {
2151 t.Errorf("Expected non-empty Error.Error()")
2152 }
2153 }
2154
2155 func TestSetCredentialsAsHeaders(t *testing.T) {
2156 req := new(http.Request)
2157 id, secret := "id", "secret"
2158 modifiedRequest := setCredentialsAsHeaders(req, id, secret)
2159
2160 actualID, actualSecret, ok := modifiedRequest.BasicAuth()
2161 if !ok {
2162 t.Errorf("request does not contain basic credentials")
2163 }
2164
2165 if actualID != id {
2166 t.Errorf("id is %s, want %s", actualID, id)
2167 }
2168
2169 if actualSecret != secret {
2170 t.Errorf("secret is %s, want %s", actualSecret, secret)
2171 }
2172 }
2173
2174 func TestUnauthenticatedRateLimitedTransport(t *testing.T) {
2175 client, mux, _, teardown := setup()
2176 defer teardown()
2177
2178 clientID, clientSecret := "id", "secret"
2179 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2180 id, secret, ok := r.BasicAuth()
2181 if !ok {
2182 t.Errorf("request does not contain basic auth credentials")
2183 }
2184 if id != clientID {
2185 t.Errorf("request contained basic auth username %q, want %q", id, clientID)
2186 }
2187 if secret != clientSecret {
2188 t.Errorf("request contained basic auth password %q, want %q", secret, clientSecret)
2189 }
2190 })
2191
2192 tp := &UnauthenticatedRateLimitedTransport{
2193 ClientID: clientID,
2194 ClientSecret: clientSecret,
2195 }
2196 unauthedClient := NewClient(tp.Client())
2197 unauthedClient.BaseURL = client.BaseURL
2198 req, _ := unauthedClient.NewRequest("GET", ".", nil)
2199 ctx := context.Background()
2200 _, err := unauthedClient.Do(ctx, req, nil)
2201 assertNilError(t, err)
2202 }
2203
2204 func TestUnauthenticatedRateLimitedTransport_missingFields(t *testing.T) {
2205 // missing ClientID
2206 tp := &UnauthenticatedRateLimitedTransport{
2207 ClientSecret: "secret",
2208 }
2209 _, err := tp.RoundTrip(nil)
2210 if err == nil {
2211 t.Errorf("Expected error to be returned")
2212 }
2213
2214 // missing ClientSecret
2215 tp = &UnauthenticatedRateLimitedTransport{
2216 ClientID: "id",
2217 }
2218 _, err = tp.RoundTrip(nil)
2219 if err == nil {
2220 t.Errorf("Expected error to be returned")
2221 }
2222 }
2223
2224 func TestUnauthenticatedRateLimitedTransport_transport(t *testing.T) {
2225 // default transport
2226 tp := &UnauthenticatedRateLimitedTransport{
2227 ClientID: "id",
2228 ClientSecret: "secret",
2229 }
2230 if tp.transport() != http.DefaultTransport {
2231 t.Errorf("Expected http.DefaultTransport to be used.")
2232 }
2233
2234 // custom transport
2235 tp = &UnauthenticatedRateLimitedTransport{
2236 ClientID: "id",
2237 ClientSecret: "secret",
2238 Transport: &http.Transport{},
2239 }
2240 if tp.transport() == http.DefaultTransport {
2241 t.Errorf("Expected custom transport to be used.")
2242 }
2243 }
2244
2245 func TestBasicAuthTransport(t *testing.T) {
2246 client, mux, _, teardown := setup()
2247 defer teardown()
2248
2249 username, password, otp := "u", "p", "123456"
2250
2251 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2252 u, p, ok := r.BasicAuth()
2253 if !ok {
2254 t.Errorf("request does not contain basic auth credentials")
2255 }
2256 if u != username {
2257 t.Errorf("request contained basic auth username %q, want %q", u, username)
2258 }
2259 if p != password {
2260 t.Errorf("request contained basic auth password %q, want %q", p, password)
2261 }
2262 if got, want := r.Header.Get(headerOTP), otp; got != want {
2263 t.Errorf("request contained OTP %q, want %q", got, want)
2264 }
2265 })
2266
2267 tp := &BasicAuthTransport{
2268 Username: username,
2269 Password: password,
2270 OTP: otp,
2271 }
2272 basicAuthClient := NewClient(tp.Client())
2273 basicAuthClient.BaseURL = client.BaseURL
2274 req, _ := basicAuthClient.NewRequest("GET", ".", nil)
2275 ctx := context.Background()
2276 _, err := basicAuthClient.Do(ctx, req, nil)
2277 assertNilError(t, err)
2278 }
2279
2280 func TestBasicAuthTransport_transport(t *testing.T) {
2281 // default transport
2282 tp := &BasicAuthTransport{}
2283 if tp.transport() != http.DefaultTransport {
2284 t.Errorf("Expected http.DefaultTransport to be used.")
2285 }
2286
2287 // custom transport
2288 tp = &BasicAuthTransport{
2289 Transport: &http.Transport{},
2290 }
2291 if tp.transport() == http.DefaultTransport {
2292 t.Errorf("Expected custom transport to be used.")
2293 }
2294 }
2295
2296 func TestFormatRateReset(t *testing.T) {
2297 d := 120*time.Minute + 12*time.Second
2298 got := formatRateReset(d)
2299 want := "[rate reset in 120m12s]"
2300 if got != want {
2301 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2302 }
2303
2304 d = 14*time.Minute + 2*time.Second
2305 got = formatRateReset(d)
2306 want = "[rate reset in 14m02s]"
2307 if got != want {
2308 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2309 }
2310
2311 d = 2*time.Minute + 2*time.Second
2312 got = formatRateReset(d)
2313 want = "[rate reset in 2m02s]"
2314 if got != want {
2315 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2316 }
2317
2318 d = 12 * time.Second
2319 got = formatRateReset(d)
2320 want = "[rate reset in 12s]"
2321 if got != want {
2322 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2323 }
2324
2325 d = -1 * (2*time.Hour + 2*time.Second)
2326 got = formatRateReset(d)
2327 want = "[rate limit was reset 120m02s ago]"
2328 if got != want {
2329 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2330 }
2331 }
2332
2333 func TestNestedStructAccessorNoPanic(t *testing.T) {
2334 issue := &Issue{User: nil}
2335 got := issue.GetUser().GetPlan().GetName()
2336 want := ""
2337 if got != want {
2338 t.Errorf("Issues.Get.GetUser().GetPlan().GetName() returned %+v, want %+v", got, want)
2339 }
2340 }
2341
2342 func TestTwoFactorAuthError(t *testing.T) {
2343 u, err := url.Parse("https://example.com")
2344 if err != nil {
2345 t.Fatal(err)
2346 }
2347
2348 e := &TwoFactorAuthError{
2349 Response: &http.Response{
2350 Request: &http.Request{Method: "PUT", URL: u},
2351 StatusCode: http.StatusTooManyRequests,
2352 },
2353 Message: "<msg>",
2354 }
2355 if got, want := e.Error(), "PUT https://example.com: 429 <msg> []"; got != want {
2356 t.Errorf("TwoFactorAuthError = %q, want %q", got, want)
2357 }
2358 }
2359
2360 func TestRateLimitError(t *testing.T) {
2361 u, err := url.Parse("https://example.com")
2362 if err != nil {
2363 t.Fatal(err)
2364 }
2365
2366 r := &RateLimitError{
2367 Response: &http.Response{
2368 Request: &http.Request{Method: "PUT", URL: u},
2369 StatusCode: http.StatusTooManyRequests,
2370 },
2371 Message: "<msg>",
2372 }
2373 if got, want := r.Error(), "PUT https://example.com: 429 <msg> [rate limit was reset"; !strings.Contains(got, want) {
2374 t.Errorf("RateLimitError = %q, want %q", got, want)
2375 }
2376 }
2377
2378 func TestAcceptedError(t *testing.T) {
2379 a := &AcceptedError{}
2380 if got, want := a.Error(), "try again later"; !strings.Contains(got, want) {
2381 t.Errorf("AcceptedError = %q, want %q", got, want)
2382 }
2383 }
2384
2385 func TestAbuseRateLimitError(t *testing.T) {
2386 u, err := url.Parse("https://example.com")
2387 if err != nil {
2388 t.Fatal(err)
2389 }
2390
2391 r := &AbuseRateLimitError{
2392 Response: &http.Response{
2393 Request: &http.Request{Method: "PUT", URL: u},
2394 StatusCode: http.StatusTooManyRequests,
2395 },
2396 Message: "<msg>",
2397 }
2398 if got, want := r.Error(), "PUT https://example.com: 429 <msg>"; got != want {
2399 t.Errorf("AbuseRateLimitError = %q, want %q", got, want)
2400 }
2401 }
2402
2403 func TestAddOptions_QueryValues(t *testing.T) {
2404 if _, err := addOptions("yo", ""); err == nil {
2405 t.Error("addOptions err = nil, want error")
2406 }
2407 }
2408
2409 func TestBareDo_returnsOpenBody(t *testing.T) {
2410 client, mux, _, teardown := setup()
2411 defer teardown()
2412
2413 expectedBody := "Hello from the other side !"
2414
2415 mux.HandleFunc("/test-url", func(w http.ResponseWriter, r *http.Request) {
2416 testMethod(t, r, "GET")
2417 fmt.Fprint(w, expectedBody)
2418 })
2419
2420 ctx := context.Background()
2421 req, err := client.NewRequest("GET", "test-url", nil)
2422 if err != nil {
2423 t.Fatalf("client.NewRequest returned error: %v", err)
2424 }
2425
2426 resp, err := client.BareDo(ctx, req)
2427 if err != nil {
2428 t.Fatalf("client.BareDo returned error: %v", err)
2429 }
2430
2431 got, err := io.ReadAll(resp.Body)
2432 if err != nil {
2433 t.Fatalf("io.ReadAll returned error: %v", err)
2434 }
2435 if string(got) != expectedBody {
2436 t.Fatalf("Expected %q, got %q", expectedBody, string(got))
2437 }
2438 if err := resp.Body.Close(); err != nil {
2439 t.Fatalf("resp.Body.Close() returned error: %v", err)
2440 }
2441 }
2442
2443 func TestErrorResponse_Marshal(t *testing.T) {
2444 testJSONMarshal(t, &ErrorResponse{}, "{}")
2445
2446 u := &ErrorResponse{
2447 Message: "msg",
2448 Errors: []Error{
2449 {
2450 Resource: "res",
2451 Field: "f",
2452 Code: "c",
2453 Message: "msg",
2454 },
2455 },
2456 Block: &ErrorBlock{
2457 Reason: "reason",
2458 CreatedAt: &Timestamp{referenceTime},
2459 },
2460 DocumentationURL: "doc",
2461 }
2462
2463 want := `{
2464 "message": "msg",
2465 "errors": [
2466 {
2467 "resource": "res",
2468 "field": "f",
2469 "code": "c",
2470 "message": "msg"
2471 }
2472 ],
2473 "block": {
2474 "reason": "reason",
2475 "created_at": ` + referenceTimeStr + `
2476 },
2477 "documentation_url": "doc"
2478 }`
2479
2480 testJSONMarshal(t, u, want)
2481 }
2482
2483 func TestErrorBlock_Marshal(t *testing.T) {
2484 testJSONMarshal(t, &ErrorBlock{}, "{}")
2485
2486 u := &ErrorBlock{
2487 Reason: "reason",
2488 CreatedAt: &Timestamp{referenceTime},
2489 }
2490
2491 want := `{
2492 "reason": "reason",
2493 "created_at": ` + referenceTimeStr + `
2494 }`
2495
2496 testJSONMarshal(t, u, want)
2497 }
2498
2499 func TestRateLimitError_Marshal(t *testing.T) {
2500 testJSONMarshal(t, &RateLimitError{}, "{}")
2501
2502 u := &RateLimitError{
2503 Rate: Rate{
2504 Limit: 1,
2505 Remaining: 1,
2506 Reset: Timestamp{referenceTime},
2507 },
2508 Message: "msg",
2509 }
2510
2511 want := `{
2512 "Rate": {
2513 "limit": 1,
2514 "remaining": 1,
2515 "reset": ` + referenceTimeStr + `
2516 },
2517 "message": "msg"
2518 }`
2519
2520 testJSONMarshal(t, u, want)
2521 }
2522
2523 func TestAbuseRateLimitError_Marshal(t *testing.T) {
2524 testJSONMarshal(t, &AbuseRateLimitError{}, "{}")
2525
2526 u := &AbuseRateLimitError{
2527 Message: "msg",
2528 }
2529
2530 want := `{
2531 "message": "msg"
2532 }`
2533
2534 testJSONMarshal(t, u, want)
2535 }
2536
2537 func TestError_Marshal(t *testing.T) {
2538 testJSONMarshal(t, &Error{}, "{}")
2539
2540 u := &Error{
2541 Resource: "res",
2542 Field: "field",
2543 Code: "code",
2544 Message: "msg",
2545 }
2546
2547 want := `{
2548 "resource": "res",
2549 "field": "field",
2550 "code": "code",
2551 "message": "msg"
2552 }`
2553
2554 testJSONMarshal(t, u, want)
2555 }
2556
2557 func TestParseTokenExpiration(t *testing.T) {
2558 tests := []struct {
2559 header string
2560 want Timestamp
2561 }{
2562 {
2563 header: "",
2564 want: Timestamp{},
2565 },
2566 {
2567 header: "this is a garbage",
2568 want: Timestamp{},
2569 },
2570 {
2571 header: "2021-09-03 02:34:04 UTC",
2572 want: Timestamp{time.Date(2021, time.September, 3, 2, 34, 4, 0, time.UTC)},
2573 },
2574 {
2575 header: "2021-09-03 14:34:04 UTC",
2576 want: Timestamp{time.Date(2021, time.September, 3, 14, 34, 4, 0, time.UTC)},
2577 },
2578 // Some tokens include the timezone offset instead of the timezone.
2579 // https://github.com/google/go-github/issues/2649
2580 {
2581 header: "2023-04-26 20:23:26 +0200",
2582 want: Timestamp{time.Date(2023, time.April, 26, 18, 23, 26, 0, time.UTC)},
2583 },
2584 }
2585
2586 for _, tt := range tests {
2587 res := &http.Response{
2588 Request: &http.Request{},
2589 Header: http.Header{},
2590 }
2591
2592 res.Header.Set(headerTokenExpiration, tt.header)
2593 exp := parseTokenExpiration(res)
2594 if !exp.Equal(tt.want) {
2595 t.Errorf("parseTokenExpiration of %q\nreturned %#v\n want %#v", tt.header, exp, tt.want)
2596 }
2597 }
2598 }
2599
2600 func TestClientCopy_leak_transport(t *testing.T) {
2601 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2602 w.Header().Set("Content-Type", "application/json")
2603 accessToken := r.Header.Get("Authorization")
2604 _, _ = fmt.Fprintf(w, `{"login": "%s"}`, accessToken)
2605 }))
2606 clientPreconfiguredWithURLs, err := NewClient(nil).WithEnterpriseURLs(srv.URL, srv.URL)
2607 if err != nil {
2608 t.Fatal(err)
2609 }
2610
2611 aliceClient := clientPreconfiguredWithURLs.WithAuthToken("alice")
2612 bobClient := clientPreconfiguredWithURLs.WithAuthToken("bob")
2613
2614 alice, _, err := aliceClient.Users.Get(context.Background(), "")
2615 if err != nil {
2616 t.Fatal(err)
2617 }
2618
2619 assertNoDiff(t, "Bearer alice", alice.GetLogin())
2620
2621 bob, _, err := bobClient.Users.Get(context.Background(), "")
2622 if err != nil {
2623 t.Fatal(err)
2624 }
2625
2626 assertNoDiff(t, "Bearer bob", bob.GetLogin())
2627 }