forked from go-resty/resty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry_test.go
825 lines (663 loc) · 21.1 KB
/
retry_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
// Copyright (c) 2015-2023 Jeevanandam M ([email protected]), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strconv"
"strings"
"testing"
"time"
)
func TestBackoffSuccess(t *testing.T) {
attempts := 3
externalCounter := 0
retryErr := Backoff(func() (*Response, error) {
externalCounter++
if externalCounter < attempts {
return nil, errors.New("not yet got the number we're after")
}
return nil, nil
})
assertError(t, retryErr)
assertEqual(t, externalCounter, attempts)
}
func TestBackoffNoWaitForLastRetry(t *testing.T) {
attempts := 1
externalCounter := 0
numRetries := 1
canceledCtx, cancel := context.WithCancel(context.Background())
defer cancel()
resp := &Response{
Request: &Request{
ctx: canceledCtx,
client: &Client{
RetryAfter: func(*Client, *Response) (time.Duration, error) {
return 6, nil
},
},
},
}
retryErr := Backoff(func() (*Response, error) {
externalCounter++
return resp, nil
}, RetryConditions([]RetryConditionFunc{func(response *Response, err error) bool {
if externalCounter == attempts+numRetries {
// Backoff returns context canceled if goes to sleep after last retry.
cancel()
}
return true
}}), Retries(numRetries))
assertNil(t, retryErr)
}
func TestBackoffTenAttemptsSuccess(t *testing.T) {
attempts := 10
externalCounter := 0
retryErr := Backoff(func() (*Response, error) {
externalCounter++
if externalCounter < attempts {
return nil, errors.New("not yet got the number we're after")
}
return nil, nil
}, Retries(attempts), WaitTime(5), MaxWaitTime(500))
assertError(t, retryErr)
assertEqual(t, externalCounter, attempts)
}
// Check to make sure the conditional of the retry condition is being used
func TestConditionalBackoffCondition(t *testing.T) {
attempts := 3
counter := 0
check := RetryConditionFunc(func(*Response, error) bool {
return attempts != counter
})
retryErr := Backoff(func() (*Response, error) {
counter++
return nil, nil
}, RetryConditions([]RetryConditionFunc{check}))
assertError(t, retryErr)
assertEqual(t, counter, attempts)
}
// Check to make sure that if the conditional is false we don't retry
func TestConditionalBackoffConditionNonExecution(t *testing.T) {
attempts := 3
counter := 0
retryErr := Backoff(func() (*Response, error) {
counter++
return nil, nil
}, RetryConditions([]RetryConditionFunc{filler}))
assertError(t, retryErr)
assertNotEqual(t, counter, attempts)
}
// Check to make sure that RetryHooks are executed
func TestOnRetryBackoff(t *testing.T) {
attempts := 3
counter := 0
hook := func(r *Response, err error) {
counter++
}
retryErr := Backoff(func() (*Response, error) {
return nil, nil
}, RetryHooks([]OnRetryFunc{hook}))
assertError(t, retryErr)
assertNotEqual(t, counter, attempts)
}
// Check to make sure the functions added to add conditionals work
func TestConditionalGet(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attemptCount := 1
externalCounter := 0
// This check should pass on first run, and let the response through
check := RetryConditionFunc(func(*Response, error) bool {
externalCounter++
return attemptCount != externalCounter
})
client := dc().AddRetryCondition(check).SetRetryCount(1)
resp, err := client.R().
SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
Get(ts.URL + "/")
assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "200 OK", resp.Status())
assertNotNil(t, resp.Body())
assertEqual(t, "TestGet: text response", resp.String())
assertEqual(t, externalCounter, attemptCount)
logResponse(t, resp)
}
// Check to make sure the package Function works.
func TestConditionalGetDefaultClient(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attemptCount := 1
externalCounter := 0
// This check should pass on first run, and let the response through
check := RetryConditionFunc(func(*Response, error) bool {
externalCounter++
return attemptCount != externalCounter
})
// Clear the default client.
client := dc()
// Proceed to check.
client.AddRetryCondition(check).SetRetryCount(1)
resp, err := client.R().
SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
Get(ts.URL + "/")
assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "200 OK", resp.Status())
assertNotNil(t, resp.Body())
assertEqual(t, "TestGet: text response", resp.String())
assertEqual(t, externalCounter, attemptCount)
logResponse(t, resp)
}
func TestClientRetryGet(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
c := dc().
SetTimeout(time.Second * 3).
SetRetryCount(3)
resp, err := c.R().Get(ts.URL + "/set-retrycount-test")
assertEqual(t, "", resp.Status())
assertEqual(t, "", resp.Proto())
assertEqual(t, 0, resp.StatusCode())
assertEqual(t, 0, len(resp.Cookies()))
assertNotNil(t, resp.Body())
assertEqual(t, 0, len(resp.Header()))
assertEqual(t, true, strings.HasPrefix(err.Error(), "Get "+ts.URL+"/set-retrycount-test") ||
strings.HasPrefix(err.Error(), "Get \""+ts.URL+"/set-retrycount-test\""))
}
func TestClientRetryWait(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := time.Duration(3) * time.Second
retryMaxWaitTime := time.Duration(9) * time.Second
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
_, _ = c.R().Get(ts.URL + "/set-retrywaittime-test")
// 6 attempts were made
assertEqual(t, attempt, 6)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
for i := 1; i < len(retryIntervals); i++ {
slept := time.Duration(retryIntervals[i])
// Ensure that client has slept some duration between
// waitTime and maxWaitTime for consequent requests
if slept < retryWaitTime || slept > retryMaxWaitTime {
t.Errorf("Client has slept %f seconds before retry %d", slept.Seconds(), i)
}
}
}
func TestClientRetryWaitMaxInfinite(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := time.Duration(3) * time.Second
retryMaxWaitTime := time.Duration(-1.0) // negative value
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
_, _ = c.R().Get(ts.URL + "/set-retrywaittime-test")
// 6 attempts were made
assertEqual(t, attempt, 6)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
for i := 1; i < len(retryIntervals); i++ {
slept := time.Duration(retryIntervals[i])
// Ensure that client has slept some duration between
// waitTime and maxWaitTime for consequent requests
if slept < retryWaitTime {
t.Errorf("Client has slept %f seconds before retry %d", slept.Seconds(), i)
}
}
}
func TestClientRetryWaitMaxMinimum(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
const retryMaxWaitTime = time.Nanosecond // minimal duration value
c := dc().
SetRetryCount(1).
SetRetryMaxWaitTime(retryMaxWaitTime).
AddRetryCondition(func(*Response, error) bool { return true })
_, err := c.R().Get(ts.URL + "/set-retrywaittime-test")
assertError(t, err)
}
func TestClientRetryWaitCallbackError(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := 3 * time.Second
retryMaxWaitTime := 9 * time.Second
retryAfter := func(client *Client, resp *Response) (time.Duration, error) {
return 0, errors.New("quota exceeded")
}
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
SetRetryAfter(retryAfter).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
_, err := c.R().Get(ts.URL + "/set-retrywaittime-test")
// 1 attempts were made
assertEqual(t, attempt, 1)
// non-nil error was returned
assertNotEqual(t, nil, err)
}
func TestClientRetryWaitCallback(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := 3 * time.Second
retryMaxWaitTime := 9 * time.Second
retryAfter := func(client *Client, resp *Response) (time.Duration, error) {
return 5 * time.Second, nil
}
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
SetRetryAfter(retryAfter).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
_, _ = c.R().Get(ts.URL + "/set-retrywaittime-test")
// 6 attempts were made
assertEqual(t, attempt, 6)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
for i := 1; i < len(retryIntervals); i++ {
slept := time.Duration(retryIntervals[i])
// Ensure that client has slept some duration between
// waitTime and maxWaitTime for consequent requests
if slept < 5*time.Second-5*time.Millisecond || 5*time.Second+5*time.Millisecond < slept {
t.Logf("Client has slept %f seconds before retry %d", slept.Seconds(), i)
}
}
}
func TestClientRetryWaitCallbackTooShort(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := 3 * time.Second
retryMaxWaitTime := 9 * time.Second
retryAfter := func(client *Client, resp *Response) (time.Duration, error) {
return 2 * time.Second, nil // too short duration
}
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
SetRetryAfter(retryAfter).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
_, _ = c.R().Get(ts.URL + "/set-retrywaittime-test")
// 6 attempts were made
assertEqual(t, attempt, 6)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
for i := 1; i < len(retryIntervals); i++ {
slept := time.Duration(retryIntervals[i])
// Ensure that client has slept some duration between
// waitTime and maxWaitTime for consequent requests
if slept < retryWaitTime-5*time.Millisecond || retryWaitTime+5*time.Millisecond < slept {
t.Logf("Client has slept %f seconds before retry %d", slept.Seconds(), i)
}
}
}
func TestClientRetryWaitCallbackTooLong(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := 1 * time.Second
retryMaxWaitTime := 3 * time.Second
retryAfter := func(client *Client, resp *Response) (time.Duration, error) {
return 4 * time.Second, nil // too long duration
}
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
SetRetryAfter(retryAfter).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
_, _ = c.R().Get(ts.URL + "/set-retrywaittime-test")
// 6 attempts were made
assertEqual(t, attempt, 6)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
for i := 1; i < len(retryIntervals); i++ {
slept := time.Duration(retryIntervals[i])
// Ensure that client has slept some duration between
// waitTime and maxWaitTime for consequent requests
if slept < retryMaxWaitTime-5*time.Millisecond || retryMaxWaitTime+5*time.Millisecond < slept {
t.Logf("Client has slept %f seconds before retry %d", slept.Seconds(), i)
}
}
}
func TestClientRetryWaitCallbackSwitchToDefault(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := 1 * time.Second
retryMaxWaitTime := 3 * time.Second
retryAfter := func(client *Client, resp *Response) (time.Duration, error) {
return 0, nil // use default algorithm to determine retry-after time
}
c := dc().
EnableTrace().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
SetRetryAfter(retryAfter).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
resp, _ := c.R().Get(ts.URL + "/set-retrywaittime-test")
// 6 attempts were made
assertEqual(t, attempt, 6)
assertEqual(t, resp.Request.Attempt, 6)
assertEqual(t, resp.Request.TraceInfo().RequestAttempt, 6)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
for i := 1; i < len(retryIntervals); i++ {
slept := time.Duration(retryIntervals[i])
expected := (1 << (uint(i - 1))) * time.Second
if expected > retryMaxWaitTime {
expected = retryMaxWaitTime
}
// Ensure that client has slept some duration between
// waitTime and maxWaitTime for consequent requests
if slept < expected/2-5*time.Millisecond || expected+5*time.Millisecond < slept {
t.Errorf("Client has slept %f seconds before retry %d", slept.Seconds(), i)
}
}
}
func TestClientRetryCancel(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
retryCount := 5
retryIntervals := make([]uint64, retryCount+1)
// Set retry wait times that do not intersect with default ones
retryWaitTime := time.Duration(10) * time.Second
retryMaxWaitTime := time.Duration(20) * time.Second
c := dc().
SetRetryCount(retryCount).
SetRetryWaitTime(retryWaitTime).
SetRetryMaxWaitTime(retryMaxWaitTime).
AddRetryCondition(
func(r *Response, _ error) bool {
timeSlept, _ := strconv.ParseUint(string(r.Body()), 10, 64)
retryIntervals[attempt] = timeSlept
attempt++
return true
},
)
timeout := 2 * time.Second
ctx, cancelFunc := context.WithTimeout(context.Background(), timeout)
_, _ = c.R().SetContext(ctx).Get(ts.URL + "/set-retrywaittime-test")
// 1 attempts were made
assertEqual(t, attempt, 1)
// Initial attempt has 0 time slept since last request
assertEqual(t, retryIntervals[0], uint64(0))
// Second attempt should be interrupted on context timeout
if time.Duration(retryIntervals[1]) > timeout {
t.Errorf("Client didn't awake on context cancel")
}
cancelFunc()
}
func TestClientRetryPost(t *testing.T) {
ts := createPostServer(t)
defer ts.Close()
usersmap := map[string]interface{}{
"user1": map[string]interface{}{"FirstName": "firstname1", "LastName": "lastname1", "ZipCode": "10001"},
}
var users []map[string]interface{}
users = append(users, usersmap)
c := dc()
c.SetRetryCount(3)
c.AddRetryCondition(RetryConditionFunc(func(r *Response, _ error) bool {
return r.StatusCode() >= http.StatusInternalServerError
}))
resp, _ := c.R().
SetBody(&users).
Post(ts.URL + "/usersmap?status=500")
if resp != nil {
if resp.StatusCode() == http.StatusInternalServerError {
t.Logf("Got response body: %s", string(resp.body))
var usersResponse []map[string]interface{}
err := json.Unmarshal(resp.body, &usersResponse)
assertError(t, err)
if !reflect.DeepEqual(users, usersResponse) {
t.Errorf("Expected request body to be echoed back as response body. Instead got: %s", string(resp.body))
}
return
}
t.Errorf("Got unexpected response code: %d with body: %s", resp.StatusCode(), string(resp.body))
}
}
func TestClientRetryErrorRecover(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
c := dc().
SetRetryCount(2).
SetError(AuthError{}).
AddRetryCondition(
func(r *Response, _ error) bool {
err, ok := r.Error().(*AuthError)
retry := ok && r.StatusCode() == 429 && err.Message == "too many"
return retry
},
)
resp, err := c.R().
SetHeader(hdrContentTypeKey, "application/json; charset=utf-8").
SetJSONEscapeHTML(false).
SetResult(AuthSuccess{}).
Get(ts.URL + "/set-retry-error-recover")
assertError(t, err)
authSuccess := resp.Result().(*AuthSuccess)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "hello", authSuccess.Message)
assertNil(t, resp.Error())
}
func TestClientRetryCount(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
c := dc().
SetTimeout(time.Second * 3).
SetRetryCount(1).
AddRetryCondition(
func(r *Response, _ error) bool {
attempt++
return true
},
)
resp, err := c.R().Get(ts.URL + "/set-retrycount-test")
assertEqual(t, "", resp.Status())
assertEqual(t, "", resp.Proto())
assertEqual(t, 0, resp.StatusCode())
assertEqual(t, 0, len(resp.Cookies()))
assertNotNil(t, resp.Body())
assertEqual(t, 0, len(resp.Header()))
// 2 attempts were made
assertEqual(t, attempt, 2)
assertEqual(t, true, strings.HasPrefix(err.Error(), "Get "+ts.URL+"/set-retrycount-test") ||
strings.HasPrefix(err.Error(), "Get \""+ts.URL+"/set-retrycount-test\""))
}
func TestClientErrorRetry(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
c := dc().
SetTimeout(time.Second * 3).
SetRetryCount(1).
AddRetryAfterErrorCondition()
resp, err := c.R().
SetHeader(hdrContentTypeKey, "application/json; charset=utf-8").
SetJSONEscapeHTML(false).
SetResult(AuthSuccess{}).
Get(ts.URL + "/set-retry-error-recover")
assertError(t, err)
authSuccess := resp.Result().(*AuthSuccess)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, "hello", authSuccess.Message)
assertNil(t, resp.Error())
}
func TestClientRetryHook(t *testing.T) {
ts := createGetServer(t)
defer ts.Close()
attempt := 0
c := dc().
SetRetryCount(2).
SetTimeout(time.Second * 3).
AddRetryHook(
func(r *Response, _ error) {
attempt++
},
)
resp, err := c.R().Get(ts.URL + "/set-retrycount-test")
assertEqual(t, "", resp.Status())
assertEqual(t, "", resp.Proto())
assertEqual(t, 0, resp.StatusCode())
assertEqual(t, 0, len(resp.Cookies()))
assertNotNil(t, resp.Body())
assertEqual(t, 0, len(resp.Header()))
assertEqual(t, 3, attempt)
assertEqual(t, true, strings.HasPrefix(err.Error(), "Get "+ts.URL+"/set-retrycount-test") ||
strings.HasPrefix(err.Error(), "Get \""+ts.URL+"/set-retrycount-test\""))
}
func filler(*Response, error) bool {
return false
}
var errSeekFailure = fmt.Errorf("failing seek test")
type failingSeeker struct {
reader *bytes.Reader
}
func (f failingSeeker) Read(b []byte) (n int, err error) {
return f.reader.Read(b)
}
func (f failingSeeker) Seek(offset int64, whence int) (int64, error) {
if offset == 0 && whence == io.SeekStart {
return 0, errSeekFailure
}
return f.reader.Seek(offset, whence)
}
func TestResetMultipartReaderSeekStartError(t *testing.T) {
ts := createFilePostServer(t)
defer ts.Close()
testSeeker := &failingSeeker{
bytes.NewReader([]byte("test")),
}
c := dc().
SetRetryCount(2).
SetTimeout(time.Second * 3).
SetRetryResetReaders(true).
AddRetryAfterErrorCondition()
resp, err := c.R().
SetFileReader("name", "filename", testSeeker).
Post(ts.URL + "/set-reset-multipart-readers-test")
assertEqual(t, 500, resp.StatusCode())
assertEqual(t, err.Error(), errSeekFailure.Error())
}
func TestResetMultipartReaders(t *testing.T) {
ts := createFilePostServer(t)
defer ts.Close()
str := "test"
buf := []byte(str)
bufReader := bytes.NewReader(buf)
bufCpy := make([]byte, len(buf))
c := dc().
SetRetryCount(2).
SetTimeout(time.Second * 3).
SetRetryResetReaders(true).
AddRetryAfterErrorCondition().
AddRetryHook(
func(response *Response, _ error) {
read, err := bufReader.Read(bufCpy)
assertNil(t, err)
assertEqual(t, len(buf), read)
assertEqual(t, str, string(bufCpy))
},
)
resp, err := c.R().
SetFileReader("name", "filename", bufReader).
Post(ts.URL + "/set-reset-multipart-readers-test")
assertEqual(t, 500, resp.StatusCode())
assertNil(t, err)
}