Debian Codegraph @

github/github_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 A map[interface{}]interface{}
543 }
544 _, err := c.NewRequest("GET", ".", &T{})
545
546 if err == nil {
547 t.Error("Expected error to be returned.")
548 }
549 if err, ok := err.(*json.UnsupportedTypeError); !ok {
550 t.Errorf("Expected a JSON error; got %#v.", err)
551 }
552 }
553
554 func TestNewRequest_badURL(t *testing.T) {
555 c := NewClient(nil)
556 _, err := c.NewRequest("GET", ":", nil)
557 testURLParseError(t, err)
558 }
559
560 func TestNewRequest_badMethod(t *testing.T) {
561 c := NewClient(nil)
562 if _, err := c.NewRequest("BOGUS\nMETHOD", ".", nil); err == nil {
563 t.Fatal("NewRequest returned nil; expected error")
564 }
565 }
566
567 // ensure that no User-Agent header is set if the client's UserAgent is empty.
568 // This caused a problem with Google's internal http client.
569 func TestNewRequest_emptyUserAgent(t *testing.T) {
570 c := NewClient(nil)
571 c.UserAgent = ""
572 req, err := c.NewRequest("GET", ".", nil)
573 if err != nil {
574 t.Fatalf("NewRequest returned unexpected error: %v", err)
575 }
576 if _, ok := req.Header["User-Agent"]; ok {
577 t.Fatal("constructed request contains unexpected User-Agent header")
578 }
579 }
580
581 // If a nil body is passed to github.NewRequest, make sure that nil is also
582 // passed to http.NewRequest. In most cases, passing an io.Reader that returns
583 // no content is fine, since there is no difference between an HTTP request
584 // body that is an empty string versus one that is not set at all. However in
585 // certain cases, intermediate systems may treat these differently resulting in
586 // subtle errors.
587 func TestNewRequest_emptyBody(t *testing.T) {
588 c := NewClient(nil)
589 req, err := c.NewRequest("GET", ".", nil)
590 if err != nil {
591 t.Fatalf("NewRequest returned unexpected error: %v", err)
592 }
593 if req.Body != nil {
594 t.Fatalf("constructed request contains a non-nil Body")
595 }
596 }
597
598 func TestNewRequest_errorForNoTrailingSlash(t *testing.T) {
599 tests := []struct {
600 rawurl string
601 wantError bool
602 }{
603 {rawurl: "https://example.com/api/v3", wantError: true},
604 {rawurl: "https://example.com/api/v3/", wantError: false},
605 }
606 c := NewClient(nil)
607 for _, test := range tests {
608 u, err := url.Parse(test.rawurl)
609 if err != nil {
610 t.Fatalf("url.Parse returned unexpected error: %v.", err)
611 }
612 c.BaseURL = u
613 if _, err := c.NewRequest(http.MethodGet, "test", nil); test.wantError && err == nil {
614 t.Fatalf("Expected error to be returned.")
615 } else if !test.wantError && err != nil {
616 t.Fatalf("NewRequest returned unexpected error: %v.", err)
617 }
618 }
619 }
620
621 func TestNewFormRequest(t *testing.T) {
622 c := NewClient(nil)
623
624 inURL, outURL := "/foo", defaultBaseURL+"foo"
625 form := url.Values{}
626 form.Add("login", "l")
627 inBody, outBody := strings.NewReader(form.Encode()), "login=l"
628 req, _ := c.NewFormRequest(inURL, inBody)
629
630 // test that relative URL was expanded
631 if got, want := req.URL.String(), outURL; got != want {
632 t.Errorf("NewFormRequest(%q) URL is %v, want %v", inURL, got, want)
633 }
634
635 // test that body was form encoded
636 body, _ := io.ReadAll(req.Body)
637 if got, want := string(body), outBody; got != want {
638 t.Errorf("NewFormRequest(%q) Body is %v, want %v", inBody, got, want)
639 }
640
641 // test that default user-agent is attached to the request
642 if got, want := req.Header.Get("User-Agent"), c.UserAgent; got != want {
643 t.Errorf("NewFormRequest() User-Agent is %v, want %v", got, want)
644 }
645
646 apiVersion := req.Header.Get(headerAPIVersion)
647 if got, want := apiVersion, defaultAPIVersion; got != want {
648 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
649 }
650
651 req, _ = c.NewFormRequest(inURL, inBody, WithVersion("2022-11-29"))
652 apiVersion = req.Header.Get(headerAPIVersion)
653 if got, want := apiVersion, "2022-11-29"; got != want {
654 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
655 }
656 }
657
658 func TestNewFormRequest_badURL(t *testing.T) {
659 c := NewClient(nil)
660 _, err := c.NewFormRequest(":", nil)
661 testURLParseError(t, err)
662 }
663
664 func TestNewFormRequest_emptyUserAgent(t *testing.T) {
665 c := NewClient(nil)
666 c.UserAgent = ""
667 req, err := c.NewFormRequest(".", nil)
668 if err != nil {
669 t.Fatalf("NewFormRequest returned unexpected error: %v", err)
670 }
671 if _, ok := req.Header["User-Agent"]; ok {
672 t.Fatal("constructed request contains unexpected User-Agent header")
673 }
674 }
675
676 func TestNewFormRequest_emptyBody(t *testing.T) {
677 c := NewClient(nil)
678 req, err := c.NewFormRequest(".", nil)
679 if err != nil {
680 t.Fatalf("NewFormRequest returned unexpected error: %v", err)
681 }
682 if req.Body != nil {
683 t.Fatalf("constructed request contains a non-nil Body")
684 }
685 }
686
687 func TestNewFormRequest_errorForNoTrailingSlash(t *testing.T) {
688 tests := []struct {
689 rawURL string
690 wantError bool
691 }{
692 {rawURL: "https://example.com/api/v3", wantError: true},
693 {rawURL: "https://example.com/api/v3/", wantError: false},
694 }
695 c := NewClient(nil)
696 for _, test := range tests {
697 u, err := url.Parse(test.rawURL)
698 if err != nil {
699 t.Fatalf("url.Parse returned unexpected error: %v.", err)
700 }
701 c.BaseURL = u
702 if _, err := c.NewFormRequest("test", nil); test.wantError && err == nil {
703 t.Fatalf("Expected error to be returned.")
704 } else if !test.wantError && err != nil {
705 t.Fatalf("NewFormRequest returned unexpected error: %v.", err)
706 }
707 }
708 }
709
710 func TestNewUploadRequest_WithVersion(t *testing.T) {
711 c := NewClient(nil)
712 req, _ := c.NewUploadRequest("https://example.com/", nil, 0, "")
713
714 apiVersion := req.Header.Get(headerAPIVersion)
715 if got, want := apiVersion, defaultAPIVersion; got != want {
716 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
717 }
718
719 req, _ = c.NewUploadRequest("https://example.com/", nil, 0, "", WithVersion("2022-11-29"))
720 apiVersion = req.Header.Get(headerAPIVersion)
721 if got, want := apiVersion, "2022-11-29"; got != want {
722 t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
723 }
724 }
725
726 func TestNewUploadRequest_badURL(t *testing.T) {
727 c := NewClient(nil)
728 _, err := c.NewUploadRequest(":", nil, 0, "")
729 testURLParseError(t, err)
730
731 const methodName = "NewUploadRequest"
732 testBadOptions(t, methodName, func() (err error) {
733 _, err = c.NewUploadRequest("\n", nil, -1, "\n")
734 return err
735 })
736 }
737
738 func TestNewUploadRequest_errorForNoTrailingSlash(t *testing.T) {
739 tests := []struct {
740 rawurl string
741 wantError bool
742 }{
743 {rawurl: "https://example.com/api/uploads", wantError: true},
744 {rawurl: "https://example.com/api/uploads/", wantError: false},
745 }
746 c := NewClient(nil)
747 for _, test := range tests {
748 u, err := url.Parse(test.rawurl)
749 if err != nil {
750 t.Fatalf("url.Parse returned unexpected error: %v.", err)
751 }
752 c.UploadURL = u
753 if _, err = c.NewUploadRequest("test", nil, 0, ""); test.wantError && err == nil {
754 t.Fatalf("Expected error to be returned.")
755 } else if !test.wantError && err != nil {
756 t.Fatalf("NewUploadRequest returned unexpected error: %v.", err)
757 }
758 }
759 }
760
761 func TestResponse_populatePageValues(t *testing.T) {
762 r := http.Response{
763 Header: http.Header{
764 "Link": {`<https://api.github.com/?page=1>; rel="first",` +
765 ` <https://api.github.com/?page=2>; rel="prev",` +
766 ` <https://api.github.com/?page=4>; rel="next",` +
767 ` <https://api.github.com/?page=5>; rel="last"`,
768 },
769 },
770 }
771
772 response := newResponse(&r)
773 if got, want := response.FirstPage, 1; got != want {
774 t.Errorf("response.FirstPage: %v, want %v", got, want)
775 }
776 if got, want := response.PrevPage, 2; want != got {
777 t.Errorf("response.PrevPage: %v, want %v", got, want)
778 }
779 if got, want := response.NextPage, 4; want != got {
780 t.Errorf("response.NextPage: %v, want %v", got, want)
781 }
782 if got, want := response.LastPage, 5; want != got {
783 t.Errorf("response.LastPage: %v, want %v", got, want)
784 }
785 if got, want := response.NextPageToken, ""; want != got {
786 t.Errorf("response.NextPageToken: %v, want %v", got, want)
787 }
788 }
789
790 func TestResponse_populateSinceValues(t *testing.T) {
791 r := http.Response{
792 Header: http.Header{
793 "Link": {`<https://api.github.com/?since=1>; rel="first",` +
794 ` <https://api.github.com/?since=2>; rel="prev",` +
795 ` <https://api.github.com/?since=4>; rel="next",` +
796 ` <https://api.github.com/?since=5>; rel="last"`,
797 },
798 },
799 }
800
801 response := newResponse(&r)
802 if got, want := response.FirstPage, 1; got != want {
803 t.Errorf("response.FirstPage: %v, want %v", got, want)
804 }
805 if got, want := response.PrevPage, 2; want != got {
806 t.Errorf("response.PrevPage: %v, want %v", got, want)
807 }
808 if got, want := response.NextPage, 4; want != got {
809 t.Errorf("response.NextPage: %v, want %v", got, want)
810 }
811 if got, want := response.LastPage, 5; want != got {
812 t.Errorf("response.LastPage: %v, want %v", got, want)
813 }
814 if got, want := response.NextPageToken, ""; want != got {
815 t.Errorf("response.NextPageToken: %v, want %v", got, want)
816 }
817 }
818
819 func TestResponse_SinceWithPage(t *testing.T) {
820 r := http.Response{
821 Header: http.Header{
822 "Link": {`<https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=1>; rel="first",` +
823 ` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=2>; rel="prev",` +
824 ` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=4>; rel="next",` +
825 ` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=5>; rel="last"`,
826 },
827 },
828 }
829
830 response := newResponse(&r)
831 if got, want := response.FirstPage, 1; got != want {
832 t.Errorf("response.FirstPage: %v, want %v", got, want)
833 }
834 if got, want := response.PrevPage, 2; want != got {
835 t.Errorf("response.PrevPage: %v, want %v", got, want)
836 }
837 if got, want := response.NextPage, 4; want != got {
838 t.Errorf("response.NextPage: %v, want %v", got, want)
839 }
840 if got, want := response.LastPage, 5; want != got {
841 t.Errorf("response.LastPage: %v, want %v", got, want)
842 }
843 if got, want := response.NextPageToken, ""; want != got {
844 t.Errorf("response.NextPageToken: %v, want %v", got, want)
845 }
846 }
847
848 func TestResponse_cursorPagination(t *testing.T) {
849 r := http.Response{
850 Header: http.Header{
851 "Status": {"200 OK"},
852 "Link": {`<https://api.github.com/resource?per_page=2&page=url-encoded-next-page-token>; rel="next"`},
853 },
854 }
855
856 response := newResponse(&r)
857 if got, want := response.FirstPage, 0; got != want {
858 t.Errorf("response.FirstPage: %v, want %v", got, want)
859 }
860 if got, want := response.PrevPage, 0; want != got {
861 t.Errorf("response.PrevPage: %v, want %v", got, want)
862 }
863 if got, want := response.NextPage, 0; want != got {
864 t.Errorf("response.NextPage: %v, want %v", got, want)
865 }
866 if got, want := response.LastPage, 0; want != got {
867 t.Errorf("response.LastPage: %v, want %v", got, want)
868 }
869 if got, want := response.NextPageToken, "url-encoded-next-page-token"; want != got {
870 t.Errorf("response.NextPageToken: %v, want %v", got, want)
871 }
872
873 // cursor-based pagination with "cursor" param
874 r = http.Response{
875 Header: http.Header{
876 "Link": {
877 `<https://api.github.com/?cursor=v1_12345678>; rel="next"`,
878 },
879 },
880 }
881
882 response = newResponse(&r)
883 if got, want := response.Cursor, "v1_12345678"; got != want {
884 t.Errorf("response.Cursor: %v, want %v", got, want)
885 }
886 }
887
888 func TestResponse_beforeAfterPagination(t *testing.T) {
889 r := http.Response{
890 Header: http.Header{
891 "Link": {`<https://api.github.com/?after=a1b2c3&before=>; rel="next",` +
892 ` <https://api.github.com/?after=&before=>; rel="first",` +
893 ` <https://api.github.com/?after=&before=d4e5f6>; rel="prev",`,
894 },
895 },
896 }
897
898 response := newResponse(&r)
899 if got, want := response.Before, "d4e5f6"; got != want {
900 t.Errorf("response.Before: %v, want %v", got, want)
901 }
902 if got, want := response.After, "a1b2c3"; got != want {
903 t.Errorf("response.After: %v, want %v", got, want)
904 }
905 if got, want := response.FirstPage, 0; got != want {
906 t.Errorf("response.FirstPage: %v, want %v", got, want)
907 }
908 if got, want := response.PrevPage, 0; want != got {
909 t.Errorf("response.PrevPage: %v, want %v", got, want)
910 }
911 if got, want := response.NextPage, 0; want != got {
912 t.Errorf("response.NextPage: %v, want %v", got, want)
913 }
914 if got, want := response.LastPage, 0; want != got {
915 t.Errorf("response.LastPage: %v, want %v", got, want)
916 }
917 if got, want := response.NextPageToken, ""; want != got {
918 t.Errorf("response.NextPageToken: %v, want %v", got, want)
919 }
920 }
921
922 func TestResponse_populatePageValues_invalid(t *testing.T) {
923 r := http.Response{
924 Header: http.Header{
925 "Link": {`<https://api.github.com/?page=1>,` +
926 `<https://api.github.com/?page=abc>; rel="first",` +
927 `https://api.github.com/?page=2; rel="prev",` +
928 `<https://api.github.com/>; rel="next",` +
929 `<https://api.github.com/?page=>; rel="last"`,
930 },
931 },
932 }
933
934 response := newResponse(&r)
935 if got, want := response.FirstPage, 0; got != want {
936 t.Errorf("response.FirstPage: %v, want %v", got, want)
937 }
938 if got, want := response.PrevPage, 0; got != want {
939 t.Errorf("response.PrevPage: %v, want %v", got, want)
940 }
941 if got, want := response.NextPage, 0; got != want {
942 t.Errorf("response.NextPage: %v, want %v", got, want)
943 }
944 if got, want := response.LastPage, 0; got != want {
945 t.Errorf("response.LastPage: %v, want %v", got, want)
946 }
947
948 // more invalid URLs
949 r = http.Response{
950 Header: http.Header{
951 "Link": {`<https://api.github.com/%?page=2>; rel="first"`},
952 },
953 }
954
955 response = newResponse(&r)
956 if got, want := response.FirstPage, 0; got != want {
957 t.Errorf("response.FirstPage: %v, want %v", got, want)
958 }
959 }
960
961 func TestResponse_populateSinceValues_invalid(t *testing.T) {
962 r := http.Response{
963 Header: http.Header{
964 "Link": {`<https://api.github.com/?since=1>,` +
965 `<https://api.github.com/?since=abc>; rel="first",` +
966 `https://api.github.com/?since=2; rel="prev",` +
967 `<https://api.github.com/>; rel="next",` +
968 `<https://api.github.com/?since=>; rel="last"`,
969 },
970 },
971 }
972
973 response := newResponse(&r)
974 if got, want := response.FirstPage, 0; got != want {
975 t.Errorf("response.FirstPage: %v, want %v", got, want)
976 }
977 if got, want := response.PrevPage, 0; got != want {
978 t.Errorf("response.PrevPage: %v, want %v", got, want)
979 }
980 if got, want := response.NextPage, 0; got != want {
981 t.Errorf("response.NextPage: %v, want %v", got, want)
982 }
983 if got, want := response.LastPage, 0; got != want {
984 t.Errorf("response.LastPage: %v, want %v", got, want)
985 }
986
987 // more invalid URLs
988 r = http.Response{
989 Header: http.Header{
990 "Link": {`<https://api.github.com/%?since=2>; rel="first"`},
991 },
992 }
993
994 response = newResponse(&r)
995 if got, want := response.FirstPage, 0; got != want {
996 t.Errorf("response.FirstPage: %v, want %v", got, want)
997 }
998 }
999
1000 func TestDo(t *testing.T) {
1001 client, mux, _, teardown := setup()
1002 defer teardown()
1003
1004 type foo struct {
1005 A string
1006 }
1007
1008 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1009 testMethod(t, r, "GET")
1010 fmt.Fprint(w, `{"A":"a"}`)
1011 })
1012
1013 req, _ := client.NewRequest("GET", ".", nil)
1014 body := new(foo)
1015 ctx := context.Background()
1016 _, err := client.Do(ctx, req, body)
1017 assertNilError(t, err)
1018
1019 want := &foo{"a"}
1020 if !cmp.Equal(body, want) {
1021 t.Errorf("Response body = %v, want %v", body, want)
1022 }
1023 }
1024
1025 func TestDo_nilContext(t *testing.T) {
1026 client, _, _, teardown := setup()
1027 defer teardown()
1028
1029 req, _ := client.NewRequest("GET", ".", nil)
1030 _, err := client.Do(nil, req, nil)
1031
1032 if !errors.Is(err, errNonNilContext) {
1033 t.Errorf("Expected context must be non-nil error")
1034 }
1035 }
1036
1037 func TestDo_httpError(t *testing.T) {
1038 client, mux, _, teardown := setup()
1039 defer teardown()
1040
1041 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1042 http.Error(w, "Bad Request", 400)
1043 })
1044
1045 req, _ := client.NewRequest("GET", ".", nil)
1046 ctx := context.Background()
1047 resp, err := client.Do(ctx, req, nil)
1048
1049 if err == nil {
1050 t.Fatal("Expected HTTP 400 error, got no error.")
1051 }
1052 if resp.StatusCode != 400 {
1053 t.Errorf("Expected HTTP 400 error, got %d status code.", resp.StatusCode)
1054 }
1055 }
1056
1057 // Test handling of an error caused by the internal http client's Do()
1058 // function. A redirect loop is pretty unlikely to occur within the GitHub
1059 // API, but does allow us to exercise the right code path.
1060 func TestDo_redirectLoop(t *testing.T) {
1061 client, mux, _, teardown := setup()
1062 defer teardown()
1063
1064 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1065 http.Redirect(w, r, baseURLPath, http.StatusFound)
1066 })
1067
1068 req, _ := client.NewRequest("GET", ".", nil)
1069 ctx := context.Background()
1070 _, err := client.Do(ctx, req, nil)
1071
1072 if err == nil {
1073 t.Error("Expected error to be returned.")
1074 }
1075 if err, ok := err.(*url.Error); !ok {
1076 t.Errorf("Expected a URL error; got %#v.", err)
1077 }
1078 }
1079
1080 // Test that an error caused by the internal http client's Do() function
1081 // does not leak the client secret.
1082 func TestDo_sanitizeURL(t *testing.T) {
1083 tp := &UnauthenticatedRateLimitedTransport{
1084 ClientID: "id",
1085 ClientSecret: "secret",
1086 }
1087 unauthedClient := NewClient(tp.Client())
1088 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".
1089 req, err := unauthedClient.NewRequest("GET", ".", nil)
1090 if err != nil {
1091 t.Fatalf("NewRequest returned unexpected error: %v", err)
1092 }
1093 ctx := context.Background()
1094 _, err = unauthedClient.Do(ctx, req, nil)
1095 if err == nil {
1096 t.Fatal("Expected error to be returned.")
1097 }
1098 if strings.Contains(err.Error(), "client_secret=secret") {
1099 t.Errorf("Do error contains secret, should be redacted:\n%q", err)
1100 }
1101 }
1102
1103 func TestDo_rateLimit(t *testing.T) {
1104 client, mux, _, teardown := setup()
1105 defer teardown()
1106
1107 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1108 w.Header().Set(headerRateLimit, "60")
1109 w.Header().Set(headerRateRemaining, "59")
1110 w.Header().Set(headerRateReset, "1372700873")
1111 })
1112
1113 req, _ := client.NewRequest("GET", ".", nil)
1114 ctx := context.Background()
1115 resp, err := client.Do(ctx, req, nil)
1116 if err != nil {
1117 t.Errorf("Do returned unexpected error: %v", err)
1118 }
1119 if got, want := resp.Rate.Limit, 60; got != want {
1120 t.Errorf("Client rate limit = %v, want %v", got, want)
1121 }
1122 if got, want := resp.Rate.Remaining, 59; got != want {
1123 t.Errorf("Client rate remaining = %v, want %v", got, want)
1124 }
1125 reset := time.Date(2013, time.July, 1, 17, 47, 53, 0, time.UTC)
1126 if resp.Rate.Reset.UTC() != reset {
1127 t.Errorf("Client rate reset = %v, want %v", resp.Rate.Reset, reset)
1128 }
1129 }
1130
1131 func TestDo_rateLimitCategory(t *testing.T) {
1132 tests := []struct {
1133 method string
1134 url string
1135 category rateLimitCategory
1136 }{
1137 {
1138 method: http.MethodGet,
1139 url: "/",
1140 category: coreCategory,
1141 },
1142 {
1143 method: http.MethodGet,
1144 url: "/search/issues?q=rate",
1145 category: searchCategory,
1146 },
1147 {
1148 method: http.MethodGet,
1149 url: "/graphql",
1150 category: graphqlCategory,
1151 },
1152 {
1153 method: http.MethodPost,
1154 url: "/app-manifests/code/conversions",
1155 category: integrationManifestCategory,
1156 },
1157 {
1158 method: http.MethodGet,
1159 url: "/app-manifests/code/conversions",
1160 category: coreCategory, // only POST requests are in the integration manifest category
1161 },
1162 {
1163 method: http.MethodPut,
1164 url: "/repos/google/go-github/import",
1165 category: sourceImportCategory,
1166 },
1167 {
1168 method: http.MethodGet,
1169 url: "/repos/google/go-github/import",
1170 category: coreCategory, // only PUT requests are in the source import category
1171 },
1172 {
1173 method: http.MethodPost,
1174 url: "/repos/google/go-github/code-scanning/sarifs",
1175 category: codeScanningUploadCategory,
1176 },
1177 {
1178 method: http.MethodGet,
1179 url: "/scim/v2/organizations/ORG/Users",
1180 category: scimCategory,
1181 },
1182 {
1183 method: http.MethodPost,
1184 url: "/repos/google/go-github/dependency-graph/snapshots",
1185 category: dependencySnapshotsCategory,
1186 },
1187 {
1188 method: http.MethodGet,
1189 url: "/search/code?q=rate",
1190 category: codeSearchCategory,
1191 },
1192 // missing a check for actionsRunnerRegistrationCategory: API not found
1193 }
1194
1195 for _, tt := range tests {
1196 if got, want := category(tt.method, tt.url), tt.category; got != want {
1197 t.Errorf("expecting category %v, found %v", got, want)
1198 }
1199 }
1200 }
1201
1202 // ensure rate limit is still parsed, even for error responses
1203 func TestDo_rateLimit_errorResponse(t *testing.T) {
1204 client, mux, _, teardown := setup()
1205 defer teardown()
1206
1207 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1208 w.Header().Set(headerRateLimit, "60")
1209 w.Header().Set(headerRateRemaining, "59")
1210 w.Header().Set(headerRateReset, "1372700873")
1211 http.Error(w, "Bad Request", 400)
1212 })
1213
1214 req, _ := client.NewRequest("GET", ".", nil)
1215 ctx := context.Background()
1216 resp, err := client.Do(ctx, req, nil)
1217 if err == nil {
1218 t.Error("Expected error to be returned.")
1219 }
1220 if _, ok := err.(*RateLimitError); ok {
1221 t.Errorf("Did not expect a *RateLimitError error; got %#v.", err)
1222 }
1223 if got, want := resp.Rate.Limit, 60; got != want {
1224 t.Errorf("Client rate limit = %v, want %v", got, want)
1225 }
1226 if got, want := resp.Rate.Remaining, 59; got != want {
1227 t.Errorf("Client rate remaining = %v, want %v", got, want)
1228 }
1229 reset := time.Date(2013, time.July, 1, 17, 47, 53, 0, time.UTC)
1230 if resp.Rate.Reset.UTC() != reset {
1231 t.Errorf("Client rate reset = %v, want %v", resp.Rate.Reset, reset)
1232 }
1233 }
1234
1235 // Ensure *RateLimitError is returned when API rate limit is exceeded.
1236 func TestDo_rateLimit_rateLimitError(t *testing.T) {
1237 client, mux, _, teardown := setup()
1238 defer teardown()
1239
1240 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1241 w.Header().Set(headerRateLimit, "60")
1242 w.Header().Set(headerRateRemaining, "0")
1243 w.Header().Set(headerRateReset, "1372700873")
1244 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1245 w.WriteHeader(http.StatusForbidden)
1246 fmt.Fprintln(w, `{
1247 "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.)",
1248 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1249 }`)
1250 })
1251
1252 req, _ := client.NewRequest("GET", ".", nil)
1253 ctx := context.Background()
1254 _, err := client.Do(ctx, req, nil)
1255
1256 if err == nil {
1257 t.Error("Expected error to be returned.")
1258 }
1259 rateLimitErr, ok := err.(*RateLimitError)
1260 if !ok {
1261 t.Fatalf("Expected a *RateLimitError error; got %#v.", err)
1262 }
1263 if got, want := rateLimitErr.Rate.Limit, 60; got != want {
1264 t.Errorf("rateLimitErr rate limit = %v, want %v", got, want)
1265 }
1266 if got, want := rateLimitErr.Rate.Remaining, 0; got != want {
1267 t.Errorf("rateLimitErr rate remaining = %v, want %v", got, want)
1268 }
1269 reset := time.Date(2013, time.July, 1, 17, 47, 53, 0, time.UTC)
1270 if rateLimitErr.Rate.Reset.UTC() != reset {
1271 t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset)
1272 }
1273 }
1274
1275 // Ensure a network call is not made when it's known that API rate limit is still exceeded.
1276 func TestDo_rateLimit_noNetworkCall(t *testing.T) {
1277 client, mux, _, teardown := setup()
1278 defer teardown()
1279
1280 reset := time.Now().UTC().Add(time.Minute).Round(time.Second) // Rate reset is a minute from now, with 1 second precision.
1281
1282 mux.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) {
1283 w.Header().Set(headerRateLimit, "60")
1284 w.Header().Set(headerRateRemaining, "0")
1285 w.Header().Set(headerRateReset, fmt.Sprint(reset.Unix()))
1286 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1287 w.WriteHeader(http.StatusForbidden)
1288 fmt.Fprintln(w, `{
1289 "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.)",
1290 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1291 }`)
1292 })
1293
1294 madeNetworkCall := false
1295 mux.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) {
1296 madeNetworkCall = true
1297 })
1298
1299 // First request is made, and it makes the client aware of rate reset time being in the future.
1300 req, _ := client.NewRequest("GET", "first", nil)
1301 ctx := context.Background()
1302 _, err := client.Do(ctx, req, nil)
1303 if err == nil {
1304 t.Error("Expected error to be returned.")
1305 }
1306
1307 // Second request should not cause a network call to be made, since client can predict a rate limit error.
1308 req, _ = client.NewRequest("GET", "second", nil)
1309 _, err = client.Do(ctx, req, nil)
1310
1311 if madeNetworkCall {
1312 t.Fatal("Network call was made, even though rate limit is known to still be exceeded.")
1313 }
1314
1315 if err == nil {
1316 t.Error("Expected error to be returned.")
1317 }
1318 rateLimitErr, ok := err.(*RateLimitError)
1319 if !ok {
1320 t.Fatalf("Expected a *RateLimitError error; got %#v.", err)
1321 }
1322 if got, want := rateLimitErr.Rate.Limit, 60; got != want {
1323 t.Errorf("rateLimitErr rate limit = %v, want %v", got, want)
1324 }
1325 if got, want := rateLimitErr.Rate.Remaining, 0; got != want {
1326 t.Errorf("rateLimitErr rate remaining = %v, want %v", got, want)
1327 }
1328 if rateLimitErr.Rate.Reset.UTC() != reset {
1329 t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset)
1330 }
1331 }
1332
1333 // Ignore rate limit headers if the response was served from cache.
1334 func TestDo_rateLimit_ignoredFromCache(t *testing.T) {
1335 client, mux, _, teardown := setup()
1336 defer teardown()
1337
1338 reset := time.Now().UTC().Add(time.Minute).Round(time.Second) // Rate reset is a minute from now, with 1 second precision.
1339
1340 // By adding the X-From-Cache header we pretend this is served from a cache.
1341 mux.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) {
1342 w.Header().Set("X-From-Cache", "1")
1343 w.Header().Set(headerRateLimit, "60")
1344 w.Header().Set(headerRateRemaining, "0")
1345 w.Header().Set(headerRateReset, fmt.Sprint(reset.Unix()))
1346 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1347 w.WriteHeader(http.StatusForbidden)
1348 fmt.Fprintln(w, `{
1349 "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.)",
1350 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1351 }`)
1352 })
1353
1354 madeNetworkCall := false
1355 mux.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) {
1356 madeNetworkCall = true
1357 })
1358
1359 // First request is made so afterwards we can check the returned rate limit headers were ignored.
1360 req, _ := client.NewRequest("GET", "first", nil)
1361 ctx := context.Background()
1362 _, err := client.Do(ctx, req, nil)
1363 if err == nil {
1364 t.Error("Expected error to be returned.")
1365 }
1366
1367 // Second request should not by hindered by rate limits.
1368 req, _ = client.NewRequest("GET", "second", nil)
1369 _, err = client.Do(ctx, req, nil)
1370
1371 if err != nil {
1372 t.Fatalf("Second request failed, even though the rate limits from the cache should've been ignored: %v", err)
1373 }
1374 if !madeNetworkCall {
1375 t.Fatal("Network call was not made, even though the rate limits from the cache should've been ignored")
1376 }
1377 }
1378
1379 // Ensure *AbuseRateLimitError is returned when the response indicates that
1380 // the client has triggered an abuse detection mechanism.
1381 func TestDo_rateLimit_abuseRateLimitError(t *testing.T) {
1382 client, mux, _, teardown := setup()
1383 defer teardown()
1384
1385 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1386 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1387 w.WriteHeader(http.StatusForbidden)
1388 // When the abuse rate limit error is of the "temporarily blocked from content creation" type,
1389 // there is no "Retry-After" header.
1390 fmt.Fprintln(w, `{
1391 "message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.",
1392 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1393 }`)
1394 })
1395
1396 req, _ := client.NewRequest("GET", ".", nil)
1397 ctx := context.Background()
1398 _, err := client.Do(ctx, req, nil)
1399
1400 if err == nil {
1401 t.Error("Expected error to be returned.")
1402 }
1403 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1404 if !ok {
1405 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1406 }
1407 if got, want := abuseRateLimitErr.RetryAfter, (*time.Duration)(nil); got != want {
1408 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1409 }
1410 }
1411
1412 // Ensure *AbuseRateLimitError is returned when the response indicates that
1413 // the client has triggered an abuse detection mechanism on GitHub Enterprise.
1414 func TestDo_rateLimit_abuseRateLimitErrorEnterprise(t *testing.T) {
1415 client, mux, _, teardown := setup()
1416 defer teardown()
1417
1418 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1419 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1420 w.WriteHeader(http.StatusForbidden)
1421 // When the abuse rate limit error is of the "temporarily blocked from content creation" type,
1422 // there is no "Retry-After" header.
1423 // This response returns a documentation url like the one returned for GitHub Enterprise, this
1424 // url changes between versions but follows roughly the same format.
1425 fmt.Fprintln(w, `{
1426 "message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.",
1427 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1428 }`)
1429 })
1430
1431 req, _ := client.NewRequest("GET", ".", nil)
1432 ctx := context.Background()
1433 _, err := client.Do(ctx, req, nil)
1434
1435 if err == nil {
1436 t.Error("Expected error to be returned.")
1437 }
1438 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1439 if !ok {
1440 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1441 }
1442 if got, want := abuseRateLimitErr.RetryAfter, (*time.Duration)(nil); got != want {
1443 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1444 }
1445 }
1446
1447 // Ensure *AbuseRateLimitError.RetryAfter is parsed correctly for the Retry-After header.
1448 func TestDo_rateLimit_abuseRateLimitError_retryAfter(t *testing.T) {
1449 client, mux, _, teardown := setup()
1450 defer teardown()
1451
1452 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1453 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1454 w.Header().Set(headerRetryAfter, "123") // Retry after value of 123 seconds.
1455 w.WriteHeader(http.StatusForbidden)
1456 fmt.Fprintln(w, `{
1457 "message": "You have triggered an abuse detection mechanism ...",
1458 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1459 }`)
1460 })
1461
1462 req, _ := client.NewRequest("GET", ".", nil)
1463 ctx := context.Background()
1464 _, err := client.Do(ctx, req, nil)
1465
1466 if err == nil {
1467 t.Error("Expected error to be returned.")
1468 }
1469 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1470 if !ok {
1471 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1472 }
1473 if abuseRateLimitErr.RetryAfter == nil {
1474 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1475 }
1476 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; got != want {
1477 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1478 }
1479
1480 // expect prevention of a following request
1481 if _, err = client.Do(ctx, req, nil); err == nil {
1482 t.Error("Expected error to be returned.")
1483 }
1484 abuseRateLimitErr, ok = err.(*AbuseRateLimitError)
1485 if !ok {
1486 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1487 }
1488 if abuseRateLimitErr.RetryAfter == nil {
1489 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1490 }
1491 // the saved duration might be a bit smaller than Retry-After because the duration is calculated from the expected end-of-cooldown time
1492 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; want-got > 1*time.Second {
1493 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1494 }
1495 if got, wantSuffix := abuseRateLimitErr.Message, "not making remote request."; !strings.HasSuffix(got, wantSuffix) {
1496 t.Errorf("Expected request to be prevented because of secondary rate limit, got: %v.", got)
1497 }
1498 }
1499
1500 // Ensure *AbuseRateLimitError.RetryAfter is parsed correctly for the x-ratelimit-reset header.
1501 func TestDo_rateLimit_abuseRateLimitError_xRateLimitReset(t *testing.T) {
1502 client, mux, _, teardown := setup()
1503 defer teardown()
1504
1505 // x-ratelimit-reset value of 123 seconds into the future.
1506 blockUntil := time.Now().Add(time.Duration(123) * time.Second).Unix()
1507
1508 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1509 w.Header().Set("Content-Type", "application/json; charset=utf-8")
1510 w.Header().Set(headerRateReset, strconv.Itoa(int(blockUntil)))
1511 w.Header().Set(headerRateRemaining, "1") // set remaining to a value > 0 to distinct from a primary rate limit
1512 w.WriteHeader(http.StatusForbidden)
1513 fmt.Fprintln(w, `{
1514 "message": "You have triggered an abuse detection mechanism ...",
1515 "documentation_url": "https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"
1516 }`)
1517 })
1518
1519 req, _ := client.NewRequest("GET", ".", nil)
1520 ctx := context.Background()
1521 _, err := client.Do(ctx, req, nil)
1522
1523 if err == nil {
1524 t.Error("Expected error to be returned.")
1525 }
1526 abuseRateLimitErr, ok := err.(*AbuseRateLimitError)
1527 if !ok {
1528 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1529 }
1530 if abuseRateLimitErr.RetryAfter == nil {
1531 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1532 }
1533 // 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
1534 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; want-got > 1*time.Second {
1535 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1536 }
1537
1538 // expect prevention of a following request
1539 if _, err = client.Do(ctx, req, nil); err == nil {
1540 t.Error("Expected error to be returned.")
1541 }
1542 abuseRateLimitErr, ok = err.(*AbuseRateLimitError)
1543 if !ok {
1544 t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err)
1545 }
1546 if abuseRateLimitErr.RetryAfter == nil {
1547 t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil")
1548 }
1549 // the saved duration might be a bit smaller than Retry-After because the duration is calculated from the expected end-of-cooldown time
1550 if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; want-got > 1*time.Second {
1551 t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want)
1552 }
1553 if got, wantSuffix := abuseRateLimitErr.Message, "not making remote request."; !strings.HasSuffix(got, wantSuffix) {
1554 t.Errorf("Expected request to be prevented because of secondary rate limit, got: %v.", got)
1555 }
1556 }
1557
1558 func TestDo_noContent(t *testing.T) {
1559 client, mux, _, teardown := setup()
1560 defer teardown()
1561
1562 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
1563 w.WriteHeader(http.StatusNoContent)
1564 })
1565
1566 var body json.RawMessage
1567
1568 req, _ := client.NewRequest("GET", ".", nil)
1569 ctx := context.Background()
1570 _, err := client.Do(ctx, req, &body)
1571 if err != nil {
1572 t.Fatalf("Do returned unexpected error: %v", err)
1573 }
1574 }
1575
1576 func TestSanitizeURL(t *testing.T) {
1577 tests := []struct {
1578 in, want string
1579 }{
1580 {"/?a=b", "/?a=b"},
1581 {"/?a=b&client_secret=secret", "/?a=b&client_secret=REDACTED"},
1582 {"/?a=b&client_id=id&client_secret=secret", "/?a=b&client_id=id&client_secret=REDACTED"},
1583 }
1584
1585 for _, tt := range tests {
1586 inURL, _ := url.Parse(tt.in)
1587 want, _ := url.Parse(tt.want)
1588
1589 if got := sanitizeURL(inURL); !cmp.Equal(got, want) {
1590 t.Errorf("sanitizeURL(%v) returned %v, want %v", tt.in, got, want)
1591 }
1592 }
1593 }
1594
1595 func TestCheckResponse(t *testing.T) {
1596 res := &http.Response{
1597 Request: &http.Request{},
1598 StatusCode: http.StatusBadRequest,
1599 Body: io.NopCloser(strings.NewReader(`{"message":"m",
1600 "errors": [{"resource": "r", "field": "f", "code": "c"}],
1601 "block": {"reason": "dmca", "created_at": "2016-03-17T15:39:46Z"}}`)),
1602 }
1603 err := CheckResponse(res).(*ErrorResponse)
1604
1605 if err == nil {
1606 t.Errorf("Expected error response.")
1607 }
1608
1609 want := &ErrorResponse{
1610 Response: res,
1611 Message: "m",
1612 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1613 Block: &ErrorBlock{
1614 Reason: "dmca",
1615 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1616 },
1617 }
1618 if !errors.Is(err, want) {
1619 t.Errorf("Error = %#v, want %#v", err, want)
1620 }
1621 }
1622
1623 func TestCheckResponse_RateLimit(t *testing.T) {
1624 res := &http.Response{
1625 Request: &http.Request{},
1626 StatusCode: http.StatusForbidden,
1627 Header: http.Header{},
1628 Body: io.NopCloser(strings.NewReader(`{"message":"m",
1629 "documentation_url": "url"}`)),
1630 }
1631 res.Header.Set(headerRateLimit, "60")
1632 res.Header.Set(headerRateRemaining, "0")
1633 res.Header.Set(headerRateReset, "243424")
1634
1635 err := CheckResponse(res).(*RateLimitError)
1636
1637 if err == nil {
1638 t.Errorf("Expected error response.")
1639 }
1640
1641 want := &RateLimitError{
1642 Rate: parseRate(res),
1643 Response: res,
1644 Message: "m",
1645 }
1646 if !errors.Is(err, want) {
1647 t.Errorf("Error = %#v, want %#v", err, want)
1648 }
1649 }
1650
1651 func TestCheckResponse_AbuseRateLimit(t *testing.T) {
1652 res := &http.Response{
1653 Request: &http.Request{},
1654 StatusCode: http.StatusForbidden,
1655 Body: io.NopCloser(strings.NewReader(`{"message":"m",
1656 "documentation_url": "docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits"}`)),
1657 }
1658 err := CheckResponse(res).(*AbuseRateLimitError)
1659
1660 if err == nil {
1661 t.Errorf("Expected error response.")
1662 }
1663
1664 want := &AbuseRateLimitError{
1665 Response: res,
1666 Message: "m",
1667 }
1668 if !errors.Is(err, want) {
1669 t.Errorf("Error = %#v, want %#v", err, want)
1670 }
1671 }
1672
1673 func TestCompareHttpResponse(t *testing.T) {
1674 testcases := map[string]struct {
1675 h1 *http.Response
1676 h2 *http.Response
1677 expected bool
1678 }{
1679 "both are nil": {
1680 expected: true,
1681 },
1682 "both are non nil - same StatusCode": {
1683 expected: true,
1684 h1: &http.Response{StatusCode: 200},
1685 h2: &http.Response{StatusCode: 200},
1686 },
1687 "both are non nil - different StatusCode": {
1688 expected: false,
1689 h1: &http.Response{StatusCode: 200},
1690 h2: &http.Response{StatusCode: 404},
1691 },
1692 "one is nil, other is not": {
1693 expected: false,
1694 h2: &http.Response{},
1695 },
1696 }
1697
1698 for name, tc := range testcases {
1699 t.Run(name, func(t *testing.T) {
1700 v := compareHTTPResponse(tc.h1, tc.h2)
1701 if tc.expected != v {
1702 t.Errorf("Expected %t, got %t for (%#v, %#v)", tc.expected, v, tc.h1, tc.h2)
1703 }
1704 })
1705 }
1706 }
1707
1708 func TestErrorResponse_Is(t *testing.T) {
1709 err := &ErrorResponse{
1710 Response: &http.Response{},
1711 Message: "m",
1712 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1713 Block: &ErrorBlock{
1714 Reason: "r",
1715 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1716 },
1717 DocumentationURL: "https://github.com",
1718 }
1719 testcases := map[string]struct {
1720 wantSame bool
1721 otherError error
1722 }{
1723 "errors are same": {
1724 wantSame: true,
1725 otherError: &ErrorResponse{
1726 Response: &http.Response{},
1727 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1728 Message: "m",
1729 Block: &ErrorBlock{
1730 Reason: "r",
1731 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1732 },
1733 DocumentationURL: "https://github.com",
1734 },
1735 },
1736 "errors have different values - Message": {
1737 wantSame: false,
1738 otherError: &ErrorResponse{
1739 Response: &http.Response{},
1740 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1741 Message: "m1",
1742 Block: &ErrorBlock{
1743 Reason: "r",
1744 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1745 },
1746 DocumentationURL: "https://github.com",
1747 },
1748 },
1749 "errors have different values - DocumentationURL": {
1750 wantSame: false,
1751 otherError: &ErrorResponse{
1752 Response: &http.Response{},
1753 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1754 Message: "m",
1755 Block: &ErrorBlock{
1756 Reason: "r",
1757 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1758 },
1759 DocumentationURL: "https://google.com",
1760 },
1761 },
1762 "errors have different values - Response is nil": {
1763 wantSame: false,
1764 otherError: &ErrorResponse{
1765 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1766 Message: "m",
1767 Block: &ErrorBlock{
1768 Reason: "r",
1769 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1770 },
1771 DocumentationURL: "https://github.com",
1772 },
1773 },
1774 "errors have different values - Errors": {
1775 wantSame: false,
1776 otherError: &ErrorResponse{
1777 Response: &http.Response{},
1778 Errors: []Error{{Resource: "r1", Field: "f1", Code: "c1"}},
1779 Message: "m",
1780 Block: &ErrorBlock{
1781 Reason: "r",
1782 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1783 },
1784 DocumentationURL: "https://github.com",
1785 },
1786 },
1787 "errors have different values - Errors have different length": {
1788 wantSame: false,
1789 otherError: &ErrorResponse{
1790 Response: &http.Response{},
1791 Errors: []Error{},
1792 Message: "m",
1793 Block: &ErrorBlock{
1794 Reason: "r",
1795 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1796 },
1797 DocumentationURL: "https://github.com",
1798 },
1799 },
1800 "errors have different values - Block - one is nil, other is not": {
1801 wantSame: false,
1802 otherError: &ErrorResponse{
1803 Response: &http.Response{},
1804 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1805 Message: "m",
1806 DocumentationURL: "https://github.com",
1807 },
1808 },
1809 "errors have different values - Block - different Reason": {
1810 wantSame: false,
1811 otherError: &ErrorResponse{
1812 Response: &http.Response{},
1813 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1814 Message: "m",
1815 Block: &ErrorBlock{
1816 Reason: "r1",
1817 CreatedAt: &Timestamp{time.Date(2016, time.March, 17, 15, 39, 46, 0, time.UTC)},
1818 },
1819 DocumentationURL: "https://github.com",
1820 },
1821 },
1822 "errors have different values - Block - different CreatedAt #1": {
1823 wantSame: false,
1824 otherError: &ErrorResponse{
1825 Response: &http.Response{},
1826 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1827 Message: "m",
1828 Block: &ErrorBlock{
1829 Reason: "r",
1830 CreatedAt: nil,
1831 },
1832 DocumentationURL: "https://github.com",
1833 },
1834 },
1835 "errors have different values - Block - different CreatedAt #2": {
1836 wantSame: false,
1837 otherError: &ErrorResponse{
1838 Response: &http.Response{},
1839 Errors: []Error{{Resource: "r", Field: "f", Code: "c"}},
1840 Message: "m",
1841 Block: &ErrorBlock{
1842 Reason: "r",
1843 CreatedAt: &Timestamp{time.Date(2017, time.March, 17, 15, 39, 46, 0, time.UTC)},
1844 },
1845 DocumentationURL: "https://github.com",
1846 },
1847 },
1848 "errors have different types": {
1849 wantSame: false,
1850 otherError: errors.New("Github"),
1851 },
1852 }
1853
1854 for name, tc := range testcases {
1855 t.Run(name, func(t *testing.T) {
1856 if tc.wantSame != err.Is(tc.otherError) {
1857 t.Errorf("Error = %#v, want %#v", err, tc.otherError)
1858 }
1859 })
1860 }
1861 }
1862
1863 func TestRateLimitError_Is(t *testing.T) {
1864 err := &RateLimitError{
1865 Response: &http.Response{},
1866 Message: "Github",
1867 }
1868 testcases := map[string]struct {
1869 wantSame bool
1870 err *RateLimitError
1871 otherError error
1872 }{
1873 "errors are same": {
1874 wantSame: true,
1875 err: err,
1876 otherError: &RateLimitError{
1877 Response: &http.Response{},
1878 Message: "Github",
1879 },
1880 },
1881 "errors are same - Response is nil": {
1882 wantSame: true,
1883 err: &RateLimitError{
1884 Message: "Github",
1885 },
1886 otherError: &RateLimitError{
1887 Message: "Github",
1888 },
1889 },
1890 "errors have different values - Rate": {
1891 wantSame: false,
1892 err: err,
1893 otherError: &RateLimitError{
1894 Rate: Rate{Limit: 10},
1895 Response: &http.Response{},
1896 Message: "Gitlab",
1897 },
1898 },
1899 "errors have different values - Response is nil": {
1900 wantSame: false,
1901 err: err,
1902 otherError: &RateLimitError{
1903 Message: "Github",
1904 },
1905 },
1906 "errors have different values - StatusCode": {
1907 wantSame: false,
1908 err: err,
1909 otherError: &RateLimitError{
1910 Response: &http.Response{StatusCode: 200},
1911 Message: "Github",
1912 },
1913 },
1914 "errors have different types": {
1915 wantSame: false,
1916 err: err,
1917 otherError: errors.New("Github"),
1918 },
1919 }
1920
1921 for name, tc := range testcases {
1922 t.Run(name, func(t *testing.T) {
1923 if tc.wantSame != tc.err.Is(tc.otherError) {
1924 t.Errorf("Error = %#v, want %#v", tc.err, tc.otherError)
1925 }
1926 })
1927 }
1928 }
1929
1930 func TestAbuseRateLimitError_Is(t *testing.T) {
1931 t1 := 1 * time.Second
1932 t2 := 2 * time.Second
1933 err := &AbuseRateLimitError{
1934 Response: &http.Response{},
1935 Message: "Github",
1936 RetryAfter: &t1,
1937 }
1938 testcases := map[string]struct {
1939 wantSame bool
1940 err *AbuseRateLimitError
1941 otherError error
1942 }{
1943 "errors are same": {
1944 wantSame: true,
1945 err: err,
1946 otherError: &AbuseRateLimitError{
1947 Response: &http.Response{},
1948 Message: "Github",
1949 RetryAfter: &t1,
1950 },
1951 },
1952 "errors are same - Response is nil": {
1953 wantSame: true,
1954 err: &AbuseRateLimitError{
1955 Message: "Github",
1956 RetryAfter: &t1,
1957 },
1958 otherError: &AbuseRateLimitError{
1959 Message: "Github",
1960 RetryAfter: &t1,
1961 },
1962 },
1963 "errors have different values - Message": {
1964 wantSame: false,
1965 err: err,
1966 otherError: &AbuseRateLimitError{
1967 Response: &http.Response{},
1968 Message: "Gitlab",
1969 RetryAfter: nil,
1970 },
1971 },
1972 "errors have different values - RetryAfter": {
1973 wantSame: false,
1974 err: err,
1975 otherError: &AbuseRateLimitError{
1976 Response: &http.Response{},
1977 Message: "Github",
1978 RetryAfter: &t2,
1979 },
1980 },
1981 "errors have different values - Response is nil": {
1982 wantSame: false,
1983 err: err,
1984 otherError: &AbuseRateLimitError{
1985 Message: "Github",
1986 RetryAfter: &t1,
1987 },
1988 },
1989 "errors have different values - StatusCode": {
1990 wantSame: false,
1991 err: err,
1992 otherError: &AbuseRateLimitError{
1993 Response: &http.Response{StatusCode: 200},
1994 Message: "Github",
1995 RetryAfter: &t1,
1996 },
1997 },
1998 "errors have different types": {
1999 wantSame: false,
2000 err: err,
2001 otherError: errors.New("Github"),
2002 },
2003 }
2004
2005 for name, tc := range testcases {
2006 t.Run(name, func(t *testing.T) {
2007 if tc.wantSame != tc.err.Is(tc.otherError) {
2008 t.Errorf("Error = %#v, want %#v", tc.err, tc.otherError)
2009 }
2010 })
2011 }
2012 }
2013
2014 func TestAcceptedError_Is(t *testing.T) {
2015 err := &AcceptedError{Raw: []byte("Github")}
2016 testcases := map[string]struct {
2017 wantSame bool
2018 otherError error
2019 }{
2020 "errors are same": {
2021 wantSame: true,
2022 otherError: &AcceptedError{Raw: []byte("Github")},
2023 },
2024 "errors have different values": {
2025 wantSame: false,
2026 otherError: &AcceptedError{Raw: []byte("Gitlab")},
2027 },
2028 "errors have different types": {
2029 wantSame: false,
2030 otherError: errors.New("Github"),
2031 },
2032 }
2033
2034 for name, tc := range testcases {
2035 t.Run(name, func(t *testing.T) {
2036 if tc.wantSame != err.Is(tc.otherError) {
2037 t.Errorf("Error = %#v, want %#v", err, tc.otherError)
2038 }
2039 })
2040 }
2041 }
2042
2043 // ensure that we properly handle API errors that do not contain a response body
2044 func TestCheckResponse_noBody(t *testing.T) {
2045 res := &http.Response{
2046 Request: &http.Request{},
2047 StatusCode: http.StatusBadRequest,
2048 Body: io.NopCloser(strings.NewReader("")),
2049 }
2050 err := CheckResponse(res).(*ErrorResponse)
2051
2052 if err == nil {
2053 t.Errorf("Expected error response.")
2054 }
2055
2056 want := &ErrorResponse{
2057 Response: res,
2058 }
2059 if !errors.Is(err, want) {
2060 t.Errorf("Error = %#v, want %#v", err, want)
2061 }
2062 }
2063
2064 func TestCheckResponse_unexpectedErrorStructure(t *testing.T) {
2065 httpBody := `{"message":"m", "errors": ["error 1"]}`
2066 res := &http.Response{
2067 Request: &http.Request{},
2068 StatusCode: http.StatusBadRequest,
2069 Body: io.NopCloser(strings.NewReader(httpBody)),
2070 }
2071 err := CheckResponse(res).(*ErrorResponse)
2072
2073 if err == nil {
2074 t.Errorf("Expected error response.")
2075 }
2076
2077 want := &ErrorResponse{
2078 Response: res,
2079 Message: "m",
2080 Errors: []Error{{Message: "error 1"}},
2081 }
2082 if !errors.Is(err, want) {
2083 t.Errorf("Error = %#v, want %#v", err, want)
2084 }
2085 data, err2 := io.ReadAll(err.Response.Body)
2086 if err2 != nil {
2087 t.Fatalf("failed to read response body: %v", err)
2088 }
2089 if got := string(data); got != httpBody {
2090 t.Errorf("ErrorResponse.Response.Body = %q, want %q", got, httpBody)
2091 }
2092 }
2093
2094 func TestParseBooleanResponse_true(t *testing.T) {
2095 result, err := parseBoolResponse(nil)
2096 if err != nil {
2097 t.Errorf("parseBoolResponse returned error: %+v", err)
2098 }
2099
2100 if want := true; result != want {
2101 t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
2102 }
2103 }
2104
2105 func TestParseBooleanResponse_false(t *testing.T) {
2106 v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusNotFound}}
2107 result, err := parseBoolResponse(v)
2108 if err != nil {
2109 t.Errorf("parseBoolResponse returned error: %+v", err)
2110 }
2111
2112 if want := false; result != want {
2113 t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
2114 }
2115 }
2116
2117 func TestParseBooleanResponse_error(t *testing.T) {
2118 v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusBadRequest}}
2119 result, err := parseBoolResponse(v)
2120
2121 if err == nil {
2122 t.Errorf("Expected error to be returned.")
2123 }
2124
2125 if want := false; result != want {
2126 t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want)
2127 }
2128 }
2129
2130 func TestErrorResponse_Error(t *testing.T) {
2131 res := &http.Response{Request: &http.Request{}}
2132 err := ErrorResponse{Message: "m", Response: res}
2133 if err.Error() == "" {
2134 t.Errorf("Expected non-empty ErrorResponse.Error()")
2135 }
2136
2137 //dont panic if request is nil
2138 res = &http.Response{}
2139 err = ErrorResponse{Message: "m", Response: res}
2140 if err.Error() == "" {
2141 t.Errorf("Expected non-empty ErrorResponse.Error()")
2142 }
2143
2144 //dont panic if response is nil
2145 err = ErrorResponse{Message: "m"}
2146 if err.Error() == "" {
2147 t.Errorf("Expected non-empty ErrorResponse.Error()")
2148 }
2149 }
2150
2151 func TestError_Error(t *testing.T) {
2152 err := Error{}
2153 if err.Error() == "" {
2154 t.Errorf("Expected non-empty Error.Error()")
2155 }
2156 }
2157
2158 func TestSetCredentialsAsHeaders(t *testing.T) {
2159 req := new(http.Request)
2160 id, secret := "id", "secret"
2161 modifiedRequest := setCredentialsAsHeaders(req, id, secret)
2162
2163 actualID, actualSecret, ok := modifiedRequest.BasicAuth()
2164 if !ok {
2165 t.Errorf("request does not contain basic credentials")
2166 }
2167
2168 if actualID != id {
2169 t.Errorf("id is %s, want %s", actualID, id)
2170 }
2171
2172 if actualSecret != secret {
2173 t.Errorf("secret is %s, want %s", actualSecret, secret)
2174 }
2175 }
2176
2177 func TestUnauthenticatedRateLimitedTransport(t *testing.T) {
2178 client, mux, _, teardown := setup()
2179 defer teardown()
2180
2181 clientID, clientSecret := "id", "secret"
2182 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2183 id, secret, ok := r.BasicAuth()
2184 if !ok {
2185 t.Errorf("request does not contain basic auth credentials")
2186 }
2187 if id != clientID {
2188 t.Errorf("request contained basic auth username %q, want %q", id, clientID)
2189 }
2190 if secret != clientSecret {
2191 t.Errorf("request contained basic auth password %q, want %q", secret, clientSecret)
2192 }
2193 })
2194
2195 tp := &UnauthenticatedRateLimitedTransport{
2196 ClientID: clientID,
2197 ClientSecret: clientSecret,
2198 }
2199 unauthedClient := NewClient(tp.Client())
2200 unauthedClient.BaseURL = client.BaseURL
2201 req, _ := unauthedClient.NewRequest("GET", ".", nil)
2202 ctx := context.Background()
2203 _, err := unauthedClient.Do(ctx, req, nil)
2204 assertNilError(t, err)
2205 }
2206
2207 func TestUnauthenticatedRateLimitedTransport_missingFields(t *testing.T) {
2208 // missing ClientID
2209 tp := &UnauthenticatedRateLimitedTransport{
2210 ClientSecret: "secret",
2211 }
2212 _, err := tp.RoundTrip(nil)
2213 if err == nil {
2214 t.Errorf("Expected error to be returned")
2215 }
2216
2217 // missing ClientSecret
2218 tp = &UnauthenticatedRateLimitedTransport{
2219 ClientID: "id",
2220 }
2221 _, err = tp.RoundTrip(nil)
2222 if err == nil {
2223 t.Errorf("Expected error to be returned")
2224 }
2225 }
2226
2227 func TestUnauthenticatedRateLimitedTransport_transport(t *testing.T) {
2228 // default transport
2229 tp := &UnauthenticatedRateLimitedTransport{
2230 ClientID: "id",
2231 ClientSecret: "secret",
2232 }
2233 if tp.transport() != http.DefaultTransport {
2234 t.Errorf("Expected http.DefaultTransport to be used.")
2235 }
2236
2237 // custom transport
2238 tp = &UnauthenticatedRateLimitedTransport{
2239 ClientID: "id",
2240 ClientSecret: "secret",
2241 Transport: &http.Transport{},
2242 }
2243 if tp.transport() == http.DefaultTransport {
2244 t.Errorf("Expected custom transport to be used.")
2245 }
2246 }
2247
2248 func TestBasicAuthTransport(t *testing.T) {
2249 client, mux, _, teardown := setup()
2250 defer teardown()
2251
2252 username, password, otp := "u", "p", "123456"
2253
2254 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2255 u, p, ok := r.BasicAuth()
2256 if !ok {
2257 t.Errorf("request does not contain basic auth credentials")
2258 }
2259 if u != username {
2260 t.Errorf("request contained basic auth username %q, want %q", u, username)
2261 }
2262 if p != password {
2263 t.Errorf("request contained basic auth password %q, want %q", p, password)
2264 }
2265 if got, want := r.Header.Get(headerOTP), otp; got != want {
2266 t.Errorf("request contained OTP %q, want %q", got, want)
2267 }
2268 })
2269
2270 tp := &BasicAuthTransport{
2271 Username: username,
2272 Password: password,
2273 OTP: otp,
2274 }
2275 basicAuthClient := NewClient(tp.Client())
2276 basicAuthClient.BaseURL = client.BaseURL
2277 req, _ := basicAuthClient.NewRequest("GET", ".", nil)
2278 ctx := context.Background()
2279 _, err := basicAuthClient.Do(ctx, req, nil)
2280 assertNilError(t, err)
2281 }
2282
2283 func TestBasicAuthTransport_transport(t *testing.T) {
2284 // default transport
2285 tp := &BasicAuthTransport{}
2286 if tp.transport() != http.DefaultTransport {
2287 t.Errorf("Expected http.DefaultTransport to be used.")
2288 }
2289
2290 // custom transport
2291 tp = &BasicAuthTransport{
2292 Transport: &http.Transport{},
2293 }
2294 if tp.transport() == http.DefaultTransport {
2295 t.Errorf("Expected custom transport to be used.")
2296 }
2297 }
2298
2299 func TestFormatRateReset(t *testing.T) {
2300 d := 120*time.Minute + 12*time.Second
2301 got := formatRateReset(d)
2302 want := "[rate reset in 120m12s]"
2303 if got != want {
2304 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2305 }
2306
2307 d = 14*time.Minute + 2*time.Second
2308 got = formatRateReset(d)
2309 want = "[rate reset in 14m02s]"
2310 if got != want {
2311 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2312 }
2313
2314 d = 2*time.Minute + 2*time.Second
2315 got = formatRateReset(d)
2316 want = "[rate reset in 2m02s]"
2317 if got != want {
2318 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2319 }
2320
2321 d = 12 * time.Second
2322 got = formatRateReset(d)
2323 want = "[rate reset in 12s]"
2324 if got != want {
2325 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2326 }
2327
2328 d = -1 * (2*time.Hour + 2*time.Second)
2329 got = formatRateReset(d)
2330 want = "[rate limit was reset 120m02s ago]"
2331 if got != want {
2332 t.Errorf("Format is wrong. got: %v, want: %v", got, want)
2333 }
2334 }
2335
2336 func TestNestedStructAccessorNoPanic(t *testing.T) {
2337 issue := &Issue{User: nil}
2338 got := issue.GetUser().GetPlan().GetName()
2339 want := ""
2340 if got != want {
2341 t.Errorf("Issues.Get.GetUser().GetPlan().GetName() returned %+v, want %+v", got, want)
2342 }
2343 }
2344
2345 func TestTwoFactorAuthError(t *testing.T) {
2346 u, err := url.Parse("https://example.com")
2347 if err != nil {
2348 t.Fatal(err)
2349 }
2350
2351 e := &TwoFactorAuthError{
2352 Response: &http.Response{
2353 Request: &http.Request{Method: "PUT", URL: u},
2354 StatusCode: http.StatusTooManyRequests,
2355 },
2356 Message: "<msg>",
2357 }
2358 if got, want := e.Error(), "PUT https://example.com: 429 <msg> []"; got != want {
2359 t.Errorf("TwoFactorAuthError = %q, want %q", got, want)
2360 }
2361 }
2362
2363 func TestRateLimitError(t *testing.T) {
2364 u, err := url.Parse("https://example.com")
2365 if err != nil {
2366 t.Fatal(err)
2367 }
2368
2369 r := &RateLimitError{
2370 Response: &http.Response{
2371 Request: &http.Request{Method: "PUT", URL: u},
2372 StatusCode: http.StatusTooManyRequests,
2373 },
2374 Message: "<msg>",
2375 }
2376 if got, want := r.Error(), "PUT https://example.com: 429 <msg> [rate limit was reset"; !strings.Contains(got, want) {
2377 t.Errorf("RateLimitError = %q, want %q", got, want)
2378 }
2379 }
2380
2381 func TestAcceptedError(t *testing.T) {
2382 a := &AcceptedError{}
2383 if got, want := a.Error(), "try again later"; !strings.Contains(got, want) {
2384 t.Errorf("AcceptedError = %q, want %q", got, want)
2385 }
2386 }
2387
2388 func TestAbuseRateLimitError(t *testing.T) {
2389 u, err := url.Parse("https://example.com")
2390 if err != nil {
2391 t.Fatal(err)
2392 }
2393
2394 r := &AbuseRateLimitError{
2395 Response: &http.Response{
2396 Request: &http.Request{Method: "PUT", URL: u},
2397 StatusCode: http.StatusTooManyRequests,
2398 },
2399 Message: "<msg>",
2400 }
2401 if got, want := r.Error(), "PUT https://example.com: 429 <msg>"; got != want {
2402 t.Errorf("AbuseRateLimitError = %q, want %q", got, want)
2403 }
2404 }
2405
2406 func TestAddOptions_QueryValues(t *testing.T) {
2407 if _, err := addOptions("yo", ""); err == nil {
2408 t.Error("addOptions err = nil, want error")
2409 }
2410 }
2411
2412 func TestBareDo_returnsOpenBody(t *testing.T) {
2413 client, mux, _, teardown := setup()
2414 defer teardown()
2415
2416 expectedBody := "Hello from the other side !"
2417
2418 mux.HandleFunc("/test-url", func(w http.ResponseWriter, r *http.Request) {
2419 testMethod(t, r, "GET")
2420 fmt.Fprint(w, expectedBody)
2421 })
2422
2423 ctx := context.Background()
2424 req, err := client.NewRequest("GET", "test-url", nil)
2425 if err != nil {
2426 t.Fatalf("client.NewRequest returned error: %v", err)
2427 }
2428
2429 resp, err := client.BareDo(ctx, req)
2430 if err != nil {
2431 t.Fatalf("client.BareDo returned error: %v", err)
2432 }
2433
2434 got, err := io.ReadAll(resp.Body)
2435 if err != nil {
2436 t.Fatalf("io.ReadAll returned error: %v", err)
2437 }
2438 if string(got) != expectedBody {
2439 t.Fatalf("Expected %q, got %q", expectedBody, string(got))
2440 }
2441 if err := resp.Body.Close(); err != nil {
2442 t.Fatalf("resp.Body.Close() returned error: %v", err)
2443 }
2444 }
2445
2446 func TestErrorResponse_Marshal(t *testing.T) {
2447 testJSONMarshal(t, &ErrorResponse{}, "{}")
2448
2449 u := &ErrorResponse{
2450 Message: "msg",
2451 Errors: []Error{
2452 {
2453 Resource: "res",
2454 Field: "f",
2455 Code: "c",
2456 Message: "msg",
2457 },
2458 },
2459 Block: &ErrorBlock{
2460 Reason: "reason",
2461 CreatedAt: &Timestamp{referenceTime},
2462 },
2463 DocumentationURL: "doc",
2464 }
2465
2466 want := `{
2467 "message": "msg",
2468 "errors": [
2469 {
2470 "resource": "res",
2471 "field": "f",
2472 "code": "c",
2473 "message": "msg"
2474 }
2475 ],
2476 "block": {
2477 "reason": "reason",
2478 "created_at": ` + referenceTimeStr + `
2479 },
2480 "documentation_url": "doc"
2481 }`
2482
2483 testJSONMarshal(t, u, want)
2484 }
2485
2486 func TestErrorBlock_Marshal(t *testing.T) {
2487 testJSONMarshal(t, &ErrorBlock{}, "{}")
2488
2489 u := &ErrorBlock{
2490 Reason: "reason",
2491 CreatedAt: &Timestamp{referenceTime},
2492 }
2493
2494 want := `{
2495 "reason": "reason",
2496 "created_at": ` + referenceTimeStr + `
2497 }`
2498
2499 testJSONMarshal(t, u, want)
2500 }
2501
2502 func TestRateLimitError_Marshal(t *testing.T) {
2503 testJSONMarshal(t, &RateLimitError{}, "{}")
2504
2505 u := &RateLimitError{
2506 Rate: Rate{
2507 Limit: 1,
2508 Remaining: 1,
2509 Reset: Timestamp{referenceTime},
2510 },
2511 Message: "msg",
2512 }
2513
2514 want := `{
2515 "Rate": {
2516 "limit": 1,
2517 "remaining": 1,
2518 "reset": ` + referenceTimeStr + `
2519 },
2520 "message": "msg"
2521 }`
2522
2523 testJSONMarshal(t, u, want)
2524 }
2525
2526 func TestAbuseRateLimitError_Marshal(t *testing.T) {
2527 testJSONMarshal(t, &AbuseRateLimitError{}, "{}")
2528
2529 u := &AbuseRateLimitError{
2530 Message: "msg",
2531 }
2532
2533 want := `{
2534 "message": "msg"
2535 }`
2536
2537 testJSONMarshal(t, u, want)
2538 }
2539
2540 func TestError_Marshal(t *testing.T) {
2541 testJSONMarshal(t, &Error{}, "{}")
2542
2543 u := &Error{
2544 Resource: "res",
2545 Field: "field",
2546 Code: "code",
2547 Message: "msg",
2548 }
2549
2550 want := `{
2551 "resource": "res",
2552 "field": "field",
2553 "code": "code",
2554 "message": "msg"
2555 }`
2556
2557 testJSONMarshal(t, u, want)
2558 }
2559
2560 func TestParseTokenExpiration(t *testing.T) {
2561 tests := []struct {
2562 header string
2563 want Timestamp
2564 }{
2565 {
2566 header: "",
2567 want: Timestamp{},
2568 },
2569 {
2570 header: "this is a garbage",
2571 want: Timestamp{},
2572 },
2573 {
2574 header: "2021-09-03 02:34:04 UTC",
2575 want: Timestamp{time.Date(2021, time.September, 3, 2, 34, 4, 0, time.UTC)},
2576 },
2577 {
2578 header: "2021-09-03 14:34:04 UTC",
2579 want: Timestamp{time.Date(2021, time.September, 3, 14, 34, 4, 0, time.UTC)},
2580 },
2581 // Some tokens include the timezone offset instead of the timezone.
2582 // https://github.com/google/go-github/issues/2649
2583 {
2584 header: "2023-04-26 20:23:26 +0200",
2585 want: Timestamp{time.Date(2023, time.April, 26, 18, 23, 26, 0, time.UTC)},
2586 },
2587 }
2588
2589 for _, tt := range tests {
2590 res := &http.Response{
2591 Request: &http.Request{},
2592 Header: http.Header{},
2593 }
2594
2595 res.Header.Set(headerTokenExpiration, tt.header)
2596 exp := parseTokenExpiration(res)
2597 if !exp.Equal(tt.want) {
2598 t.Errorf("parseTokenExpiration of %q\nreturned %#v\n want %#v", tt.header, exp, tt.want)
2599 }
2600 }
2601 }
2602
2603 func TestClientCopy_leak_transport(t *testing.T) {
2604 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2605 w.Header().Set("Content-Type", "application/json")
2606 accessToken := r.Header.Get("Authorization")
2607 _, _ = fmt.Fprintf(w, `{"login": "%s"}`, accessToken)
2608 }))
2609 clientPreconfiguredWithURLs, err := NewClient(nil).WithEnterpriseURLs(srv.URL, srv.URL)
2610 if err != nil {
2611 t.Fatal(err)
2612 }
2613
2614 aliceClient := clientPreconfiguredWithURLs.WithAuthToken("alice")
2615 bobClient := clientPreconfiguredWithURLs.WithAuthToken("bob")
2616
2617 alice, _, err := aliceClient.Users.Get(context.Background(), "")
2618 if err != nil {
2619 t.Fatal(err)
2620 }
2621
2622 assertNoDiff(t, "Bearer alice", alice.GetLogin())
2623
2624 bob, _, err := bobClient.Users.Get(context.Background(), "")
2625 if err != nil {
2626 t.Fatal(err)
2627 }
2628
2629 assertNoDiff(t, "Bearer bob", bob.GetLogin())
2630 }