forked from bamzi/jobrunner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runjob_test.go
134 lines (107 loc) · 2.4 KB
/
runjob_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
122
123
124
125
126
127
128
129
130
131
132
133
134
package jobrunner
import (
"context"
"fmt"
"testing"
"time"
)
var (
testOpts []Option
)
func stateChanged(j *Job) {
fmt.Printf("%s-%s p[%s] n[%s]\n",
j.name, j.currentState,
j.prev.Format(time.RFC3339),
j.next.Format(time.RFC3339))
}
func init() {
testOpts = []Option{
WithStateUpdateDuration(1 * time.Second),
}
}
type TestRunner struct {
count int
}
func (p *TestRunner) Run() error {
fmt.Println("callback triggered")
p.count++
return nil
}
func NewTestRunner() *TestRunner {
runner := &TestRunner{
count: 0,
}
return runner
}
func TestDebounce(t *testing.T) {
OnJobChanged(stateChanged)
ctx, cancel := context.WithCancel(context.Background())
Start(ctx, testOpts...)
defer cancel()
runner := NewTestRunner()
job := New("Debounced", runner)
Debounced(5*time.Second, job, BuildWrapperDefault)
time.Sleep(3 * time.Second)
Debounced(5*time.Second, job, BuildWrapperDefault)
time.Sleep(12 * time.Second)
if runner.count != 1 {
t.Error(runner.count)
t.FailNow()
}
}
func TestNTimesEvery(t *testing.T) {
OnJobChanged(stateChanged)
ctx, cancel := context.WithCancel(context.Background())
Start(ctx, testOpts...)
defer cancel()
runner := NewTestRunner()
job := New("NTimesEvery", runner)
NTimesEvery(8, 2*time.Second, job, BuildWrapperDefault)
time.Sleep(20 * time.Second)
if runner.count != 8 {
t.Error(runner.count)
t.Fail()
}
}
func TestOnceNow(t *testing.T) {
OnJobChanged(stateChanged)
ctx, cancel := context.WithCancel(context.Background())
Start(ctx, testOpts...)
defer cancel()
runner := NewTestRunner()
job := New("OnceNow", runner)
OnceNow(job, BuildWrapperDefault)
time.Sleep(10 * time.Second)
if runner.count != 1 {
t.Error(runner.count)
t.Fail()
}
}
func TestAt(t *testing.T) {
OnJobChanged(stateChanged)
ctx, cancel := context.WithCancel(context.Background())
Start(ctx, testOpts...)
defer cancel()
runner := NewTestRunner()
job := New("At", runner)
At(Now().Add(5*time.Second), job, BuildWrapperDefault)
time.Sleep(11 * time.Second)
if runner.count != 1 {
t.Error(runner.count)
t.Fail()
}
}
func TestEvery(t *testing.T) {
OnJobChanged(stateChanged)
ctx, cancel := context.WithCancel(context.Background())
Start(ctx)
defer cancel()
runner := NewTestRunner()
job := New("Every", runner)
Every(2*time.Second, job, BuildWrapperDefault)
time.Sleep(11 * time.Second)
if runner.count != 5 {
t.Error(runner.count)
t.Fail()
}
}