| 1 |
package backoff |
| 2 |
|
| 3 |
import ( |
| 4 |
"math" |
| 5 |
"testing" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
func TestBackOff(t *testing.T) { |
| 10 |
var ( |
| 11 |
testInitialInterval = 500 * time.Millisecond |
| 12 |
testRandomizationFactor = 0.1 |
| 13 |
testMultiplier = 2.0 |
| 14 |
testMaxInterval = 5 * time.Second |
| 15 |
) |
| 16 |
|
| 17 |
exp := NewExponentialBackOff() |
| 18 |
exp.InitialInterval = testInitialInterval |
| 19 |
exp.RandomizationFactor = testRandomizationFactor |
| 20 |
exp.Multiplier = testMultiplier |
| 21 |
exp.MaxInterval = testMaxInterval |
| 22 |
exp.Reset() |
| 23 |
|
| 24 |
var expectedResults = []time.Duration{500, 1000, 2000, 4000, 5000, 5000, 5000, 5000, 5000, 5000} |
| 25 |
for i, d := range expectedResults { |
| 26 |
expectedResults[i] = d * time.Millisecond |
| 27 |
} |
| 28 |
|
| 29 |
for _, expected := range expectedResults { |
| 30 |
assertEquals(t, expected, exp.currentInterval) |
| 31 |
// Assert that the next backoff falls in the expected range. |
| 32 |
var minInterval = expected - time.Duration(testRandomizationFactor*float64(expected)) |
| 33 |
var maxInterval = expected + time.Duration(testRandomizationFactor*float64(expected)) |
| 34 |
var actualInterval = exp.NextBackOff() |
| 35 |
if !(minInterval <= actualInterval && actualInterval <= maxInterval) { |
| 36 |
t.Error("error") |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
func TestGetRandomizedInterval(t *testing.T) { |
| 42 |
// 33% chance of being 1. |
| 43 |
assertEquals(t, 1, getRandomValueFromInterval(0.5, 0, 2)) |
| 44 |
assertEquals(t, 1, getRandomValueFromInterval(0.5, 0.33, 2)) |
| 45 |
// 33% chance of being 2. |
| 46 |
assertEquals(t, 2, getRandomValueFromInterval(0.5, 0.34, 2)) |
| 47 |
assertEquals(t, 2, getRandomValueFromInterval(0.5, 0.66, 2)) |
| 48 |
// 33% chance of being 3. |
| 49 |
assertEquals(t, 3, getRandomValueFromInterval(0.5, 0.67, 2)) |
| 50 |
assertEquals(t, 3, getRandomValueFromInterval(0.5, 0.99, 2)) |
| 51 |
} |
| 52 |
|
| 53 |
func TestBackOffOverflow(t *testing.T) { |
| 54 |
var ( |
| 55 |
testInitialInterval time.Duration = math.MaxInt64 / 2 |
| 56 |
testMaxInterval time.Duration = math.MaxInt64 |
| 57 |
testMultiplier = 2.1 |
| 58 |
) |
| 59 |
|
| 60 |
exp := NewExponentialBackOff() |
| 61 |
exp.InitialInterval = testInitialInterval |
| 62 |
exp.Multiplier = testMultiplier |
| 63 |
exp.MaxInterval = testMaxInterval |
| 64 |
exp.Reset() |
| 65 |
|
| 66 |
exp.NextBackOff() |
| 67 |
// Assert that when an overflow is possible, the current interval time.Duration is set to the max interval time.Duration. |
| 68 |
assertEquals(t, testMaxInterval, exp.currentInterval) |
| 69 |
} |
| 70 |
|
| 71 |
func assertEquals(t *testing.T, expected, value time.Duration) { |
| 72 |
if expected != value { |
| 73 |
t.Errorf("got: %d, expected: %d", value, expected) |
| 74 |
} |
| 75 |
} |