forked from sethvargo/go-retry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backoff_constant_test.go
126 lines (115 loc) · 2.09 KB
/
backoff_constant_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
package retry
import (
"fmt"
"reflect"
"sort"
"testing"
"time"
)
func TestConstantBackoff(t *testing.T) {
t.Parallel()
cases := []struct {
name string
base time.Duration
tries int
exp []time.Duration
err bool
}{
{
name: "zero",
err: true,
},
{
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,
10 * time.Millisecond,
10 * time.Millisecond,
10 * time.Millisecond,
10 * time.Millisecond,
},
},
{
name: "many",
base: 1 * time.Nanosecond,
tries: 14,
exp: []time.Duration{
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
1 * time.Nanosecond,
},
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
b, err := NewConstant(tc.base)
if (err != nil) != tc.err {
t.Fatal(err)
}
if b == nil {
return
}
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 ExampleNewConstant() {
b, err := NewConstant(1 * time.Second)
if err != nil {
// handle err
}
for i := 0; i < 5; i++ {
val, _ := b.Next()
fmt.Printf("%v\n", val)
}
// Output:
// 1s
// 1s
// 1s
// 1s
// 1s
}