-
Notifications
You must be signed in to change notification settings - Fork 186
/
ticker_test.go
96 lines (80 loc) · 1.74 KB
/
ticker_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
package backoff
import (
"context"
"errors"
"fmt"
"log"
"testing"
)
func TestTicker(t *testing.T) {
const successOn = 3
var i = 0
// This function is successful on "successOn" calls.
f := func() error {
i++
log.Printf("function is called %d. time\n", i)
if i == successOn {
log.Println("OK")
return nil
}
log.Println("error")
return errors.New("error")
}
b := NewExponentialBackOff()
ticker := NewTickerWithTimer(b, &testTimer{})
var err error
for range ticker.C {
if err = f(); err != nil {
t.Log(err)
continue
}
break
}
if err != nil {
t.Errorf("unexpected error: %s", err.Error())
}
if i != successOn {
t.Errorf("invalid number of retries: %d", i)
}
}
func TestTickerContext(t *testing.T) {
var i = 0
ctx, cancel := context.WithCancel(context.Background())
// Cancel context as soon as it is created.
// Ticker must stop after first tick.
cancel()
// This function cancels context on "cancelOn" calls.
f := func() error {
i++
log.Printf("function is called %d. time\n", i)
log.Println("error")
return fmt.Errorf("error (%d)", i)
}
b := WithContext(NewConstantBackOff(0), ctx)
ticker := NewTickerWithTimer(b, &testTimer{})
var err error
for range ticker.C {
if err = f(); err != nil {
t.Log(err)
continue
}
ticker.Stop()
break
}
// Ticker is guaranteed to tick at least once.
if err == nil {
t.Errorf("error is unexpectedly nil")
}
if err.Error() != "error (1)" {
t.Errorf("unexpected error: %s", err)
}
if i != 1 {
t.Errorf("invalid number of retries: %d", i)
}
}
func TestTickerDefaultTimer(t *testing.T) {
b := NewExponentialBackOff()
ticker := NewTickerWithTimer(b, nil)
// ensure a timer was actually assigned, instead of remaining as nil.
<-ticker.C
}