-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathriprovare_test.go
120 lines (105 loc) · 2.34 KB
/
riprovare_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
package riprovare
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRetry_Success(t *testing.T) {
var result int
err := Retry(SimpleRetryPolicy(3), func() error {
result = 5
return nil
})
assert.Equal(t, 5, result)
assert.NoError(t, err)
}
func TestRetry_Failure(t *testing.T) {
attempts := 0
err := Retry(SimpleRetryPolicy(3), func() error {
attempts++
return fmt.Errorf("oh snap this broke")
})
unrecoverable := &UnrecoverableError{}
assert.Equal(t, 3, attempts)
assert.Error(t, err)
assert.ErrorAs(t, err, unrecoverable)
}
func TestRetry_Recovered(t *testing.T) {
attempts := 0
err := Retry(SimpleRetryPolicy(3), func() error {
attempts++
if attempts == 3 {
return nil
}
return fmt.Errorf("oh snap this broke")
})
assert.Equal(t, 3, attempts)
assert.NoError(t, err)
}
func TestFixedRetryPolicy(t *testing.T) {
counter := 0
start := time.Now()
policy := FixedRetryPolicy(3, time.Second*1)
for i := 0; i <= 2; i++ {
counter++
if !policy(nil) {
break
}
}
assert.Equal(t, 3, counter)
assert.GreaterOrEqual(t, time.Since(start), 2*time.Second)
}
func TestFixedRetryPolicy_ContextCanceled(t *testing.T) {
counter := 0
policy := FixedRetryPolicy(3, time.Second*1)
for i := 0; i <= 2; i++ {
counter++
if !policy(context.Canceled) {
break
}
}
assert.Equal(t, 1, counter)
}
func TestExponentialBackoffRetryPolicy(t *testing.T) {
counter := 0
lastDuration := time.Duration(0)
policy := ExponentialBackoffRetryPolicy(3, 1*time.Second)
for i := 0; i <= 2; i++ {
counter++
start := time.Now()
if !policy(nil) {
break
}
duration := time.Since(start)
assert.Greater(t, duration, lastDuration)
lastDuration = duration
}
assert.Equal(t, 3, counter)
}
func TestExponentialBackoffRetryPolicy_ContextCanceled(t *testing.T) {
counter := 0
policy := ExponentialBackoffRetryPolicy(3, 1*time.Second)
for i := 0; i <= 2; i++ {
counter++
if !policy(context.Canceled) {
break
}
}
assert.Equal(t, 1, counter)
}
func TestRetry_ErrorHook(t *testing.T) {
counter := 0
hookCounter := 0
hook := OnErrorFunc(func(err error) {
hookCounter++
})
err := Retry(SimpleRetryPolicy(3), func() error {
counter++
return fmt.Errorf("oh snap this broke")
}, ErrorHook(hook))
assert.Error(t, err)
assert.Equal(t, 3, counter)
assert.Equal(t, 3, hookCounter)
}