-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbackoff_test.go
112 lines (101 loc) · 2.47 KB
/
backoff_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
// Copyright © by Jeff Foley 2022-2024. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// SPDX-License-Identifier: Apache-2.0
package resolve
import (
"testing"
"time"
)
func TestExponentialBackoff(t *testing.T) {
tests := []struct {
name string
events int
delay time.Duration
expected time.Duration
}{
{
name: "Two events and 500ms delay",
events: 2,
delay: 500 * time.Millisecond,
expected: 2 * time.Second,
},
{
name: "Four events and 1sec delay",
events: 4,
delay: time.Second,
expected: 16 * time.Second,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
backoff := ExponentialBackoff(tt.events, tt.delay)
if backoff < tt.expected || backoff > tt.expected+tt.delay {
t.Errorf("Unexpected Result, expected %v, got %v", tt.expected, backoff)
}
})
}
}
func TestTruncatedExponentialBackoff(t *testing.T) {
tests := []struct {
name string
events int
delay time.Duration
max time.Duration
expected time.Duration
}{
{
name: "One event and 250ms delay with 2sec max",
events: 1,
delay: 250 * time.Millisecond,
max: 2 * time.Second,
expected: 500 * time.Millisecond,
},
{
name: "Four events and 500ms delay with 4sec max",
events: 4,
delay: 500 * time.Millisecond,
max: 4 * time.Second,
expected: 4 * time.Second,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
backoff := TruncatedExponentialBackoff(tt.events, tt.delay, tt.max)
if backoff < tt.expected || backoff > tt.expected+tt.delay {
t.Errorf("Unexpected Result, expected %v, got %v", tt.expected, backoff)
}
})
}
}
func TestBackoffJitter(t *testing.T) {
tests := []struct {
name string
min time.Duration
max time.Duration
}{
{
name: "The max is less than the min",
min: time.Second,
max: 500 * time.Millisecond,
},
{
name: "Between one and four seconds",
min: time.Second,
max: 4 * time.Second,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
backoff := BackoffJitter(tt.min, tt.max)
if tt.min >= tt.max {
if backoff != time.Duration(0) {
t.Errorf("Unexpected Result, expected %v, got %v", 0, backoff)
}
return
}
if backoff < tt.min || backoff > tt.max {
t.Errorf("Unexpected Result from min: %v, max: %v, got %v", tt.min, tt.max, backoff)
}
})
}
}