-
Notifications
You must be signed in to change notification settings - Fork 89
/
helix_test.go
865 lines (702 loc) · 25 KB
/
helix_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
package helix
import (
"context"
"errors"
"log"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"testing"
"time"
)
type mockHTTPClient struct {
mockHandler http.HandlerFunc
}
func (mtc *mockHTTPClient) Do(req *http.Request) (*http.Response, error) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(mtc.mockHandler)
handler.ServeHTTP(rr, req)
return rr.Result(), nil
}
func newMockClient(options *Options, mockHandler http.HandlerFunc) *Client {
options.HTTPClient = &mockHTTPClient{mockHandler}
return &Client{
opts: options,
ctx: context.Background(),
}
}
func newMockHandler(statusCode int, json string, headers map[string]string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if len(headers) > 0 {
for key, value := range headers {
w.Header().Add(key, value)
}
}
w.WriteHeader(statusCode)
w.Write([]byte(json))
}
}
func TestNewClient(t *testing.T) {
t.Parallel()
testCases := []struct {
extpectErr bool
options *Options
}{
{
true,
&Options{}, // no client id
},
{
false,
&Options{
ClientID: "my-client-id",
ClientSecret: "my-client-secret",
HTTPClient: &http.Client{},
AppAccessToken: "my-app-access-token",
UserAccessToken: "my-user-access-token",
RefreshToken: "my-refresh-token",
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
RateLimitFunc: func(*Response) error { return nil },
RedirectURI: "http://localhost/auth/callback",
APIBaseURL: "http://localhost/proxy",
},
},
}
for _, testCase := range testCases {
client, err := NewClient(testCase.options)
if err != nil && !testCase.extpectErr {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
if testCase.extpectErr {
continue
}
opts := client.opts
if opts.ClientID != testCase.options.ClientID {
t.Errorf("expected clientID to be \"%s\", got \"%s\"", testCase.options.ClientID, opts.ClientID)
}
if opts.ClientSecret != testCase.options.ClientSecret {
t.Errorf("expected clientSecret to be \"%s\", got \"%s\"", testCase.options.ClientSecret, opts.ClientSecret)
}
if reflect.TypeOf(opts.RateLimitFunc).Kind() != reflect.Func {
t.Errorf("expected rateLimitFunc to be a function, got \"%+v\"", reflect.TypeOf(opts.RateLimitFunc).Kind())
}
if opts.HTTPClient != testCase.options.HTTPClient {
t.Errorf("expected httpClient to be \"%s\", got \"%s\"", testCase.options.HTTPClient, opts.HTTPClient)
}
if opts.UserAgent != testCase.options.UserAgent {
t.Errorf("expected userAgent to be \"%s\", got \"%s\"", testCase.options.UserAgent, opts.UserAgent)
}
if opts.AppAccessToken != testCase.options.AppAccessToken {
t.Errorf("expected accessToken to be \"%s\", got \"%s\"", testCase.options.AppAccessToken, opts.AppAccessToken)
}
if opts.UserAccessToken != testCase.options.UserAccessToken {
t.Errorf("expected accessToken to be \"%s\", got \"%s\"", testCase.options.UserAccessToken, opts.UserAccessToken)
}
if opts.RefreshToken != testCase.options.RefreshToken {
t.Errorf("expected refreshToken to be \"%s\", got \"%s\"", testCase.options.RefreshToken, opts.RefreshToken)
}
if opts.RedirectURI != testCase.options.RedirectURI {
t.Errorf("expected redirectURI to be \"%s\", got \"%s\"", testCase.options.RedirectURI, opts.RedirectURI)
}
if opts.APIBaseURL != testCase.options.APIBaseURL {
t.Errorf("expected APIBaseURL to be \"%s\", got \"%s\"", testCase.options.APIBaseURL, opts.APIBaseURL)
}
}
}
func TestNewClientDefault(t *testing.T) {
t.Parallel()
options := &Options{ClientID: "my-client-id"}
client, err := NewClient(options)
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
opts := client.opts
if opts.ClientID != options.ClientID {
t.Errorf("expected clientID to be \"%s\", got \"%s\"", options.ClientID, opts.ClientID)
}
if opts.ClientSecret != "" {
t.Errorf("expected clientSecret to be \"%s\", got \"%s\"", options.ClientSecret, opts.ClientSecret)
}
if opts.UserAgent != "" {
t.Errorf("expected userAgent to be \"%s\", got \"%s\"", "", opts.UserAgent)
}
if opts.UserAccessToken != "" {
t.Errorf("expected accesstoken to be \"\", got \"%s\"", opts.UserAccessToken)
}
if opts.HTTPClient != http.DefaultClient {
t.Errorf("expected httpClient to be \"%v\", got \"%v\"", http.DefaultClient, opts.HTTPClient)
}
if opts.RateLimitFunc != nil {
t.Errorf("expected rateLimitFunc to be \"%v\", got \"%v\"", nil, opts.RateLimitFunc)
}
if opts.RedirectURI != options.RedirectURI {
t.Errorf("expected redirectURI to be \"%s\", got \"%s\"", options.RedirectURI, opts.RedirectURI)
}
}
func TestNewClientHasContext(t *testing.T) {
t.Parallel()
contextExists := false
mockClient := &mockHTTPClient{func(w http.ResponseWriter, r *http.Request) {
contextExists = r.Context() != nil
}}
c, err := NewClient(&Options{
ClientID: "test",
HTTPClient: mockClient,
})
if err != nil {
t.Errorf("could not create client: %v", err)
return
}
_, err = c.GetStreams(nil)
if err != nil {
t.Errorf("Did not expect error, got \"%s\"", err)
}
if !contextExists {
t.Error("Expected context to be passed into request, got nil context")
}
}
func TestNewClientWithContext(t *testing.T) {
t.Parallel()
type CtxKey string
ctxKey := CtxKey("test")
contextExists := false
mockClient := &mockHTTPClient{func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
contextExists = ctx != nil && ctx.Value(ctxKey) != nil
}}
ctx := context.WithValue(context.Background(), ctxKey, 0)
c, err := NewClientWithContext(ctx, &Options{
ClientID: "test",
HTTPClient: mockClient,
})
if err != nil {
t.Errorf("could not create client with context: %v", err)
return
}
_, err = c.GetStreams(nil)
if err != nil {
t.Errorf("Did not expect error, got \"%s\"", err)
}
if !contextExists {
t.Error("Expected context to be passed into request, got nil context")
}
}
func TestNewClientWithContextCancel(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wasCanceled := false
mockClient := &mockHTTPClient{func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
wasCanceled = true
}}
c, err := NewClientWithContext(ctx, &Options{
ClientID: "test",
HTTPClient: mockClient,
})
if err != nil {
t.Errorf("Could not create client with context: %v", err)
return
}
cancel()
_, err = c.GetStreams(nil)
if err != nil {
t.Errorf("Did not expect error, got \"%s\"", err)
}
if !wasCanceled {
t.Error("Context was not cancelled")
}
}
func TestNoContext(t *testing.T) {
t.Parallel()
contextExists := false
handlerFunc := func(w http.ResponseWriter, r *http.Request) {
if r.Context() != nil {
contextExists = true
}
}
c := newMockClient(&Options{}, handlerFunc)
_, err := c.GetStreams(nil)
if err != nil {
t.Errorf("Did not expect error, got \"%s\"", err)
}
if !contextExists {
t.Error("Expected context to be passed into request, got nil context")
}
}
func TestRatelimitCallback(t *testing.T) {
t.Parallel()
respBody1 := `{"error":"Too Many Requests","status":429,"message":"Request limit exceeded"}`
options1 := &Options{
ClientID: "my-client-id",
RateLimitFunc: func(resp *Response) error {
return nil
},
}
c := newMockClient(options1, newMockHandler(http.StatusTooManyRequests, respBody1, nil))
go func() {
_, err := c.GetStreams(&StreamsParams{})
if err != nil {
t.Errorf("Did not expect error, got \"%s\"", err.Error())
}
}()
time.Sleep(5 * time.Millisecond)
respBody2 := `{"data":[{"id":"EncouragingPluckySlothSSSsss","url":"https://clips.twitch.tv/EncouragingPluckySlothSSSsss","embed_url":"https://clips.twitch.tv/embed?clip=EncouragingPluckySlothSSSsss","broadcaster_id":"26490481","creator_id":"143839181","video_id":"222004532","game_id":"490377","language":"en","title":"summit and fat tim discover how to use maps","view_count":81808,"created_at":"2018-01-25T04:04:15Z","thumbnail_url":"https://clips-media-assets.twitch.tv/182509178-preview-480x272.jpg"}]}`
options2 := &Options{
ClientID: "my-client-id",
}
c = newMockClient(options2, newMockHandler(http.StatusOK, respBody2, nil))
_, err := c.GetStreams(&StreamsParams{})
if err != nil {
t.Errorf("Did not expect error, got \"%s\"", err.Error())
}
}
func TestRatelimitCallbackFailsOnError(t *testing.T) {
t.Parallel()
errMsg := "Oops! Your rate limiter funciton is broken :("
respBody1 := `{"error":"Too Many Requests","status":429,"message":"Request limit exceeded"}`
options1 := &Options{
ClientID: "my-client-id",
RateLimitFunc: func(resp *Response) error {
return errors.New(errMsg)
},
}
c := newMockClient(options1, newMockHandler(http.StatusTooManyRequests, respBody1, nil))
_, err := c.GetStreams(&StreamsParams{})
if err == nil {
t.Error("Expected error, got none")
}
if err.Error() != errMsg {
t.Errorf("Expected error to be \"%s\", got \"%s\"", errMsg, err.Error())
}
}
func TestAutomaticUserTokenRefresh(t *testing.T) {
t.Parallel()
options := &Options{
ClientID: "client-id",
ClientSecret: "old-client-secret",
UserAccessToken: "old-user-token",
RefreshToken: "old-refresh-token",
}
client := newMockClient(options, func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/oauth2/token") {
w.Write([]byte(`{"access_token":"new-access-token","expires_in":14154,"refresh_token":"new-refresh-token","scope":["analytics:read:games","bits:read","clips:edit","user:edit","user:read:email"]}`))
} else if strings.Contains(r.URL.Path, "/channels/followers") {
if strings.Contains(r.Header.Get("Authorization"), "old-user-token") {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"Unauthorized","status":401,"message":"Invalid OAuth token"}`))
} else {
w.Write([]byte(`{"total":8,"data":[],"pagination":{}}`))
}
} else {
log.Printf("Unknown URL sent to test server: %s", r.URL.Path)
}
})
_, err := client.GetChannelFollows(&GetChannelFollowsParams{}) // any method works
if err != nil {
t.Fatalf("Did not expect an error, got \"%s\"", err.Error())
}
time.Sleep(5 * time.Millisecond)
if client.opts.UserAccessToken != "new-access-token" {
t.Errorf("expected UserAccessToken to be %q, got %q", "new-access-token", client.opts.UserAccessToken)
}
if client.opts.RefreshToken != "new-refresh-token" {
t.Errorf("expected RefreshToken to be %q, got %q", "new-refresh-token", client.opts.RefreshToken)
}
}
func TestSetRequestHeaders(t *testing.T) {
t.Parallel()
testCases := []struct {
endpoint string
method string
userBearerToken string
appBearerToken string
}{
{"/users", "GET", "my-user-access-token", "my-app-access-token"},
{"/entitlements/upload", "POST", "", "my-app-access-token"},
{"/streams", "GET", "", ""},
}
for _, testCase := range testCases {
client, err := NewClient(&Options{
ClientID: "my-client-id",
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
AppAccessToken: testCase.appBearerToken,
UserAccessToken: testCase.userBearerToken,
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
req, _ := http.NewRequest(testCase.method, testCase.endpoint, nil)
client.setRequestHeaders(req)
if testCase.userBearerToken != "" {
expectedAuthHeader := "Bearer " + testCase.userBearerToken
if req.Header.Get("Authorization") != expectedAuthHeader {
t.Errorf("expected Authorization header to be \"%s\", got \"%s\"", expectedAuthHeader, req.Header.Get("Authorization"))
}
}
if testCase.userBearerToken == "" && testCase.appBearerToken != "" {
expectedAuthHeader := "Bearer " + testCase.appBearerToken
if req.Header.Get("Authorization") != expectedAuthHeader {
t.Errorf("expected Authorization header to be \"%s\", got \"%s\"", expectedAuthHeader, req.Header.Get("Authorization"))
}
}
if testCase.userBearerToken == "" && testCase.appBearerToken == "" {
if req.Header.Get("Authorization") != "" {
t.Error("did not expect Authorization header to be set")
}
}
if req.Header.Get("User-Agent") != client.opts.UserAgent {
t.Errorf("expected User-Agent header to be \"%s\", got \"%s\"", client.opts.UserAgent, req.Header.Get("User-Agent"))
}
}
}
func TestGetRateLimitHeaders(t *testing.T) {
t.Parallel()
testCases := []struct {
statusCode int
options *Options
Logins []string
respBody string
headerLimit string
headerRemaining string
headerReset string
}{
{
http.StatusOK,
&Options{ClientID: "my-client-id"},
[]string{"summit1g"},
`{"data":[{"id":"26490481","login":"summit1g","display_name":"summit1g","type":"","broadcaster_type":"partner","description":"I'm a competitive CounterStrike player who likes to play casually now and many other games. You will mostly see me play CS, H1Z1,and single player games at night. There will be many othergames played on this stream in the future as they come out:D","profile_image_url":"https://static-cdn.jtvnw.net/jtv_user_pictures/200cea12142f2384-profile_image-300x300.png","offline_image_url":"https://static-cdn.jtvnw.net/jtv_user_pictures/summit1g-channel_offline_image-e2f9a1df9e695ec1-1920x1080.png","view_count":202707885}]}`,
"30",
"29",
"1529183210",
},
{
http.StatusOK,
&Options{ClientID: "my-client-id"},
[]string{"summit1g"},
`{"data":[{"id":"26490481","login":"summit1g","display_name":"summit1g","type":"","broadcaster_type":"partner","description":"I'm a competitive CounterStrike player who likes to play casually now and many other games. You will mostly see me play CS, H1Z1,and single player games at night. There will be many othergames played on this stream in the future as they come out:D","profile_image_url":"https://static-cdn.jtvnw.net/jtv_user_pictures/200cea12142f2384-profile_image-300x300.png","offline_image_url":"https://static-cdn.jtvnw.net/jtv_user_pictures/summit1g-channel_offline_image-e2f9a1df9e695ec1-1920x1080.png","view_count":202707885}]}`,
"",
"",
"",
},
}
for _, testCase := range testCases {
mockRespHeaders := make(map[string]string)
if testCase.headerLimit != "" {
mockRespHeaders["Ratelimit-Limit"] = testCase.headerLimit
mockRespHeaders["Ratelimit-Remaining"] = testCase.headerRemaining
mockRespHeaders["Ratelimit-Reset"] = testCase.headerReset
}
c := newMockClient(testCase.options, newMockHandler(testCase.statusCode, testCase.respBody, mockRespHeaders))
resp, err := c.GetUsers(&UsersParams{
Logins: testCase.Logins,
})
if err != nil {
t.Error(err)
}
expctedHeaderLimit, _ := strconv.Atoi(testCase.headerLimit)
if resp.GetRateLimit() != expctedHeaderLimit {
t.Errorf("expected \"Ratelimit-Limit\" to be \"%d\", got \"%d\"", expctedHeaderLimit, resp.GetRateLimit())
}
expctedHeaderRemaining, _ := strconv.Atoi(testCase.headerRemaining)
if resp.GetRateLimitRemaining() != expctedHeaderRemaining {
t.Errorf("expected \"Ratelimit-Remaining\" to be \"%d\", got \"%d\"", expctedHeaderRemaining, resp.GetRateLimitRemaining())
}
expctedHeaderReset, _ := strconv.Atoi(testCase.headerReset)
if resp.GetRateLimitReset() != expctedHeaderReset {
t.Errorf("expected \"Ratelimit-Reset\" to be \"%d\", got \"%d\"", expctedHeaderReset, resp.GetRateLimitReset())
}
}
}
type badMockHTTPClient struct {
mockHandler http.HandlerFunc
}
func (mtc *badMockHTTPClient) Do(req *http.Request) (*http.Response, error) {
return nil, errors.New("Oops, that's bad :(")
}
func TestFailedHTTPClientDoRequest(t *testing.T) {
t.Parallel()
options := &Options{
ClientID: "my-client-id",
HTTPClient: &badMockHTTPClient{
newMockHandler(0, "", nil),
},
}
c := &Client{
opts: options,
ctx: context.Background(),
}
_, err := c.GetUsers(&UsersParams{
Logins: []string{"summit1g"},
})
if err == nil {
t.Error("expected error but got nil")
}
if err.Error() != "Failed to execute API request: Oops, that's bad :(" {
t.Errorf("expected error does match return error: %v", err)
}
}
func TestDecodingBadJSON(t *testing.T) {
t.Parallel()
// Invalid JSON (missing `"` from the beginning)
c := newMockClient(&Options{ClientID: "my-client-id"}, newMockHandler(http.StatusOK, `data":["some":"data"]}`, nil))
_, err := c.GetUsers(&UsersParams{
Logins: []string{"summit1g"},
})
if err == nil {
t.Error("expected error but got nil")
}
if err.Error() != "Failed to decode API response: invalid character 'd' looking for beginning of value" {
t.Error("expected error does match return error")
}
}
func TestGetAppAccessToken(t *testing.T) {
t.Parallel()
accessToken := "my-app-access-token"
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
client.SetAppAccessToken(accessToken)
if client.GetAppAccessToken() != accessToken {
t.Errorf("expected GetAppAccessToken to return \"%s\", got \"%s\"", accessToken, client.GetAppAccessToken())
}
}
func TestSetAppAccessToken(t *testing.T) {
t.Parallel()
accessToken := "my-app-access-token"
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
client.SetAppAccessToken(accessToken)
if client.opts.AppAccessToken != accessToken {
t.Errorf("expected accessToken to be \"%s\", got \"%s\"", accessToken, client.opts.AppAccessToken)
}
}
func TestGetUserAccessToken(t *testing.T) {
t.Parallel()
accessToken := "my-user-access-token"
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
client.SetUserAccessToken(accessToken)
if client.GetUserAccessToken() != accessToken {
t.Errorf("expected GetUserAccessToken to return \"%s\", got \"%s\"", accessToken, client.GetUserAccessToken())
}
}
func TestSetUserAccessToken(t *testing.T) {
t.Parallel()
accessToken := "my-user-access-token"
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
client.SetUserAccessToken(accessToken)
if client.opts.UserAccessToken != accessToken {
t.Errorf("expected accessToken to be \"%s\", got \"%s\"", accessToken, client.opts.UserAccessToken)
}
}
func TestGetRefreshToken(t *testing.T) {
t.Parallel()
refreshToken := "my-refresh-token"
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
client.SetRefreshToken(refreshToken)
if client.GetRefreshToken() != refreshToken {
t.Errorf("expected GetRefreshToken to return \"%s\", got \"%s\"", refreshToken, client.GetRefreshToken())
}
}
func TestSetRefreshToken(t *testing.T) {
t.Parallel()
refreshToken := "my-refresh-token"
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
client.SetRefreshToken(refreshToken)
if client.opts.RefreshToken != refreshToken {
t.Errorf("expected RefreshToken to be \"%s\", got \"%s\"", refreshToken, client.opts.RefreshToken)
}
}
func TestSetUserAgent(t *testing.T) {
t.Parallel()
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
userAgent := "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36"
client.SetUserAgent(userAgent)
if client.opts.UserAgent != userAgent {
t.Errorf("expected accessToken to be \"%s\", got \"%s\"", userAgent, client.opts.UserAgent)
}
}
func TestSetRedirectURI(t *testing.T) {
t.Parallel()
client, err := NewClient(&Options{
ClientID: "cid",
})
if err != nil {
t.Errorf("Did not expect an error, got \"%s\"", err.Error())
}
redirectURI := "http://localhost/auth/callback"
client.SetRedirectURI(redirectURI)
if client.opts.RedirectURI != redirectURI {
t.Errorf("expected redirectURI to be \"%s\", got \"%s\"", redirectURI, client.opts.RedirectURI)
}
}
func TestOnUserAccessTokenRefreshed(t *testing.T) {
t.Parallel()
options := &Options{
ClientID: "client-id",
ClientSecret: "old-client-secret",
UserAccessToken: "old-user-token",
RefreshToken: "old-refresh-token",
}
client := newMockClient(options, func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/oauth2/token") {
w.Write([]byte(`{"access_token":"new-access-token","expires_in":14154,"refresh_token":"new-refresh-token","scope":["analytics:read:games","bits:read","clips:edit","user:edit","user:read:email"]}`))
} else if strings.Contains(r.URL.Path, "/channels/followers") {
if strings.Contains(r.Header.Get("Authorization"), "old-user-token") {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"Unauthorized","status":401,"message":"Invalid OAuth token"}`))
} else {
w.Write([]byte(`{"total":8,"data":[],"pagination":{}}`))
}
} else {
log.Printf("Unknown URL sent to test server: %s", r.URL.Path)
}
})
var newAccessToken, newRefreshToken string
client.OnUserAccessTokenRefreshed(func(a, r string) {
newAccessToken = a
newRefreshToken = r
})
wantNewAccessToken := "new-access-token"
wantNewRefreshToken := "new-refresh-token"
_, err := client.GetChannelFollows(&GetChannelFollowsParams{}) // any method works
if err != nil {
t.Fatalf("Did not expect an error, got \"%s\"", err.Error())
}
time.Sleep(10 * time.Millisecond)
if newAccessToken != wantNewAccessToken {
t.Errorf("expected newAccessToken to be %q, got %q", wantNewAccessToken, newAccessToken)
}
if newRefreshToken != wantNewRefreshToken {
t.Errorf("expected newRefreshToken to be %q, got %q", wantNewRefreshToken, newRefreshToken)
}
}
func TestHydrateRequestCommon(t *testing.T) {
t.Parallel()
var sourceResponse Response
sampleStatusCode := 200
sampleHeaders := http.Header{}
sampleHeaders.Set("Content-Type", "application/json")
sampleError := "foo"
sampleErrorStatus := 1
sampleErrorMessage := "something done broke"
sourceResponse.ResponseCommon.StatusCode = sampleStatusCode
sourceResponse.ResponseCommon.Header = sampleHeaders
sourceResponse.ResponseCommon.Error = sampleError
sourceResponse.ResponseCommon.ErrorStatus = sampleErrorStatus
sourceResponse.ResponseCommon.ErrorMessage = sampleErrorMessage
var targetResponse Response
sourceResponse.HydrateResponseCommon(&targetResponse.ResponseCommon)
if targetResponse.StatusCode != sampleStatusCode {
t.Errorf("expected StatusCode to be \"%d\", got \"%d\"", sampleStatusCode, targetResponse.ResponseCommon.StatusCode)
}
if targetResponse.Header.Get("Content-Type") != "application/json" {
t.Errorf("expected headers to match")
}
if targetResponse.Error != sampleError {
t.Errorf("expected Error to be \"%s\", got \"%s\"", sampleError, targetResponse.ResponseCommon.Error)
}
if targetResponse.ErrorStatus != sampleErrorStatus {
t.Errorf("expected ErrorStatus to be \"%d\", got \"%d\"", sampleErrorStatus, targetResponse.ResponseCommon.ErrorStatus)
}
if targetResponse.ErrorMessage != sampleErrorMessage {
t.Errorf("expected ErrorMessage to be \"%s\", got \"%s\"", sampleErrorMessage, targetResponse.ResponseCommon.ErrorMessage)
}
}
func TestQueryStringBuilderAllQuery(t *testing.T) {
t.Parallel()
// For structs where every member has a query tag
type Struct struct {
Foo string `query:"foo"`
Bar string `query:"bar"`
}
v := &Struct{Foo: "value", Bar: "value"}
expectedQueryString := `bar=value&foo=value`
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
t.Error("request creation failed")
}
q, err := buildQueryString(req, v)
if err != nil {
t.Errorf("expected buildQueryString to not error, got \"%s\"", err)
}
if q != expectedQueryString {
t.Errorf(`expected q to be "%s", got "%s"`, expectedQueryString, q)
}
}
func TestQueryStringBuilderPartialQuery(t *testing.T) {
t.Parallel()
// For structs where only some members have a query tag
type Struct struct {
Foo string `query:"foo"`
Bar string `json:"bar"`
}
v := &Struct{Foo: "value", Bar: "value"}
expectedQueryString := `foo=value`
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
t.Error("request creation failed")
}
q, err := buildQueryString(req, v)
if err != nil {
t.Errorf("expected buildQueryString to not error, got \"%s\"", err)
}
if q != expectedQueryString {
t.Errorf(`expected q to be "%s", got "%s"`, expectedQueryString, q)
}
}
func TestQueryStringBuilderNoQuery(t *testing.T) {
t.Parallel()
// For structs where no members have query tags
type Struct struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
v := &Struct{Foo: "value", Bar: "value"}
expectedQueryString := ``
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
t.Error("request creation failed")
}
q, err := buildQueryString(req, v)
if err != nil {
t.Errorf("expected buildQueryString to not error, got \"%s\"", err)
}
if q != expectedQueryString {
t.Errorf(`expected q to be "%s", got "%s"`, expectedQueryString, q)
}
}