-
Notifications
You must be signed in to change notification settings - Fork 5
/
queue_test.go
99 lines (81 loc) · 1.94 KB
/
queue_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
package timerqueue
import (
"math/rand"
"testing"
"time"
)
type object struct {
value int
}
var executed int
func (o *object) OnTimer(t time.Time) {
executed++
}
func populateQueue(t *testing.T, now time.Time) *Queue {
q := New()
count := 300
objects := make([]*object, count)
// Add a bunch of objects to the queue in random order.
for i, j := range rand.Perm(count) {
tm := now.Add(time.Duration(i+1) * time.Hour)
objects[j] = &object{j}
q.Schedule(objects[j], tm)
}
// Reschedule all the objects in a different random order.
for i, j := range rand.Perm(count) {
tm := now.Add(time.Duration(i+1) * time.Hour)
q.Schedule(objects[j], tm)
}
if q.Len() != count {
t.Error("invalid queue length:", q.Len())
}
return q
}
func TestEmptyQueue(t *testing.T) {
queue := New()
o, _ := queue.PeekFirst()
if o != nil {
t.Error("Expected nil peek")
}
o, _ = queue.PopFirst()
if o != nil {
t.Error("Expected nil pop")
}
}
func TestQueue(t *testing.T) {
for iter := 0; iter < 100; iter++ {
now := time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)
queue := populateQueue(t, now)
// Make sure objects are removed from the queue in order.
for prev := now; queue.Len() > 0; {
_, ptm := queue.PeekFirst()
_, tm := queue.PopFirst()
if tm != ptm {
t.Errorf("Peek/Pop mismatch.\n")
}
if tm.Sub(prev) != time.Hour {
t.Errorf("Invalid queue ordering.\n"+
" Got: %v\n"+
"Expected: %v\n", tm, prev.Add(time.Hour))
}
prev = tm
}
}
}
func TestAdvance(t *testing.T) {
for iter := 0; iter < 100; iter++ {
now := time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)
queue := populateQueue(t, now)
executed = 0
count := queue.Len()
lastTime := now.Add(time.Duration(count) * time.Hour)
for adv := 0; adv < 5; adv++ {
queue.Advance(lastTime)
if executed != count {
t.Errorf("Advance failed.\n"+
"Should have executed %d times.\n"+
"Only executed %d times.\n", count, executed)
}
}
}
}