-
Notifications
You must be signed in to change notification settings - Fork 0
/
periodic_test.go
121 lines (100 loc) · 2.15 KB
/
periodic_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
113
114
115
116
117
118
119
120
121
package devp2p
import (
"testing"
"time"
)
var (
span = time.Duration(100 * time.Millisecond).Nanoseconds()
)
func testPeriodicDispatcher() *Dispatcher {
d := NewDispatcher()
d.SetEnabled(true)
return d
}
type dummyJob struct {
id string
}
func (d *dummyJob) ID() string {
return d.id
}
func job(id string) Job {
return &dummyJob{id}
}
func waitForEvent(d *Dispatcher, id string, t *testing.T) time.Duration {
now := time.Now()
evnt := <-d.Events()
if evnt.ID() != id {
t.Fatalf("expected %s but found %s", id, evnt.ID())
}
return time.Now().Sub(now)
}
func validPeriod(i, j time.Duration, t *testing.T) {
d := i.Nanoseconds() - j.Nanoseconds()
if d < 0 {
d = d * -1
}
if d > span {
t.Fatal("bad")
}
}
func TestPeriodicDispatcherAddJob(t *testing.T) {
d := testPeriodicDispatcher()
if err := d.Add(job("a"), 1*time.Second); err != nil {
t.Fatal(err)
}
if len(d.Tracked()) != 1 {
t.Fatal("it should have 1 tracked jobs")
}
}
func TestPeriodicDispatcherRemoveJob(t *testing.T) {
d := testPeriodicDispatcher()
if err := d.Add(job("a"), 1*time.Second); err != nil {
t.Fatal(err)
}
if err := d.Remove("a"); err != nil {
t.Fatal(err)
}
if len(d.Tracked()) != 0 {
t.Fatal("it should have 0 tracked jobs")
}
}
func TestPeriodicDispatcherEvent(t *testing.T) {
d := testPeriodicDispatcher()
period := 100 * time.Millisecond
if err := d.Add(job("a"), period); err != nil {
t.Fatal(err)
}
dur0 := waitForEvent(d, "a", t)
validPeriod(dur0, period, t)
dur1 := waitForEvent(d, "a", t)
validPeriod(dur1, period, t)
d.SetEnabled(false)
select {
case e := <-d.Events():
t.Fatalf("event %d not expected", e)
case <-time.After(150 * time.Millisecond):
}
}
func TestPeriodicDispatcherMultipleEvents(t *testing.T) {
d := testPeriodicDispatcher()
period0 := 100 * time.Millisecond
if err := d.Add(job("a"), period0); err != nil {
t.Fatal(err)
}
period1 := 210 * time.Millisecond
if err := d.Add(job("b"), period1); err != nil {
t.Fatal(err)
}
// a
waitForEvent(d, "a", t)
// a
waitForEvent(d, "a", t)
// b
waitForEvent(d, "b", t)
// a
waitForEvent(d, "a", t)
// a
waitForEvent(d, "a", t)
// b
waitForEvent(d, "b", t)
}