forked from sethvargo/go-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backoff_exponential_test.go
120 lines (108 loc) · 2.09 KB
/
backoff_exponential_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 retry_test
import (
"fmt"
"math"
"reflect"
"sort"
"testing"
"time"
"github.com/sethvargo/go-retry"
)
func TestExponentialBackoff(t *testing.T) {
t.Parallel()
cases := []struct {
name string
base time.Duration
tries int
exp []time.Duration
}{
{
name: "single",
base: 1 * time.Nanosecond,
tries: 1,
exp: []time.Duration{
1 * time.Nanosecond,
},
},
{
name: "many",
base: 1 * time.Nanosecond,
tries: 14,
exp: []time.Duration{
1 * time.Nanosecond,
2 * time.Nanosecond,
4 * time.Nanosecond,
8 * time.Nanosecond,
16 * time.Nanosecond,
32 * time.Nanosecond,
64 * time.Nanosecond,
128 * time.Nanosecond,
256 * time.Nanosecond,
512 * time.Nanosecond,
1024 * time.Nanosecond,
2048 * time.Nanosecond,
4096 * time.Nanosecond,
8192 * time.Nanosecond,
},
},
{
name: "overflow",
base: 100_000 * time.Hour,
tries: 10,
exp: []time.Duration{
100_000 * time.Hour,
200_000 * time.Hour,
400_000 * time.Hour,
800_000 * time.Hour,
1_600_000 * time.Hour,
math.MaxInt64,
math.MaxInt64,
math.MaxInt64,
math.MaxInt64,
math.MaxInt64,
},
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
b := retry.NewExponential(tc.base)
resultsCh := make(chan time.Duration, tc.tries)
for i := 0; i < tc.tries; i++ {
go func() {
r, _ := b.Next()
resultsCh <- r
}()
}
results := make([]time.Duration, tc.tries)
for i := 0; i < tc.tries; i++ {
select {
case val := <-resultsCh:
results[i] = val
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
}
sort.Slice(results, func(i, j int) bool {
return results[i] < results[j]
})
if !reflect.DeepEqual(results, tc.exp) {
t.Errorf("expected \n\n%v\n\n to be \n\n%v\n\n", results, tc.exp)
}
})
}
}
func ExampleNewExponential() {
b := retry.NewExponential(1 * time.Second)
for i := 0; i < 5; i++ {
val, _ := b.Next()
fmt.Printf("%v\n", val)
}
// Output:
// 1s
// 2s
// 4s
// 8s
// 16s
}