-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathretry_test.go
109 lines (92 loc) · 1.65 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
package retry
import (
"context"
"errors"
"testing"
"time"
)
func TestExponential(t *testing.T) {
exp := Exponential(2)
if d := exp(0); d != 0 {
t.Fatal(d)
}
if d := exp(1); d != 2 {
t.Fatal(d)
}
if d := exp(10); d != 20 {
t.Fatal(d)
}
exp = Exponential(1.8)
if d := exp(10); d != 18 {
t.Fatal(d)
}
}
func TestEnsure(t *testing.T) {
r := New(WithBaseDelay(1 * time.Millisecond))
val := 0
do := func() error {
val++
t.Log(val)
if val == 5 {
return nil
}
return Retriable(errors.New("please retry"))
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := r.Ensure(ctx, do); err != nil {
t.Fatal(err)
}
if val != 5 {
t.Fatal(val)
}
}
func TestWithBaseDelay(t *testing.T) {
r := &Retry{}
opt := WithBaseDelay(1)
opt(r)
if r.base != 1 {
t.Fatal(r.base)
}
}
func TestWithBackoff(t *testing.T) {
r := &Retry{}
opt := WithBackoff(nil)
opt(r)
if r.backoff != nil {
t.Fatal(r.backoff)
}
opt = WithBackoff(Exponential(2))
opt(r)
if r.backoff == nil {
t.Fatal(r.backoff)
}
}
func TestEnsureN(t *testing.T) {
r = New(WithBaseDelay(1 * time.Millisecond))
val := 0
do := func() error {
val++
t.Log(val)
if val == 5 {
return nil
}
return Retriable(errors.New("please retry"))
}
err := r.EnsureN(context.Background(), 3, do)
if err == nil {
t.Fatal("should be error")
}
if val != 3 {
t.Fatal(val)
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
err = r.EnsureN(ctx, 5, do)
if err == nil || err != context.DeadlineExceeded {
t.Fatal("should be error")
}
if val == 5 {
t.Fatal(val)
}
}