-
Notifications
You must be signed in to change notification settings - Fork 1
/
retry_test.go
99 lines (82 loc) · 2.22 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
package retry_test
import (
"context"
"errors"
"testing"
"time"
"github.com/morilog/retry"
"github.com/stretchr/testify/require"
)
var errProcess = errors.New("process error")
var errAnother = errors.New("another error")
func TestRetry(t *testing.T) {
ctx := context.Background()
retries := 0
process := func() error {
if retries <= 3 {
retries++
return errProcess
}
return nil
}
t.Run("Should failed and return error", func(t *testing.T) {
attempts := 0
err := retry.Retry(ctx, process, retry.MaxAttempts(1), retry.OnRetry(func(ctx context.Context, attempt int) error {
attempts = attempt
return nil
}))
require.NotNil(t, err)
t.Run("Should attempts once", func(t *testing.T) {
require.Equal(t, 1, attempts)
})
})
t.Run("Should succeed on third try", func(t *testing.T) {
attempts := 0
err := retry.Retry(ctx, process, retry.MaxAttempts(4), retry.OnRetry(func(ctx context.Context, attempt int) error {
attempts = attempt
return nil
}))
require.Nil(t, err)
t.Run("Should attempts three three times", func(t *testing.T) {
require.Equal(t, 3, attempts)
})
})
t.Run("Should attempts 10 times as default", func(t *testing.T) {
attempts := 0
err := retry.Retry(ctx, func() error {
return errProcess
}, retry.Delay(10*time.Millisecond), retry.OnRetry(func(ctx context.Context, attempt int) error {
attempts = attempt
return nil
}))
require.NotNil(t, err)
require.Equal(t, 10, attempts)
})
t.Run("Should attempts for 450 millisecond", func(t *testing.T) {
start := time.Now()
_ = retry.Retry(ctx, func() error {
return errProcess
}, retry.Delay(time.Millisecond*10))
howLong := time.Since(start)
require.True(t, howLong >= 450*time.Millisecond)
require.True(t, howLong <= 500*time.Millisecond)
})
t.Run("Should stop when error is not process error", func(t *testing.T) {
attempts := 0
err := retry.Retry(ctx, func() error {
if attempts < 2 {
attempts++
return errProcess
}
return errAnother
}, retry.StopRetryIf(func(ctx context.Context, err error) bool {
if errors.Is(err, errAnother) {
return true
}
return false
}))
require.NotNil(t, err)
require.ErrorIs(t, err, errAnother)
require.Equal(t, attempts, 2)
})
}