...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package jsonclient
16
17 import (
18 "math"
19 "testing"
20 "time"
21 )
22
23 const testLeeway = 25 * time.Millisecond
24
25 func fuzzyTimeEquals(a, b time.Time, leeway time.Duration) bool {
26 diff := math.Abs(float64(a.Sub(b).Nanoseconds()))
27 return diff < float64(leeway.Nanoseconds())
28 }
29
30 func fuzzyDurationEquals(a, b time.Duration, leeway time.Duration) bool {
31 diff := math.Abs(float64(a.Nanoseconds() - b.Nanoseconds()))
32 return diff < float64(leeway.Nanoseconds())
33 }
34
35 func TestBackoff(t *testing.T) {
36 b := backoff{}
37
38
39 for i := uint(0); i < maxMultiplier; i++ {
40 n := time.Now()
41 interval := b.set(nil)
42 if interval != time.Second*(1<<i) {
43 t.Fatalf("backoff.set(nil)=%v; want %v", interval, time.Second*(1<<i))
44 }
45 expected := n.Add(interval)
46 until := b.until()
47 if !fuzzyTimeEquals(expected, until, time.Millisecond) {
48 t.Fatalf("backoff.until()=%v; want %v (+ 0-250ms)", expected, until)
49 }
50
51
52 b.notBefore = time.Time{}
53 }
54
55
56 b.multiplier = maxMultiplier
57 b.notBefore = time.Time{}
58 interval := b.set(nil)
59 if b.multiplier > maxMultiplier {
60 t.Fatalf("backoff.multiplier=%v; want %v", b.multiplier, maxMultiplier)
61 }
62 if interval > time.Second*(1<<(maxMultiplier-1)) {
63 t.Fatalf("backoff.set(nil)=%v; want %v", interval, 1<<(maxMultiplier-1)*time.Second)
64 }
65
66
67 b.multiplier = 1
68 b.notBefore = time.Time{}
69 b.decreaseMultiplier()
70 if b.multiplier != 0 {
71 t.Fatalf("backoff.multiplier=%v; want %v", b.multiplier, 0)
72 }
73
74
75 b.decreaseMultiplier()
76 if b.multiplier != 0 {
77 t.Fatalf("backoff.multiplier=%v; want %v", b.multiplier, 0)
78 }
79 }
80
81 func TestBackoffOverride(t *testing.T) {
82 b := backoff{}
83 for _, tc := range []struct {
84 notBefore time.Time
85 override time.Duration
86 expectedInterval time.Duration
87 }{
88 {
89 notBefore: time.Now().Add(time.Hour),
90 override: time.Second * 1800,
91 expectedInterval: time.Hour,
92 },
93 {
94 notBefore: time.Now().Add(time.Hour),
95 override: time.Second * 7200,
96 expectedInterval: 2 * time.Hour,
97 },
98 {
99 notBefore: time.Time{},
100 override: time.Second * 7200,
101 expectedInterval: 2 * time.Hour,
102 },
103 } {
104 b.multiplier = 0
105 b.notBefore = tc.notBefore
106 interval := b.set(&tc.override)
107 if !fuzzyDurationEquals(tc.expectedInterval, interval, testLeeway) {
108 t.Fatalf("backoff.set(%v)=%v; want %v", tc.override, interval, tc.expectedInterval)
109 }
110 }
111 }
112
View as plain text