-
Notifications
You must be signed in to change notification settings - Fork 255
/
client_test.go
1285 lines (1136 loc) · 31.9 KB
/
client_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 (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package retryablehttp
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/hashicorp/go-hclog"
)
func TestRequest(t *testing.T) {
// Fails on invalid request
_, err := NewRequest("GET", "://foo", nil)
if err == nil {
t.Fatalf("should error")
}
// Works with no request body
_, err = NewRequest("GET", "http://foo", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
// Works with request body
body := bytes.NewReader([]byte("yo"))
req, err := NewRequest("GET", "/", body)
if err != nil {
t.Fatalf("err: %v", err)
}
// Request allows typical HTTP request forming methods
req.Header.Set("X-Test", "foo")
if v, ok := req.Header["X-Test"]; !ok || len(v) != 1 || v[0] != "foo" {
t.Fatalf("bad headers: %v", req.Header)
}
// Sets the Content-Length automatically for LenReaders
if req.ContentLength != 2 {
t.Fatalf("bad ContentLength: %d", req.ContentLength)
}
}
func TestFromRequest(t *testing.T) {
// Works with no request body
httpReq, err := http.NewRequest("GET", "http://foo", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
_, err = FromRequest(httpReq)
if err != nil {
t.Fatalf("err: %v", err)
}
// Works with request body
body := bytes.NewReader([]byte("yo"))
httpReq, err = http.NewRequest("GET", "/", body)
if err != nil {
t.Fatalf("err: %v", err)
}
req, err := FromRequest(httpReq)
if err != nil {
t.Fatalf("err: %v", err)
}
// Preserves headers
httpReq.Header.Set("X-Test", "foo")
if v, ok := req.Header["X-Test"]; !ok || len(v) != 1 || v[0] != "foo" {
t.Fatalf("bad headers: %v", req.Header)
}
// Preserves the Content-Length automatically for LenReaders
if req.ContentLength != 2 {
t.Fatalf("bad ContentLength: %d", req.ContentLength)
}
}
// Since normal ways we would generate a Reader have special cases, use a
// custom type here
type custReader struct {
val string
pos int
}
func (c *custReader) Read(p []byte) (n int, err error) {
if c.val == "" {
c.val = "hello"
}
if c.pos >= len(c.val) {
return 0, io.EOF
}
var i int
for i = 0; i < len(p) && i+c.pos < len(c.val); i++ {
p[i] = c.val[i+c.pos]
}
c.pos += i
return i, nil
}
func TestClient_Do(t *testing.T) {
testBytes := []byte("hello")
// Native func
testClientDo(t, ReaderFunc(func() (io.Reader, error) {
return bytes.NewReader(testBytes), nil
}))
// Native func, different Go type
testClientDo(t, func() (io.Reader, error) {
return bytes.NewReader(testBytes), nil
})
// []byte
testClientDo(t, testBytes)
// *bytes.Buffer
testClientDo(t, bytes.NewBuffer(testBytes))
// *bytes.Reader
testClientDo(t, bytes.NewReader(testBytes))
// io.ReadSeeker
testClientDo(t, strings.NewReader(string(testBytes)))
// io.Reader
testClientDo(t, &custReader{})
}
func testClientDo(t *testing.T, body interface{}) {
// Create a request
req, err := NewRequest("PUT", "http://127.0.0.1:28934/v1/foo", body)
if err != nil {
t.Fatalf("err: %v", err)
}
req.Header.Set("foo", "bar")
// Track the number of times the logging hook was called
retryCount := -1
// Create the client. Use short retry windows.
client := NewClient()
client.RetryWaitMin = 10 * time.Millisecond
client.RetryWaitMax = 50 * time.Millisecond
client.RetryMax = 50
client.RequestLogHook = func(logger Logger, req *http.Request, retryNumber int) {
retryCount = retryNumber
if logger != client.Logger {
t.Fatalf("Client logger was not passed to logging hook")
}
dumpBytes, err := httputil.DumpRequestOut(req, false)
if err != nil {
t.Fatal("Dumping requests failed")
}
dumpString := string(dumpBytes)
if !strings.Contains(dumpString, "PUT /v1/foo") {
t.Fatalf("Bad request dump:\n%s", dumpString)
}
}
// Send the request
var resp *http.Response
doneCh := make(chan struct{})
errCh := make(chan error, 1)
go func() {
defer close(doneCh)
defer close(errCh)
var err error
resp, err = client.Do(req)
errCh <- err
}()
select {
case <-doneCh:
t.Fatalf("should retry on error")
case <-time.After(200 * time.Millisecond):
// Client should still be retrying due to connection failure.
}
// Create the mock handler. First we return a 500-range response to ensure
// that we power through and keep retrying in the face of recoverable
// errors.
code := int64(500)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check the request details
if r.Method != "PUT" {
t.Fatalf("bad method: %s", r.Method)
}
if r.RequestURI != "/v1/foo" {
t.Fatalf("bad uri: %s", r.RequestURI)
}
// Check the headers
if v := r.Header.Get("foo"); v != "bar" {
t.Fatalf("bad header: expect foo=bar, got foo=%v", v)
}
// Check the payload
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("err: %s", err)
}
expected := []byte("hello")
if !bytes.Equal(body, expected) {
t.Fatalf("bad: %v", body)
}
w.WriteHeader(int(atomic.LoadInt64(&code)))
})
// Create a test server
list, err := net.Listen("tcp", ":28934")
if err != nil {
t.Fatalf("err: %v", err)
}
defer list.Close()
go http.Serve(list, handler)
// Wait again
select {
case <-doneCh:
t.Fatalf("should retry on 500-range")
case <-time.After(200 * time.Millisecond):
// Client should still be retrying due to 500's.
}
// Start returning 200's
atomic.StoreInt64(&code, 200)
// Wait again
select {
case <-doneCh:
case <-time.After(time.Second):
t.Fatalf("timed out")
}
if resp.StatusCode != 200 {
t.Fatalf("exected 200, got: %d", resp.StatusCode)
}
if retryCount < 0 {
t.Fatal("request log hook was not called")
}
err = <-errCh
if err != nil {
t.Fatalf("err: %v", err)
}
}
func TestClient_Do_WithResponseHandler(t *testing.T) {
// Create the client. Use short retry windows so we fail faster.
client := NewClient()
client.RetryWaitMin = 10 * time.Millisecond
client.RetryWaitMax = 10 * time.Millisecond
client.RetryMax = 2
var checks int
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
checks++
if err != nil && strings.Contains(err.Error(), "nonretryable") {
return false, nil
}
return DefaultRetryPolicy(context.TODO(), resp, err)
}
// Mock server which always responds 200.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
var shouldSucceed bool
tests := []struct {
name string
handler ResponseHandlerFunc
expectedChecks int // often 2x number of attempts since we check twice
err string
}{
{
name: "nil handler",
handler: nil,
expectedChecks: 1,
},
{
name: "handler always succeeds",
handler: func(*http.Response) error {
return nil
},
expectedChecks: 2,
},
{
name: "handler always fails in a retryable way",
handler: func(*http.Response) error {
return errors.New("retryable failure")
},
expectedChecks: 6,
},
{
name: "handler always fails in a nonretryable way",
handler: func(*http.Response) error {
return errors.New("nonretryable failure")
},
expectedChecks: 2,
},
{
name: "handler succeeds on second attempt",
handler: func(*http.Response) error {
if shouldSucceed {
return nil
}
shouldSucceed = true
return errors.New("retryable failure")
},
expectedChecks: 4,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
checks = 0
shouldSucceed = false
// Create the request
req, err := NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
req.SetResponseHandler(tt.handler)
// Send the request.
_, err = client.Do(req)
if err != nil && !strings.Contains(err.Error(), tt.err) {
t.Fatalf("error does not match expectation, expected: %s, got: %s", tt.err, err.Error())
}
if err == nil && tt.err != "" {
t.Fatalf("no error, expected: %s", tt.err)
}
if checks != tt.expectedChecks {
t.Fatalf("expected %d attempts, got %d attempts", tt.expectedChecks, checks)
}
})
}
}
func TestClient_Do_WithPrepareRetry(t *testing.T) {
// Create the client. Use short retry windows so we fail faster.
client := NewClient()
client.RetryWaitMin = 10 * time.Millisecond
client.RetryWaitMax = 10 * time.Millisecond
client.RetryMax = 2
var checks int
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
checks++
if err != nil && strings.Contains(err.Error(), "nonretryable") {
return false, nil
}
return DefaultRetryPolicy(context.TODO(), resp, err)
}
var prepareChecks int
client.PrepareRetry = func(req *http.Request) error {
prepareChecks++
req.Header.Set("foo", strconv.Itoa(prepareChecks))
return nil
}
// Mock server which always responds 200.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
var shouldSucceed bool
tests := []struct {
name string
handler ResponseHandlerFunc
expectedChecks int // often 2x number of attempts since we check twice
expectedPrepareChecks int
err string
}{
{
name: "nil handler",
handler: nil,
expectedChecks: 1,
expectedPrepareChecks: 0,
},
{
name: "handler always succeeds",
handler: func(*http.Response) error {
return nil
},
expectedChecks: 2,
expectedPrepareChecks: 0,
},
{
name: "handler always fails in a retryable way",
handler: func(*http.Response) error {
return errors.New("retryable failure")
},
expectedChecks: 6,
expectedPrepareChecks: 2,
},
{
name: "handler always fails in a nonretryable way",
handler: func(*http.Response) error {
return errors.New("nonretryable failure")
},
expectedChecks: 2,
expectedPrepareChecks: 0,
},
{
name: "handler succeeds on second attempt",
handler: func(*http.Response) error {
if shouldSucceed {
return nil
}
shouldSucceed = true
return errors.New("retryable failure")
},
expectedChecks: 4,
expectedPrepareChecks: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
checks = 0
prepareChecks = 0
shouldSucceed = false
// Create the request
req, err := NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
req.SetResponseHandler(tt.handler)
// Send the request.
_, err = client.Do(req)
if err != nil && !strings.Contains(err.Error(), tt.err) {
t.Fatalf("error does not match expectation, expected: %s, got: %s", tt.err, err.Error())
}
if err == nil && tt.err != "" {
t.Fatalf("no error, expected: %s", tt.err)
}
if checks != tt.expectedChecks {
t.Fatalf("expected %d attempts, got %d attempts", tt.expectedChecks, checks)
}
if prepareChecks != tt.expectedPrepareChecks {
t.Fatalf("expected %d attempts of prepare check, got %d attempts", tt.expectedPrepareChecks, prepareChecks)
}
header := req.Request.Header.Get("foo")
if tt.expectedPrepareChecks == 0 && header != "" {
t.Fatalf("expected no changes to request header 'foo', but got '%s'", header)
}
expectedHeader := strconv.Itoa(tt.expectedPrepareChecks)
if tt.expectedPrepareChecks != 0 && header != expectedHeader {
t.Fatalf("expected changes in request header 'foo' '%s', but got '%s'", expectedHeader, header)
}
})
}
}
func TestClient_Do_fails(t *testing.T) {
// Mock server which always responds 500.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
defer ts.Close()
serverUrlWithBasicAuth, err := url.Parse(ts.URL)
if err != nil {
t.Fatalf("failed parsing test server url: %s", ts.URL)
}
serverUrlWithBasicAuth.User = url.UserPassword("user", "pasten")
tests := []struct {
url string
name string
cr CheckRetry
err string
}{
{
url: ts.URL,
name: "default_retry_policy",
cr: DefaultRetryPolicy,
err: "giving up after 3 attempt(s)",
},
{
url: serverUrlWithBasicAuth.String(),
name: "default_retry_policy_url_with_basic_auth",
cr: DefaultRetryPolicy,
err: redactURL(serverUrlWithBasicAuth) + " giving up after 3 attempt(s)",
},
{
url: ts.URL,
name: "error_propagated_retry_policy",
cr: ErrorPropagatedRetryPolicy,
err: "giving up after 3 attempt(s): unexpected HTTP status 500 Internal Server Error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create the client. Use short retry windows so we fail faster.
client := NewClient()
client.RetryWaitMin = 10 * time.Millisecond
client.RetryWaitMax = 10 * time.Millisecond
client.CheckRetry = tt.cr
client.RetryMax = 2
// Create the request
req, err := NewRequest("POST", tt.url, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
// Send the request.
_, err = client.Do(req)
if err == nil || !strings.HasSuffix(err.Error(), tt.err) {
t.Fatalf("expected %#v, got: %#v", tt.err, err)
}
})
}
}
func TestClient_Get(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Fatalf("bad method: %s", r.Method)
}
if r.RequestURI != "/foo/bar" {
t.Fatalf("bad uri: %s", r.RequestURI)
}
w.WriteHeader(200)
}))
defer ts.Close()
// Make the request.
resp, err := NewClient().Get(ts.URL + "/foo/bar")
if err != nil {
t.Fatalf("err: %v", err)
}
resp.Body.Close()
}
func TestClient_RequestLogHook(t *testing.T) {
t.Run("RequestLogHook successfully called with default Logger", func(t *testing.T) {
testClientRequestLogHook(t, defaultLogger)
})
t.Run("RequestLogHook successfully called with nil Logger", func(t *testing.T) {
testClientRequestLogHook(t, nil)
})
t.Run("RequestLogHook successfully called with nil typed Logger", func(t *testing.T) {
testClientRequestLogHook(t, Logger(nil))
})
t.Run("RequestLogHook successfully called with nil typed LeveledLogger", func(t *testing.T) {
testClientRequestLogHook(t, LeveledLogger(nil))
})
}
func testClientRequestLogHook(t *testing.T, logger interface{}) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Fatalf("bad method: %s", r.Method)
}
if r.RequestURI != "/foo/bar" {
t.Fatalf("bad uri: %s", r.RequestURI)
}
w.WriteHeader(200)
}))
defer ts.Close()
retries := -1
testURIPath := "/foo/bar"
client := NewClient()
client.Logger = logger
client.RequestLogHook = func(logger Logger, req *http.Request, retry int) {
retries = retry
if logger != client.Logger {
t.Fatalf("Client logger was not passed to logging hook")
}
dumpBytes, err := httputil.DumpRequestOut(req, false)
if err != nil {
t.Fatal("Dumping requests failed")
}
dumpString := string(dumpBytes)
if !strings.Contains(dumpString, "GET "+testURIPath) {
t.Fatalf("Bad request dump:\n%s", dumpString)
}
}
// Make the request.
resp, err := client.Get(ts.URL + testURIPath)
if err != nil {
t.Fatalf("err: %v", err)
}
resp.Body.Close()
if retries < 0 {
t.Fatal("Logging hook was not called")
}
}
func TestClient_ResponseLogHook(t *testing.T) {
t.Run("ResponseLogHook successfully called with hclog Logger", func(t *testing.T) {
buf := new(bytes.Buffer)
l := hclog.New(&hclog.LoggerOptions{
Output: buf,
})
testClientResponseLogHook(t, l, buf)
})
t.Run("ResponseLogHook successfully called with nil Logger", func(t *testing.T) {
buf := new(bytes.Buffer)
testClientResponseLogHook(t, nil, buf)
})
t.Run("ResponseLogHook successfully called with nil typed Logger", func(t *testing.T) {
buf := new(bytes.Buffer)
testClientResponseLogHook(t, Logger(nil), buf)
})
t.Run("ResponseLogHook successfully called with nil typed LeveledLogger", func(t *testing.T) {
buf := new(bytes.Buffer)
testClientResponseLogHook(t, LeveledLogger(nil), buf)
})
}
func testClientResponseLogHook(t *testing.T, l interface{}, buf *bytes.Buffer) {
passAfter := time.Now().Add(100 * time.Millisecond)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if time.Now().After(passAfter) {
w.WriteHeader(200)
w.Write([]byte("test_200_body"))
} else {
w.WriteHeader(500)
w.Write([]byte("test_500_body"))
}
}))
defer ts.Close()
client := NewClient()
client.Logger = l
client.RetryWaitMin = 10 * time.Millisecond
client.RetryWaitMax = 10 * time.Millisecond
client.RetryMax = 15
client.ResponseLogHook = func(logger Logger, resp *http.Response) {
if resp.StatusCode == 200 {
successLog := "test_log_pass"
// Log something when we get a 200
if logger != nil {
logger.Printf(successLog)
} else {
buf.WriteString(successLog)
}
} else {
// Log the response body when we get a 500
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("err: %v", err)
}
failLog := string(body)
if logger != nil {
logger.Printf(failLog)
} else {
buf.WriteString(failLog)
}
}
}
// Perform the request. Exits when we finally get a 200.
resp, err := client.Get(ts.URL)
if err != nil {
t.Fatalf("err: %v", err)
}
// Make sure we can read the response body still, since we did not
// read or close it from the response log hook.
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("err: %v", err)
}
if string(body) != "test_200_body" {
t.Fatalf("expect %q, got %q", "test_200_body", string(body))
}
// Make sure we wrote to the logger on callbacks.
out := buf.String()
if !strings.Contains(out, "test_log_pass") {
t.Fatalf("expect response callback on 200: %q", out)
}
if !strings.Contains(out, "test_500_body") {
t.Fatalf("expect response callback on 500: %q", out)
}
}
func TestClient_NewRequestWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r, err := NewRequestWithContext(ctx, http.MethodGet, "/abc", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if r.Context() != ctx {
t.Fatal("Context must be set")
}
}
func TestClient_RequestWithContext(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("test_200_body"))
}))
defer ts.Close()
req, err := NewRequest(http.MethodGet, ts.URL, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
ctx, cancel := context.WithCancel(req.Request.Context())
reqCtx := req.WithContext(ctx)
if reqCtx == req {
t.Fatal("WithContext must return a new Request object")
}
client := NewClient()
called := 0
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
called++
return DefaultRetryPolicy(reqCtx.Request.Context(), resp, err)
}
cancel()
_, err = client.Do(reqCtx)
if called != 1 {
t.Fatalf("CheckRetry called %d times, expected 1", called)
}
e := fmt.Sprintf("GET %s giving up after 1 attempt(s): %s", ts.URL, context.Canceled.Error())
if err.Error() != e {
t.Fatalf("Expected err to contain %s, got: %v", e, err)
}
}
func TestClient_CheckRetry(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "test_500_body", http.StatusInternalServerError)
}))
defer ts.Close()
client := NewClient()
retryErr := errors.New("retryError")
called := 0
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
if called < 1 {
called++
return DefaultRetryPolicy(context.TODO(), resp, err)
}
return false, retryErr
}
// CheckRetry should return our retryErr value and stop the retry loop.
_, err := client.Get(ts.URL)
if called != 1 {
t.Fatalf("CheckRetry called %d times, expected 1", called)
}
if err.Error() != fmt.Sprintf("GET %s giving up after 2 attempt(s): retryError", ts.URL) {
t.Fatalf("Expected retryError, got:%v", err)
}
}
func testStaticTime(t *testing.T) {
timeNow = func() time.Time {
now, err := time.Parse(time.RFC1123, "Fri, 31 Dec 1999 23:59:57 GMT")
if err != nil {
panic(err)
}
return now
}
t.Cleanup(func() {
timeNow = time.Now
})
}
func TestParseRetryAfterHeader(t *testing.T) {
testStaticTime(t)
tests := []struct {
name string
headers []string
sleep time.Duration
ok bool
}{
{"seconds", []string{"2"}, time.Second * 2, true},
{"date", []string{"Fri, 31 Dec 1999 23:59:59 GMT"}, time.Second * 2, true},
{"past-date", []string{"Fri, 31 Dec 1999 23:59:00 GMT"}, 0, true},
{"nil", nil, 0, false},
{"two-headers", []string{"2", "3"}, time.Second * 2, true},
{"empty", []string{""}, 0, false},
{"negative", []string{"-2"}, 0, false},
{"bad-date", []string{"Fri, 32 Dec 1999 23:59:59 GMT"}, 0, false},
{"bad-date-format", []string{"badbadbad"}, 0, false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
sleep, ok := parseRetryAfterHeader(test.headers)
if ok != test.ok {
t.Fatalf("expected ok=%t, got ok=%t", test.ok, ok)
}
if sleep != test.sleep {
t.Fatalf("expected sleep=%v, got sleep=%v", test.sleep, sleep)
}
})
}
}
func TestClient_DefaultBackoff(t *testing.T) {
testStaticTime(t)
tests := []struct {
name string
code int
retryHeader string
}{
{"http_429_seconds", http.StatusTooManyRequests, "2"},
{"http_429_date", http.StatusTooManyRequests, "Fri, 31 Dec 1999 23:59:59 GMT"},
{"http_503_seconds", http.StatusServiceUnavailable, "2"},
{"http_503_date", http.StatusServiceUnavailable, "Fri, 31 Dec 1999 23:59:59 GMT"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", test.retryHeader)
http.Error(w, fmt.Sprintf("test_%d_body", test.code), test.code)
}))
defer ts.Close()
client := NewClient()
var retryAfter time.Duration
retryable := false
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
retryable, _ = DefaultRetryPolicy(context.Background(), resp, err)
retryAfter = DefaultBackoff(client.RetryWaitMin, client.RetryWaitMax, 1, resp)
return false, nil
}
_, err := client.Get(ts.URL)
if err != nil {
t.Fatalf("expected no errors since retryable")
}
if !retryable {
t.Fatal("Since the error is recoverable, the default policy shall return true")
}
if retryAfter != 2*time.Second {
t.Fatalf("The header Retry-After specified 2 seconds, and shall not be %d seconds", retryAfter/time.Second)
}
})
}
}
func TestClient_DefaultRetryPolicy_TLS(t *testing.T) {
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
attempts := 0
client := NewClient()
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
attempts++
return DefaultRetryPolicy(context.TODO(), resp, err)
}
_, err := client.Get(ts.URL)
if err == nil {
t.Fatalf("expected x509 error, got nil")
}
if attempts != 1 {
t.Fatalf("expected 1 attempt, got %d", attempts)
}
}
func TestClient_DefaultRetryPolicy_redirects(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
}))
defer ts.Close()
attempts := 0
client := NewClient()
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
attempts++
return DefaultRetryPolicy(context.TODO(), resp, err)
}
_, err := client.Get(ts.URL)
if err == nil {
t.Fatalf("expected redirect error, got nil")
}
if attempts != 1 {
t.Fatalf("expected 1 attempt, got %d", attempts)
}
}
func TestClient_DefaultRetryPolicy_invalidscheme(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
attempts := 0
client := NewClient()
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
attempts++
return DefaultRetryPolicy(context.TODO(), resp, err)
}
url := strings.Replace(ts.URL, "http", "ftp", 1)
_, err := client.Get(url)
if err == nil {
t.Fatalf("expected scheme error, got nil")
}
if attempts != 1 {
t.Fatalf("expected 1 attempt, got %d", attempts)
}
}
func TestClient_DefaultRetryPolicy_invalidheadername(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
attempts := 0
client := NewClient()
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
attempts++
return DefaultRetryPolicy(context.TODO(), resp, err)
}
req, err := http.NewRequest(http.MethodGet, ts.URL, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
req.Header.Set("Header-Name-\033", "header value")
_, err = client.StandardClient().Do(req)
if err == nil {
t.Fatalf("expected header error, got nil")
}
if attempts != 1 {
t.Fatalf("expected 1 attempt, got %d", attempts)
}
}
func TestClient_DefaultRetryPolicy_invalidheadervalue(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
attempts := 0
client := NewClient()
client.CheckRetry = func(_ context.Context, resp *http.Response, err error) (bool, error) {
attempts++
return DefaultRetryPolicy(context.TODO(), resp, err)
}
req, err := http.NewRequest(http.MethodGet, ts.URL, nil)
if err != nil {
t.Fatalf("err: %v", err)
}
req.Header.Set("Header-Name", "bad header value \033")
_, err = client.StandardClient().Do(req)
if err == nil {
t.Fatalf("expected header value error, got nil")