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
| func TestRetryStrategy(t *testing.T) {
testCases := []struct {
name string
statusCode int
keepRetrying bool
}{
{
name: "RetryWhenInternalServerError",
statusCode: http.StatusInternalServerError,
keepRetrying: true,
},
{
name: "RetryWhenBadGateway",
statusCode: http.StatusBadGateway,
keepRetrying: true,
},
{
name: "RetryWhenGatewayTimeout",
statusCode: http.StatusGatewayTimeout,
keepRetrying: true,
},
{
name: "RetryWhenRequestTimeout",
statusCode: http.StatusRequestTimeout,
keepRetrying: true,
},
{
name: "RetryWhenTooManyRequests",
statusCode: http.StatusTooManyRequests,
keepRetrying: true,
},
{
name: "StoppedWhenBadRequest",
statusCode: http.StatusBadRequest,
keepRetrying: false,
},
{
name: "StoppedWhenUnauthorized",
statusCode: http.StatusUnauthorized,
keepRetrying: false,
},
{
name: "StoppedWhenForbidden",
statusCode: http.StatusForbidden,
keepRetrying: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
tsCounter := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tsCounter++
if tsCounter < 2 {
w.WriteHeader(tc.statusCode)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, world!"))
}))
defer ts.Close()
err := retry.Do(
func() error {
resp, err := http.Get(ts.URL)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status code: %d", resp.StatusCode)
}
return nil
},
retry.OnRetry(func(n uint, err error) {
fmt.Printf("retrying: %d, error: %s\n", n, err)
}),
retry.RetryIf(func(err error) bool {
switch err.Error() {
case "status code: 400", "status code: 401", "status code: 403":
return false
default:
return true
}
}),
)
if tc.keepRetrying {
assert.NoError(t, err)
} else {
assert.Error(t, err)
assert.Equal(t, fmt.Sprintf("status code: %d", tc.statusCode), errors.Unwrap(err).Error())
}
})
}
}
|