-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
github_test.go
2880 lines (2587 loc) · 83.9 KB
/
github_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
const (
// baseURLPath is a non-empty Client.BaseURL path to use during tests,
// to ensure relative URLs are used for all endpoints. See issue #752.
baseURLPath = "/api-v3"
)
// setup sets up a test HTTP server along with a github.Client that is
// configured to talk to that test server. Tests should register handlers on
// mux which provide mock responses for the API method being tested.
func setup(t *testing.T) (client *Client, mux *http.ServeMux, serverURL string) {
t.Helper()
// mux is the HTTP request multiplexer used with the test server.
mux = http.NewServeMux()
// We want to ensure that tests catch mistakes where the endpoint URL is
// specified as absolute rather than relative. It only makes a difference
// when there's a non-empty base URL path. So, use that. See issue #752.
apiHandler := http.NewServeMux()
apiHandler.Handle(baseURLPath+"/", http.StripPrefix(baseURLPath, mux))
apiHandler.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(os.Stderr, "FAIL: Client.BaseURL path prefix is not preserved in the request URL:")
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "\t"+req.URL.String())
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "\tDid you accidentally use an absolute endpoint URL rather than relative?")
fmt.Fprintln(os.Stderr, "\tSee https://github.com/google/go-github/issues/752 for information.")
http.Error(w, "Client.BaseURL path prefix is not preserved in the request URL.", http.StatusInternalServerError)
})
// server is a test HTTP server used to provide mock API responses.
server := httptest.NewServer(apiHandler)
// client is the GitHub client being tested and is
// configured to use test server.
client = NewClient(nil)
url, _ := url.Parse(server.URL + baseURLPath + "/")
client.BaseURL = url
client.UploadURL = url
t.Cleanup(server.Close)
return client, mux, server.URL
}
// openTestFile creates a new file with the given name and content for testing.
// In order to ensure the exact file name, this function will create a new temp
// directory, and create the file in that directory. The file is automatically
// cleaned up after the test.
func openTestFile(t *testing.T, name, content string) *os.File {
t.Helper()
fname := filepath.Join(t.TempDir(), name)
err := os.WriteFile(fname, []byte(content), 0600)
if err != nil {
t.Fatal(err)
}
file, err := os.Open(fname)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { file.Close() })
return file
}
func testMethod(t *testing.T, r *http.Request, want string) {
t.Helper()
if got := r.Method; got != want {
t.Errorf("Request method: %v, want %v", got, want)
}
}
type values map[string]string
func testFormValues(t *testing.T, r *http.Request, values values) {
t.Helper()
want := url.Values{}
for k, v := range values {
want.Set(k, v)
}
assertNilError(t, r.ParseForm())
if got := r.Form; !cmp.Equal(got, want) {
t.Errorf("Request parameters: %v, want %v", got, want)
}
}
func testHeader(t *testing.T, r *http.Request, header string, want string) {
t.Helper()
if got := r.Header.Get(header); got != want {
t.Errorf("Header.Get(%q) returned %q, want %q", header, got, want)
}
}
func testURLParseError(t *testing.T, err error) {
t.Helper()
if err == nil {
t.Errorf("Expected error to be returned")
}
if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
t.Errorf("Expected URL parse error, got %+v", err)
}
}
func testBody(t *testing.T, r *http.Request, want string) {
t.Helper()
b, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("Error reading request body: %v", err)
}
if got := string(b); got != want {
t.Errorf("request Body is %s, want %s", got, want)
}
}
// Test whether the marshaling of v produces JSON that corresponds
// to the want string.
func testJSONMarshal(t *testing.T, v interface{}, want string) {
t.Helper()
// Unmarshal the wanted JSON, to verify its correctness, and marshal it back
// to sort the keys.
u := reflect.New(reflect.TypeOf(v)).Interface()
if err := json.Unmarshal([]byte(want), &u); err != nil {
t.Errorf("Unable to unmarshal JSON for %v: %v", want, err)
}
w, err := json.MarshalIndent(u, "", " ")
if err != nil {
t.Errorf("Unable to marshal JSON for %#v", u)
}
// Marshal the target value.
got, err := json.MarshalIndent(v, "", " ")
if err != nil {
t.Errorf("Unable to marshal JSON for %#v", v)
}
if diff := cmp.Diff(string(w), string(got)); diff != "" {
t.Errorf("json.Marshal returned:\n%s\nwant:\n%s\ndiff:\n%v", got, w, diff)
}
}
// Test whether the v fields have the url tag and the parsing of v
// produces query parameters that corresponds to the want string.
func testAddURLOptions(t *testing.T, url string, v interface{}, want string) {
t.Helper()
vt := reflect.Indirect(reflect.ValueOf(v)).Type()
for i := 0; i < vt.NumField(); i++ {
field := vt.Field(i)
if alias, ok := field.Tag.Lookup("url"); ok {
if alias == "" {
t.Errorf("The field %+v has a blank url tag", field)
}
} else {
t.Errorf("The field %+v has no url tag specified", field)
}
}
got, err := addOptions(url, v)
if err != nil {
t.Errorf("Unable to add %#v as query parameters", v)
}
if got != want {
t.Errorf("addOptions(%q, %#v) returned %v, want %v", url, v, got, want)
}
}
// Test how bad options are handled. Method f under test should
// return an error.
func testBadOptions(t *testing.T, methodName string, f func() error) {
t.Helper()
if methodName == "" {
t.Error("testBadOptions: must supply method methodName")
}
if err := f(); err == nil {
t.Errorf("bad options %v err = nil, want error", methodName)
}
}
// Test function under NewRequest failure and then s.client.Do failure.
// Method f should be a regular call that would normally succeed, but
// should return an error when NewRequest or s.client.Do fails.
func testNewRequestAndDoFailure(t *testing.T, methodName string, client *Client, f func() (*Response, error)) {
testNewRequestAndDoFailureCategory(t, methodName, client, CoreCategory, f)
}
// testNewRequestAndDoFailureCategory works Like testNewRequestAndDoFailure, but allows setting the category.
func testNewRequestAndDoFailureCategory(t *testing.T, methodName string, client *Client, category RateLimitCategory, f func() (*Response, error)) {
t.Helper()
if methodName == "" {
t.Error("testNewRequestAndDoFailure: must supply method methodName")
}
client.BaseURL.Path = ""
resp, err := f()
if resp != nil {
t.Errorf("client.BaseURL.Path='' %v resp = %#v, want nil", methodName, resp)
}
if err == nil {
t.Errorf("client.BaseURL.Path='' %v err = nil, want error", methodName)
}
client.BaseURL.Path = "/api-v3/"
client.rateLimits[category].Reset.Time = time.Now().Add(10 * time.Minute)
resp, err = f()
if bypass := resp.Request.Context().Value(bypassRateLimitCheck); bypass != nil {
return
}
if want := http.StatusForbidden; resp == nil || resp.Response.StatusCode != want {
if resp != nil {
t.Errorf("rate.Reset.Time > now %v resp = %#v, want StatusCode=%v", methodName, resp.Response, want)
} else {
t.Errorf("rate.Reset.Time > now %v resp = nil, want StatusCode=%v", methodName, want)
}
}
if err == nil {
t.Errorf("rate.Reset.Time > now %v err = nil, want error", methodName)
}
}
// Test that all error response types contain the status code.
func testErrorResponseForStatusCode(t *testing.T, code int) {
t.Helper()
client, mux, _ := setup(t)
mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
w.WriteHeader(code)
})
ctx := context.Background()
_, _, err := client.Repositories.ListHooks(ctx, "o", "r", nil)
switch e := err.(type) {
case *ErrorResponse:
case *RateLimitError:
case *AbuseRateLimitError:
if code != e.Response.StatusCode {
t.Error("Error response does not contain status code")
}
default:
t.Error("Unknown error response type")
}
}
func assertNoDiff(t *testing.T, want, got interface{}) {
t.Helper()
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("diff mismatch (-want +got):\n%v", diff)
}
}
func assertNilError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
func assertWrite(t *testing.T, w io.Writer, data []byte) {
t.Helper()
_, err := w.Write(data)
assertNilError(t, err)
}
func TestNewClient(t *testing.T) {
t.Parallel()
c := NewClient(nil)
if got, want := c.BaseURL.String(), defaultBaseURL; got != want {
t.Errorf("NewClient BaseURL is %v, want %v", got, want)
}
if got, want := c.UserAgent, defaultUserAgent; got != want {
t.Errorf("NewClient UserAgent is %v, want %v", got, want)
}
c2 := NewClient(nil)
if c.client == c2.client {
t.Error("NewClient returned same http.Clients, but they should differ")
}
}
func TestNewClientWithEnvProxy(t *testing.T) {
t.Parallel()
client := NewClientWithEnvProxy()
if got, want := client.BaseURL.String(), defaultBaseURL; got != want {
t.Errorf("NewClient BaseURL is %v, want %v", got, want)
}
}
func TestClient(t *testing.T) {
t.Parallel()
c := NewClient(nil)
c2 := c.Client()
if c.client == c2 {
t.Error("Client returned same http.Client, but should be different")
}
}
func TestWithAuthToken(t *testing.T) {
t.Parallel()
token := "gh_test_token"
validate := func(t *testing.T, c *http.Client, token string) {
t.Helper()
want := token
if want != "" {
want = "Bearer " + want
}
gotReq := false
headerVal := ""
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotReq = true
headerVal = r.Header.Get("Authorization")
}))
_, err := c.Get(srv.URL)
assertNilError(t, err)
if !gotReq {
t.Error("request not sent")
}
if headerVal != want {
t.Errorf("Authorization header is %v, want %v", headerVal, want)
}
}
t.Run("zero-value Client", func(t *testing.T) {
t.Parallel()
c := new(Client).WithAuthToken(token)
validate(t, c.Client(), token)
})
t.Run("NewClient", func(t *testing.T) {
t.Parallel()
httpClient := &http.Client{}
client := NewClient(httpClient).WithAuthToken(token)
validate(t, client.Client(), token)
// make sure the original client isn't setting auth headers now
validate(t, httpClient, "")
})
t.Run("NewTokenClient", func(t *testing.T) {
t.Parallel()
validate(t, NewTokenClient(context.Background(), token).Client(), token)
})
}
func TestWithEnterpriseURLs(t *testing.T) {
t.Parallel()
for _, test := range []struct {
name string
baseURL string
wantBaseURL string
uploadURL string
wantUploadURL string
wantErr string
}{
{
name: "does not modify properly formed URLs",
baseURL: "https://custom-url/api/v3/",
wantBaseURL: "https://custom-url/api/v3/",
uploadURL: "https://custom-upload-url/api/uploads/",
wantUploadURL: "https://custom-upload-url/api/uploads/",
},
{
name: "adds trailing slash",
baseURL: "https://custom-url/api/v3",
wantBaseURL: "https://custom-url/api/v3/",
uploadURL: "https://custom-upload-url/api/uploads",
wantUploadURL: "https://custom-upload-url/api/uploads/",
},
{
name: "adds enterprise suffix",
baseURL: "https://custom-url/",
wantBaseURL: "https://custom-url/api/v3/",
uploadURL: "https://custom-upload-url/",
wantUploadURL: "https://custom-upload-url/api/uploads/",
},
{
name: "adds enterprise suffix and trailing slash",
baseURL: "https://custom-url",
wantBaseURL: "https://custom-url/api/v3/",
uploadURL: "https://custom-upload-url",
wantUploadURL: "https://custom-upload-url/api/uploads/",
},
{
name: "bad base URL",
baseURL: "bogus\nbase\nURL",
uploadURL: "https://custom-upload-url/api/uploads/",
wantErr: `invalid control character in URL`,
},
{
name: "bad upload URL",
baseURL: "https://custom-url/api/v3/",
uploadURL: "bogus\nupload\nURL",
wantErr: `invalid control character in URL`,
},
{
name: "URL has existing API prefix, adds trailing slash",
baseURL: "https://api.custom-url",
wantBaseURL: "https://api.custom-url/",
uploadURL: "https://api.custom-upload-url",
wantUploadURL: "https://api.custom-upload-url/",
},
{
name: "URL has existing API prefix and trailing slash",
baseURL: "https://api.custom-url/",
wantBaseURL: "https://api.custom-url/",
uploadURL: "https://api.custom-upload-url/",
wantUploadURL: "https://api.custom-upload-url/",
},
{
name: "URL has API subdomain, adds trailing slash",
baseURL: "https://catalog.api.custom-url",
wantBaseURL: "https://catalog.api.custom-url/",
uploadURL: "https://catalog.api.custom-upload-url",
wantUploadURL: "https://catalog.api.custom-upload-url/",
},
{
name: "URL has API subdomain and trailing slash",
baseURL: "https://catalog.api.custom-url/",
wantBaseURL: "https://catalog.api.custom-url/",
uploadURL: "https://catalog.api.custom-upload-url/",
wantUploadURL: "https://catalog.api.custom-upload-url/",
},
{
name: "URL is not a proper API subdomain, adds enterprise suffix and slash",
baseURL: "https://cloud-api.custom-url",
wantBaseURL: "https://cloud-api.custom-url/api/v3/",
uploadURL: "https://cloud-api.custom-upload-url",
wantUploadURL: "https://cloud-api.custom-upload-url/api/uploads/",
},
{
name: "URL is not a proper API subdomain, adds enterprise suffix",
baseURL: "https://cloud-api.custom-url/",
wantBaseURL: "https://cloud-api.custom-url/api/v3/",
uploadURL: "https://cloud-api.custom-upload-url/",
wantUploadURL: "https://cloud-api.custom-upload-url/api/uploads/",
},
} {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
validate := func(c *Client, err error) {
t.Helper()
if test.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("error does not contain expected string %q: %v", test.wantErr, err)
}
return
}
if err != nil {
t.Fatalf("got unexpected error: %v", err)
}
if c.BaseURL.String() != test.wantBaseURL {
t.Errorf("BaseURL is %v, want %v", c.BaseURL.String(), test.wantBaseURL)
}
if c.UploadURL.String() != test.wantUploadURL {
t.Errorf("UploadURL is %v, want %v", c.UploadURL.String(), test.wantUploadURL)
}
}
validate(NewClient(nil).WithEnterpriseURLs(test.baseURL, test.uploadURL))
validate(new(Client).WithEnterpriseURLs(test.baseURL, test.uploadURL))
validate(NewEnterpriseClient(test.baseURL, test.uploadURL, nil))
})
}
}
// Ensure that length of Client.rateLimits is the same as number of fields in RateLimits struct.
func TestClient_rateLimits(t *testing.T) {
t.Parallel()
if got, want := len(Client{}.rateLimits), reflect.TypeOf(RateLimits{}).NumField(); got != want {
t.Errorf("len(Client{}.rateLimits) is %v, want %v", got, want)
}
}
func TestNewRequest(t *testing.T) {
t.Parallel()
c := NewClient(nil)
inURL, outURL := "/foo", defaultBaseURL+"foo"
inBody, outBody := &User{Login: String("l")}, `{"login":"l"}`+"\n"
req, _ := c.NewRequest("GET", inURL, inBody)
// test that relative URL was expanded
if got, want := req.URL.String(), outURL; got != want {
t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want)
}
// test that body was JSON encoded
body, _ := io.ReadAll(req.Body)
if got, want := string(body), outBody; got != want {
t.Errorf("NewRequest(%q) Body is %v, want %v", inBody, got, want)
}
userAgent := req.Header.Get("User-Agent")
// test that default user-agent is attached to the request
if got, want := userAgent, c.UserAgent; got != want {
t.Errorf("NewRequest() User-Agent is %v, want %v", got, want)
}
if !strings.Contains(userAgent, Version) {
t.Errorf("NewRequest() User-Agent should contain %v, found %v", Version, userAgent)
}
apiVersion := req.Header.Get(headerAPIVersion)
if got, want := apiVersion, defaultAPIVersion; got != want {
t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
}
req, _ = c.NewRequest("GET", inURL, inBody, WithVersion("2022-11-29"))
apiVersion = req.Header.Get(headerAPIVersion)
if got, want := apiVersion, "2022-11-29"; got != want {
t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
}
}
func TestNewRequest_invalidJSON(t *testing.T) {
t.Parallel()
c := NewClient(nil)
type T struct {
A map[interface{}]interface{}
}
_, err := c.NewRequest("GET", ".", &T{})
if err == nil {
t.Error("Expected error to be returned.")
}
if err, ok := err.(*json.UnsupportedTypeError); !ok {
t.Errorf("Expected a JSON error; got %#v.", err)
}
}
func TestNewRequest_badURL(t *testing.T) {
t.Parallel()
c := NewClient(nil)
_, err := c.NewRequest("GET", ":", nil)
testURLParseError(t, err)
}
func TestNewRequest_badMethod(t *testing.T) {
t.Parallel()
c := NewClient(nil)
if _, err := c.NewRequest("BOGUS\nMETHOD", ".", nil); err == nil {
t.Fatal("NewRequest returned nil; expected error")
}
}
// ensure that no User-Agent header is set if the client's UserAgent is empty.
// This caused a problem with Google's internal http client.
func TestNewRequest_emptyUserAgent(t *testing.T) {
t.Parallel()
c := NewClient(nil)
c.UserAgent = ""
req, err := c.NewRequest("GET", ".", nil)
if err != nil {
t.Fatalf("NewRequest returned unexpected error: %v", err)
}
if _, ok := req.Header["User-Agent"]; ok {
t.Fatal("constructed request contains unexpected User-Agent header")
}
}
// If a nil body is passed to github.NewRequest, make sure that nil is also
// passed to http.NewRequest. In most cases, passing an io.Reader that returns
// no content is fine, since there is no difference between an HTTP request
// body that is an empty string versus one that is not set at all. However in
// certain cases, intermediate systems may treat these differently resulting in
// subtle errors.
func TestNewRequest_emptyBody(t *testing.T) {
t.Parallel()
c := NewClient(nil)
req, err := c.NewRequest("GET", ".", nil)
if err != nil {
t.Fatalf("NewRequest returned unexpected error: %v", err)
}
if req.Body != nil {
t.Fatalf("constructed request contains a non-nil Body")
}
}
func TestNewRequest_errorForNoTrailingSlash(t *testing.T) {
t.Parallel()
tests := []struct {
rawurl string
wantError bool
}{
{rawurl: "https://example.com/api/v3", wantError: true},
{rawurl: "https://example.com/api/v3/", wantError: false},
}
c := NewClient(nil)
for _, test := range tests {
u, err := url.Parse(test.rawurl)
if err != nil {
t.Fatalf("url.Parse returned unexpected error: %v.", err)
}
c.BaseURL = u
if _, err := c.NewRequest(http.MethodGet, "test", nil); test.wantError && err == nil {
t.Fatalf("Expected error to be returned.")
} else if !test.wantError && err != nil {
t.Fatalf("NewRequest returned unexpected error: %v.", err)
}
}
}
func TestNewFormRequest(t *testing.T) {
t.Parallel()
c := NewClient(nil)
inURL, outURL := "/foo", defaultBaseURL+"foo"
form := url.Values{}
form.Add("login", "l")
inBody, outBody := strings.NewReader(form.Encode()), "login=l"
req, _ := c.NewFormRequest(inURL, inBody)
// test that relative URL was expanded
if got, want := req.URL.String(), outURL; got != want {
t.Errorf("NewFormRequest(%q) URL is %v, want %v", inURL, got, want)
}
// test that body was form encoded
body, _ := io.ReadAll(req.Body)
if got, want := string(body), outBody; got != want {
t.Errorf("NewFormRequest(%q) Body is %v, want %v", inBody, got, want)
}
// test that default user-agent is attached to the request
if got, want := req.Header.Get("User-Agent"), c.UserAgent; got != want {
t.Errorf("NewFormRequest() User-Agent is %v, want %v", got, want)
}
apiVersion := req.Header.Get(headerAPIVersion)
if got, want := apiVersion, defaultAPIVersion; got != want {
t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
}
req, _ = c.NewFormRequest(inURL, inBody, WithVersion("2022-11-29"))
apiVersion = req.Header.Get(headerAPIVersion)
if got, want := apiVersion, "2022-11-29"; got != want {
t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
}
}
func TestNewFormRequest_badURL(t *testing.T) {
t.Parallel()
c := NewClient(nil)
_, err := c.NewFormRequest(":", nil)
testURLParseError(t, err)
}
func TestNewFormRequest_emptyUserAgent(t *testing.T) {
t.Parallel()
c := NewClient(nil)
c.UserAgent = ""
req, err := c.NewFormRequest(".", nil)
if err != nil {
t.Fatalf("NewFormRequest returned unexpected error: %v", err)
}
if _, ok := req.Header["User-Agent"]; ok {
t.Fatal("constructed request contains unexpected User-Agent header")
}
}
func TestNewFormRequest_emptyBody(t *testing.T) {
t.Parallel()
c := NewClient(nil)
req, err := c.NewFormRequest(".", nil)
if err != nil {
t.Fatalf("NewFormRequest returned unexpected error: %v", err)
}
if req.Body != nil {
t.Fatalf("constructed request contains a non-nil Body")
}
}
func TestNewFormRequest_errorForNoTrailingSlash(t *testing.T) {
t.Parallel()
tests := []struct {
rawURL string
wantError bool
}{
{rawURL: "https://example.com/api/v3", wantError: true},
{rawURL: "https://example.com/api/v3/", wantError: false},
}
c := NewClient(nil)
for _, test := range tests {
u, err := url.Parse(test.rawURL)
if err != nil {
t.Fatalf("url.Parse returned unexpected error: %v.", err)
}
c.BaseURL = u
if _, err := c.NewFormRequest("test", nil); test.wantError && err == nil {
t.Fatalf("Expected error to be returned.")
} else if !test.wantError && err != nil {
t.Fatalf("NewFormRequest returned unexpected error: %v.", err)
}
}
}
func TestNewUploadRequest_WithVersion(t *testing.T) {
t.Parallel()
c := NewClient(nil)
req, _ := c.NewUploadRequest("https://example.com/", nil, 0, "")
apiVersion := req.Header.Get(headerAPIVersion)
if got, want := apiVersion, defaultAPIVersion; got != want {
t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
}
req, _ = c.NewUploadRequest("https://example.com/", nil, 0, "", WithVersion("2022-11-29"))
apiVersion = req.Header.Get(headerAPIVersion)
if got, want := apiVersion, "2022-11-29"; got != want {
t.Errorf("NewRequest() %v header is %v, want %v", headerAPIVersion, got, want)
}
}
func TestNewUploadRequest_badURL(t *testing.T) {
t.Parallel()
c := NewClient(nil)
_, err := c.NewUploadRequest(":", nil, 0, "")
testURLParseError(t, err)
const methodName = "NewUploadRequest"
testBadOptions(t, methodName, func() (err error) {
_, err = c.NewUploadRequest("\n", nil, -1, "\n")
return err
})
}
func TestNewUploadRequest_errorForNoTrailingSlash(t *testing.T) {
t.Parallel()
tests := []struct {
rawurl string
wantError bool
}{
{rawurl: "https://example.com/api/uploads", wantError: true},
{rawurl: "https://example.com/api/uploads/", wantError: false},
}
c := NewClient(nil)
for _, test := range tests {
u, err := url.Parse(test.rawurl)
if err != nil {
t.Fatalf("url.Parse returned unexpected error: %v.", err)
}
c.UploadURL = u
if _, err = c.NewUploadRequest("test", nil, 0, ""); test.wantError && err == nil {
t.Fatalf("Expected error to be returned.")
} else if !test.wantError && err != nil {
t.Fatalf("NewUploadRequest returned unexpected error: %v.", err)
}
}
}
func TestResponse_populatePageValues(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?page=1>; rel="first",` +
` <https://api.github.com/?page=2>; rel="prev",` +
` <https://api.github.com/?page=4>; rel="next",` +
` <https://api.github.com/?page=5>; rel="last"`,
},
},
}
response := newResponse(&r)
if got, want := response.FirstPage, 1; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
if got, want := response.PrevPage, 2; want != got {
t.Errorf("response.PrevPage: %v, want %v", got, want)
}
if got, want := response.NextPage, 4; want != got {
t.Errorf("response.NextPage: %v, want %v", got, want)
}
if got, want := response.LastPage, 5; want != got {
t.Errorf("response.LastPage: %v, want %v", got, want)
}
if got, want := response.NextPageToken, ""; want != got {
t.Errorf("response.NextPageToken: %v, want %v", got, want)
}
}
func TestResponse_populateSinceValues(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?since=1>; rel="first",` +
` <https://api.github.com/?since=2>; rel="prev",` +
` <https://api.github.com/?since=4>; rel="next",` +
` <https://api.github.com/?since=5>; rel="last"`,
},
},
}
response := newResponse(&r)
if got, want := response.FirstPage, 1; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
if got, want := response.PrevPage, 2; want != got {
t.Errorf("response.PrevPage: %v, want %v", got, want)
}
if got, want := response.NextPage, 4; want != got {
t.Errorf("response.NextPage: %v, want %v", got, want)
}
if got, want := response.LastPage, 5; want != got {
t.Errorf("response.LastPage: %v, want %v", got, want)
}
if got, want := response.NextPageToken, ""; want != got {
t.Errorf("response.NextPageToken: %v, want %v", got, want)
}
}
func TestResponse_SinceWithPage(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=1>; rel="first",` +
` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=2>; rel="prev",` +
` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=4>; rel="next",` +
` <https://api.github.com/?since=2021-12-04T10%3A43%3A42Z&page=5>; rel="last"`,
},
},
}
response := newResponse(&r)
if got, want := response.FirstPage, 1; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
if got, want := response.PrevPage, 2; want != got {
t.Errorf("response.PrevPage: %v, want %v", got, want)
}
if got, want := response.NextPage, 4; want != got {
t.Errorf("response.NextPage: %v, want %v", got, want)
}
if got, want := response.LastPage, 5; want != got {
t.Errorf("response.LastPage: %v, want %v", got, want)
}
if got, want := response.NextPageToken, ""; want != got {
t.Errorf("response.NextPageToken: %v, want %v", got, want)
}
}
func TestResponse_cursorPagination(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Status": {"200 OK"},
"Link": {`<https://api.github.com/resource?per_page=2&page=url-encoded-next-page-token>; rel="next"`},
},
}
response := newResponse(&r)
if got, want := response.FirstPage, 0; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
if got, want := response.PrevPage, 0; want != got {
t.Errorf("response.PrevPage: %v, want %v", got, want)
}
if got, want := response.NextPage, 0; want != got {
t.Errorf("response.NextPage: %v, want %v", got, want)
}
if got, want := response.LastPage, 0; want != got {
t.Errorf("response.LastPage: %v, want %v", got, want)
}
if got, want := response.NextPageToken, "url-encoded-next-page-token"; want != got {
t.Errorf("response.NextPageToken: %v, want %v", got, want)
}
// cursor-based pagination with "cursor" param
r = http.Response{
Header: http.Header{
"Link": {
`<https://api.github.com/?cursor=v1_12345678>; rel="next"`,
},
},
}
response = newResponse(&r)
if got, want := response.Cursor, "v1_12345678"; got != want {
t.Errorf("response.Cursor: %v, want %v", got, want)
}
}
func TestResponse_beforeAfterPagination(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?after=a1b2c3&before=>; rel="next",` +
` <https://api.github.com/?after=&before=>; rel="first",` +
` <https://api.github.com/?after=&before=d4e5f6>; rel="prev",`,
},
},
}
response := newResponse(&r)
if got, want := response.Before, "d4e5f6"; got != want {
t.Errorf("response.Before: %v, want %v", got, want)
}
if got, want := response.After, "a1b2c3"; got != want {
t.Errorf("response.After: %v, want %v", got, want)
}
if got, want := response.FirstPage, 0; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
if got, want := response.PrevPage, 0; want != got {
t.Errorf("response.PrevPage: %v, want %v", got, want)
}
if got, want := response.NextPage, 0; want != got {
t.Errorf("response.NextPage: %v, want %v", got, want)
}
if got, want := response.LastPage, 0; want != got {
t.Errorf("response.LastPage: %v, want %v", got, want)
}
if got, want := response.NextPageToken, ""; want != got {
t.Errorf("response.NextPageToken: %v, want %v", got, want)
}
}
func TestResponse_populatePageValues_invalid(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?page=1>,` +
`<https://api.github.com/?page=abc>; rel="first",` +
`https://api.github.com/?page=2; rel="prev",` +
`<https://api.github.com/>; rel="next",` +
`<https://api.github.com/?page=>; rel="last"`,
},
},
}
response := newResponse(&r)
if got, want := response.FirstPage, 0; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
if got, want := response.PrevPage, 0; got != want {
t.Errorf("response.PrevPage: %v, want %v", got, want)
}
if got, want := response.NextPage, 0; got != want {
t.Errorf("response.NextPage: %v, want %v", got, want)
}
if got, want := response.LastPage, 0; got != want {
t.Errorf("response.LastPage: %v, want %v", got, want)
}
// more invalid URLs
r = http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/%?page=2>; rel="first"`},
},
}
response = newResponse(&r)
if got, want := response.FirstPage, 0; got != want {
t.Errorf("response.FirstPage: %v, want %v", got, want)
}
}
func TestResponse_populateSinceValues_invalid(t *testing.T) {
t.Parallel()
r := http.Response{
Header: http.Header{
"Link": {`<https://api.github.com/?since=1>,` +
`<https://api.github.com/?since=abc>; rel="first",` +
`https://api.github.com/?since=2; rel="prev",` +
`<https://api.github.com/>; rel="next",` +
`<https://api.github.com/?since=>; rel="last"`,
},
},
}