Debian Codegraph @

backoff_test.go

raw
1 package elastic
2
3 import (
4 "math/rand"
5 "testing"
6 "time"
7 )
8
9 func TestZeroBackoff(t *testing.T) {
10 b := ZeroBackoff{}
11 _, ok := b.Next(0)
12 if !ok {
13 t.Fatalf("expected %v, got %v", true, ok)
14 }
15 }
16
17 func TestStopBackoff(t *testing.T) {
18 b := StopBackoff{}
19 _, ok := b.Next(0)
20 if ok {
21 t.Fatalf("expected %v, got %v", false, ok)
22 }
23 }
24
25 func TestConstantBackoff(t *testing.T) {
26 b := NewConstantBackoff(time.Second)
27 d, ok := b.Next(0)
28 if !ok {
29 t.Fatalf("expected %v, got %v", true, ok)
30 }
31 if d != time.Second {
32 t.Fatalf("expected %v, got %v", time.Second, d)
33 }
34 }
35
36 func TestSimpleBackoff(t *testing.T) {
37 var tests = []struct {
38 Duration time.Duration
39 Continue bool
40 }{
41 // #0
42 {
43 Duration: 1 * time.Millisecond,
44 Continue: true,
45 },
46 // #1
47 {
48 Duration: 2 * time.Millisecond,
49 Continue: true,
50 },
51 // #2
52 {
53 Duration: 7 * time.Millisecond,
54 Continue: true,
55 },
56 // #3
57 {
58 Duration: 0,
59 Continue: false,
60 },
61 // #4
62 {
63 Duration: 0,
64 Continue: false,
65 },
66 }
67
68 b := NewSimpleBackoff(1, 2, 7)
69
70 for i, tt := range tests {
71 d, ok := b.Next(i)
72 if got, want := ok, tt.Continue; got != want {
73 t.Fatalf("#%d: expected %v, got %v", i, want, got)
74 }
75 if got, want := d, tt.Duration; got != want {
76 t.Fatalf("#%d: expected %v, got %v", i, want, got)
77 }
78 }
79 }
80
81 func TestExponentialBackoff(t *testing.T) {
82 rand.Seed(time.Now().UnixNano())
83
84 min := time.Duration(8) * time.Millisecond
85 max := time.Duration(256) * time.Millisecond
86 b := NewExponentialBackoff(min, max)
87
88 between := func(value time.Duration, a, b int) bool {
89 x := int(value / time.Millisecond)
90 return a <= x && x <= b
91 }
92
93 got, ok := b.Next(0)
94 if !ok {
95 t.Fatalf("expected %v, got %v", true, ok)
96 }
97 if !between(got, 8, 256) {
98 t.Errorf("expected [%v..%v], got %v", 8, 256, got)
99 }
100
101 got, ok = b.Next(1)
102 if !ok {
103 t.Fatalf("expected %v, got %v", true, ok)
104 }
105 if !between(got, 8, 256) {
106 t.Errorf("expected [%v..%v], got %v", 8, 256, got)
107 }
108
109 got, ok = b.Next(2)
110 if !ok {
111 t.Fatalf("expected %v, got %v", true, ok)
112 }
113 if !between(got, 8, 256) {
114 t.Errorf("expected [%v..%v], got %v", 8, 256, got)
115 }
116
117 got, ok = b.Next(3)
118 if !ok {
119 t.Fatalf("expected %v, got %v", true, ok)
120 }
121 if !between(got, 8, 256) {
122 t.Errorf("expected [%v..%v], got %v", 8, 256, got)
123 }
124
125 got, ok = b.Next(4)
126 if !ok {
127 t.Fatalf("expected %v, got %v", true, ok)
128 }
129 if !between(got, 8, 256) {
130 t.Errorf("expected [%v..%v], got %v", 8, 256, got)
131 }
132
133 if _, ok := b.Next(5); ok {
134 t.Fatalf("expected %v, got %v", false, ok)
135 }
136
137 if _, ok = b.Next(6); ok {
138 t.Fatalf("expected %v, got %v", false, ok)
139 }
140 }