-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware_test.go
More file actions
299 lines (257 loc) · 6.8 KB
/
Copy pathmiddleware_test.go
File metadata and controls
299 lines (257 loc) · 6.8 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package cadence
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
// ---------------------------------------------------------------------------
// Test logger that captures output
// ---------------------------------------------------------------------------
type testLogger struct {
mu sync.Mutex
infos []string
errors []string
}
func (l *testLogger) Info(msg string, kv ...interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
l.infos = append(l.infos, msg)
}
func (l *testLogger) Error(err error, msg string, kv ...interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
l.errors = append(l.errors, fmt.Sprintf("%s: %v", msg, err))
}
func (l *testLogger) errorCount() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.errors)
}
func (l *testLogger) infoCount() int {
l.mu.Lock()
defer l.mu.Unlock()
return len(l.infos)
}
// ---------------------------------------------------------------------------
// Recover middleware tests
// ---------------------------------------------------------------------------
func TestRecover_NoPanic(t *testing.T) {
logger := &testLogger{}
var called int32
job := Recover(logger)(FuncJob(func() {
atomic.StoreInt32(&called, 1)
}))
job.Run()
if atomic.LoadInt32(&called) != 1 {
t.Error("job should have run")
}
if logger.errorCount() != 0 {
t.Error("should not have logged error")
}
}
func TestRecover_Panic(t *testing.T) {
logger := &testLogger{}
job := Recover(logger)(FuncJob(func() {
panic("test panic")
}))
// Should not panic.
job.Run()
if logger.errorCount() != 1 {
t.Errorf("expected 1 error, got %d", logger.errorCount())
}
}
// ---------------------------------------------------------------------------
// SkipIfStillRunning middleware tests
// ---------------------------------------------------------------------------
func TestSkipIfStillRunning(t *testing.T) {
logger := &testLogger{}
var running int32
started := make(chan struct{})
done := make(chan struct{})
job := SkipIfStillRunning(logger)(FuncJob(func() {
atomic.AddInt32(&running, 1)
started <- struct{}{}
<-done
atomic.AddInt32(&running, -1)
}))
// Start first run in background.
go job.Run()
<-started
// Second run should be skipped.
job.Run()
if logger.infoCount() != 1 {
t.Errorf("expected 1 skip info, got %d", logger.infoCount())
}
// Release first run.
done <- struct{}{}
}
// ---------------------------------------------------------------------------
// DelayIfStillRunning middleware tests
// ---------------------------------------------------------------------------
func TestDelayIfStillRunning(t *testing.T) {
logger := &testLogger{}
var order []int
var mu sync.Mutex
gate := make(chan struct{})
job := DelayIfStillRunning(logger)(FuncJob(func() {
mu.Lock()
order = append(order, len(order)+1)
mu.Unlock()
select {
case <-gate:
case <-time.After(time.Second):
}
}))
// Start first run.
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
job.Run()
}()
// Give first run time to start.
time.Sleep(50 * time.Millisecond)
// Start second run — should block until first completes.
go func() {
defer wg.Done()
job.Run()
}()
// Release first run.
gate <- struct{}{}
time.Sleep(50 * time.Millisecond)
// Release second run.
gate <- struct{}{}
wg.Wait()
mu.Lock()
defer mu.Unlock()
if len(order) != 2 || order[0] != 1 || order[1] != 2 {
t.Errorf("expected sequential [1, 2], got %v", order)
}
}
// ---------------------------------------------------------------------------
// Chain tests
// ---------------------------------------------------------------------------
func TestChain_Multiple(t *testing.T) {
var calls []string
wrapper1 := func(j Job) Job {
return FuncJob(func() {
calls = append(calls, "before1")
j.Run()
calls = append(calls, "after1")
})
}
wrapper2 := func(j Job) Job {
return FuncJob(func() {
calls = append(calls, "before2")
j.Run()
calls = append(calls, "after2")
})
}
chain := NewChain(wrapper1, wrapper2)
job := chain.Then(FuncJob(func() {
calls = append(calls, "job")
}))
job.Run()
expected := []string{"before1", "before2", "job", "after2", "after1"}
if len(calls) != len(expected) {
t.Fatalf("got %v, want %v", calls, expected)
}
for i := range expected {
if calls[i] != expected[i] {
t.Errorf("call[%d] = %q, want %q", i, calls[i], expected[i])
}
}
}
// ---------------------------------------------------------------------------
// Logger tests
// ---------------------------------------------------------------------------
func TestPrintfLogger(t *testing.T) {
var msgs []string
l := &fakeStdLogger{msgs: &msgs}
logger := PrintfLogger(l)
logger.Info("should be silent")
if len(msgs) != 0 {
t.Error("PrintfLogger should not log Info")
}
logger.Error(fmt.Errorf("boom"), "test error")
if len(msgs) != 1 {
t.Errorf("expected 1 error log, got %d", len(msgs))
}
}
func TestVerbosePrintfLogger(t *testing.T) {
var msgs []string
l := &fakeStdLogger{msgs: &msgs}
logger := VerbosePrintfLogger(l)
logger.Info("hello", "key", "value")
if len(msgs) != 1 {
t.Errorf("expected 1 info log, got %d", len(msgs))
}
logger.Error(fmt.Errorf("boom"), "test error")
if len(msgs) != 2 {
t.Errorf("expected 2 logs, got %d", len(msgs))
}
}
func TestDiscardLogger(t *testing.T) {
// Should not panic.
DiscardLogger.Info("hello")
DiscardLogger.Error(fmt.Errorf("boom"), "error")
}
type fakeStdLogger struct {
msgs *[]string
}
func (f *fakeStdLogger) Printf(format string, args ...interface{}) {
*f.msgs = append(*f.msgs, fmt.Sprintf(format, args...))
}
// ---------------------------------------------------------------------------
// Option tests
// ---------------------------------------------------------------------------
func TestWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := New(WithContext(ctx))
c.AddFunc("@every 1h", func() {})
c.Start()
// Cancel the parent context.
cancel()
// The cron's internal context should also be cancelled.
select {
case <-c.ctx.Done():
// expected
case <-time.After(time.Second):
t.Error("expected cron context to be cancelled")
}
c.Stop()
}
func TestWithJitter(t *testing.T) {
c := New(WithJitter(100 * time.Millisecond))
if c.jitter != 100*time.Millisecond {
t.Errorf("jitter = %v", c.jitter)
}
}
func TestApplyJitter_Zero(t *testing.T) {
c := New()
now := time.Now()
result := c.applyJitter(now)
if !result.Equal(now) {
t.Error("zero jitter should not modify time")
}
}
func TestApplyJitter_NonZero(t *testing.T) {
c := New(WithJitter(time.Second))
now := time.Now()
result := c.applyJitter(now)
diff := result.Sub(now)
if diff < 0 || diff > time.Second {
t.Errorf("jitter out of range: %v", diff)
}
}
func TestWithLogger(t *testing.T) {
logger := &testLogger{}
c := New(WithLogger(logger))
if c.logger != logger {
t.Error("logger not set")
}
}