-
Notifications
You must be signed in to change notification settings - Fork 29
/
backoff_fibonacci_test.go
132 lines (120 loc) · 2.32 KB
/
backoff_fibonacci_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
121
122
123
124
125
126
127
128
129
130
131
132
package retry_test
import (
"fmt"
"math"
"reflect"
"sort"
"testing"
"time"
"github.com/sethvargo/go-retry"
)
func TestFibonacciBackoff(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: "max",
base: 10 * time.Millisecond,
tries: 5,
exp: []time.Duration{
10 * time.Millisecond,
20 * time.Millisecond,
30 * time.Millisecond,
50 * time.Millisecond,
80 * time.Millisecond,
},
},
{
name: "many",
base: 1 * time.Nanosecond,
tries: 14,
exp: []time.Duration{
1 * time.Nanosecond,
2 * time.Nanosecond,
3 * time.Nanosecond,
5 * time.Nanosecond,
8 * time.Nanosecond,
13 * time.Nanosecond,
21 * time.Nanosecond,
34 * time.Nanosecond,
55 * time.Nanosecond,
89 * time.Nanosecond,
144 * time.Nanosecond,
233 * time.Nanosecond,
377 * time.Nanosecond,
610 * time.Nanosecond,
},
},
{
name: "overflow",
base: 100_000 * time.Hour,
tries: 10,
exp: []time.Duration{
100_000 * time.Hour,
200_000 * time.Hour,
300_000 * time.Hour,
500_000 * time.Hour,
800_000 * time.Hour,
1_300_000 * time.Hour,
2_100_000 * time.Hour,
math.MaxInt64,
math.MaxInt64,
math.MaxInt64,
},
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
b := retry.NewFibonacci(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 ExampleNewFibonacci() {
b := retry.NewFibonacci(1 * time.Second)
for i := 0; i < 5; i++ {
val, _ := b.Next()
fmt.Printf("%v\n", val)
}
// Output:
// 1s
// 2s
// 3s
// 5s
// 8s
}