Repository navigation
Expand file tree
/
Copy pathcron_test.go
More file actions
771 lines (707 loc) · 20.6 KB
/
Copy pathcron_test.go
File metadata and controls
771 lines (707 loc) · 20.6 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
package cron_test
import (
"context"
"errors"
"slices"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"github.com/libtnb/cron"
)
func noop(ctx context.Context) error { return nil }
type typedNilSchedule struct{}
func (*typedNilSchedule) Next(time.Time) time.Time { return time.Time{} }
func TestCron_NewIsIdle(t *testing.T) {
c := cron.MustNew()
if e, ok := c.Entry(1); ok {
t.Fatalf("zero scheduler should have no entries, got %+v", e)
}
if got := slices.Collect(c.Entries()); len(got) != 0 {
t.Fatalf("Entries len = %d", len(got))
}
}
func TestCron_AddAndEntry(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
id, err := c.Add("@every 1m", cron.JobFunc(noop), cron.WithName("ping"))
if err != nil {
t.Fatal(err)
}
got, ok := c.Entry(id)
if !ok {
t.Fatal("Entry missing")
}
if got.ID != id || got.Name != "ping" || got.Spec != "@every 1m" {
t.Fatalf("Entry = %+v", got)
}
if got.Next.IsZero() {
t.Fatal("Next should be populated")
}
}
func TestCron_AddInvalidSpec_ReturnsParseError(t *testing.T) {
c := cron.MustNew()
_, err := c.Add("@nope", cron.JobFunc(noop))
if err == nil {
t.Fatal("expected error")
}
var pe *cron.ParseError
if !errors.As(err, &pe) {
t.Fatalf("got %T", err)
}
}
func TestCron_Remove(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
keep, _ := c.Add("@every 2m", cron.JobFunc(noop))
id, _ := c.Add("@every 1m", cron.JobFunc(noop))
if err := c.Remove(id); err != nil {
t.Fatalf("Remove: %v", err)
}
if err := c.Remove(id); !errors.Is(err, cron.ErrEntryNotFound) {
t.Fatalf("second Remove = %v, want ErrEntryNotFound", err)
}
if _, ok := c.Entry(id); ok {
t.Fatal("Entry still present after Remove")
}
if _, ok := c.Entry(keep); !ok {
t.Fatal("untouched entry should remain")
}
}
func TestCron_MaxEntries(t *testing.T) {
c := cron.MustNew(cron.WithMaxEntries(2), cron.WithLocation(time.UTC))
if _, err := c.Add("@every 1m", cron.JobFunc(noop)); err != nil {
t.Fatal(err)
}
if _, err := c.Add("@every 2m", cron.JobFunc(noop)); err != nil {
t.Fatal(err)
}
id, err := c.Add("@every 3m", cron.JobFunc(noop))
if !errors.Is(err, cron.ErrCapacityReached) {
t.Fatalf("3rd Add err = %v, want ErrCapacityReached", err)
}
if id != 0 {
t.Fatalf("3rd Add id = %d", id)
}
}
func TestCron_FiresOnSchedule(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
var calls atomic.Int64
_, err := c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
if err != nil {
t.Fatal(err)
}
_ = c.Start()
time.Sleep(10 * time.Second)
synctest.Wait()
_ = c.Stop(context.Background())
got := calls.Load()
if got < 9 || got > 11 {
t.Fatalf("calls = %d, want ~10", got)
}
})
}
func TestCron_RemovedEntryStopsFiring(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
var calls atomic.Int64
id, _ := c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
_ = c.Start()
time.Sleep(3 * time.Second)
synctest.Wait()
if err := c.Remove(id); err != nil {
t.Fatal(err)
}
before := calls.Load()
time.Sleep(5 * time.Second)
synctest.Wait()
after := calls.Load()
if after != before {
t.Fatalf("entry continued firing after Remove: before=%d after=%d", before, after)
}
_ = c.Stop(context.Background())
})
}
func TestCron_AddAtRuntime(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
_ = c.Start()
var calls atomic.Int64
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
time.Sleep(3 * time.Second)
synctest.Wait()
if got := calls.Load(); got < 2 || got > 4 {
t.Fatalf("calls = %d, want ~3", got)
}
_ = c.Stop(context.Background())
})
}
func TestCron_StopWaitsForInflightJob(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
started := make(chan struct{})
var release atomic.Bool
var done atomic.Bool
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
close(started)
for !release.Load() {
time.Sleep(100 * time.Millisecond)
}
done.Store(true)
return nil
}))
_ = c.Start()
<-started
stopErr := make(chan error, 1)
go func() {
stopErr <- c.Stop(context.Background())
}()
time.Sleep(2 * time.Second)
if done.Load() {
t.Fatal("job should not have completed yet")
}
release.Store(true)
synctest.Wait()
if err := <-stopErr; err != nil {
t.Fatalf("Stop err: %v", err)
}
if !done.Load() {
t.Fatal("job should have completed before Stop returned")
}
})
}
func TestCron_StopCancelsInflightJobContext(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
var seenCause atomic.Pointer[error]
jobReady := make(chan struct{})
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
select {
case <-jobReady:
default:
close(jobReady)
}
<-ctx.Done()
cause := context.Cause(ctx)
seenCause.CompareAndSwap(nil, &cause)
return ctx.Err()
}))
_ = c.Start()
<-jobReady // first invocation has entered
if err := c.Stop(context.Background()); err != nil {
t.Fatalf("Stop err: %v", err)
}
got := seenCause.Load()
if got == nil {
t.Fatal("Stop did not cancel job ctx (job never returned)")
}
if !errors.Is(*got, cron.ErrCronStopping) {
t.Fatalf("cause = %v, want ErrCronStopping", *got)
}
})
}
func TestCron_StopWithoutStartReturnsImmediately(t *testing.T) {
c := cron.MustNew()
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
if err := c.Stop(ctx); err != nil {
t.Fatalf("Stop on unstarted cron returned %v, want nil", err)
}
}
func TestCron_StopIsIdempotent(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error { return nil }))
_ = c.Start()
time.Sleep(2 * time.Second)
synctest.Wait()
if err := c.Stop(context.Background()); err != nil {
t.Fatalf("first Stop: %v", err)
}
if err := c.Stop(context.Background()); err != nil {
t.Fatalf("second Stop: %v", err)
}
})
}
func TestCron_StartAfterStopReturnsErr(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
hk := &recordingObserver{}
c := cron.MustNew(cron.WithLocation(time.UTC), cron.WithObservers(hk))
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error { return nil }))
if err := c.Start(); err != nil {
t.Fatalf("first Start: %v", err)
}
time.Sleep(2 * time.Second)
synctest.Wait()
_ = c.Stop(context.Background())
first := hk.starts.Load()
if first == 0 {
t.Fatal("hook never invoked before stop")
}
if err := c.Start(); !errors.Is(err, cron.ErrSchedulerStopped) {
t.Fatalf("Start after Stop err = %v, want ErrSchedulerStopped", err)
}
time.Sleep(2 * time.Second)
synctest.Wait()
if hk.starts.Load() != first {
t.Fatalf("Start after Stop dispatched jobs: before=%d after=%d", first, hk.starts.Load())
}
})
}
func TestCron_StartIdempotentWhileRunning(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
if err := c.Start(); err != nil {
t.Fatal(err)
}
if err := c.Start(); err != nil {
t.Fatalf("second Start while running should be nil, got %v", err)
}
_ = c.Stop(context.Background())
})
}
func TestCron_Running(t *testing.T) {
c := cron.MustNew()
if c.Running() {
t.Fatal("Running() before Start should be false")
}
_ = c.Start()
if !c.Running() {
t.Fatal("Running() after Start should be true")
}
_ = c.Stop(context.Background())
if c.Running() {
t.Fatal("Running() after Stop should be false")
}
}
func TestCron_GlobalRetryAppliesWhenEntryDoesNotOverride(t *testing.T) {
var attempts atomic.Int64
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithRetry(cron.Retry(2, cron.RetryInitial(time.Millisecond))),
)
id, err := c.AddSchedule(cron.TriggeredSchedule(),
cron.JobFunc(func(ctx context.Context) error {
attempts.Add(1)
return errors.New("boom")
}),
cron.WithName("retryable"),
)
if err != nil {
t.Fatal(err)
}
if err := c.Start(); err != nil {
t.Fatal(err)
}
defer func() { _ = c.Stop(context.Background()) }()
if err := c.Trigger(id); err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) && attempts.Load() < 3 {
time.Sleep(2 * time.Millisecond)
}
if attempts.Load() != 3 {
t.Fatalf("attempts = %d, want 3 (initial + 2 retries from global)", attempts.Load())
}
}
func TestCron_StopRespectsContextDeadline(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
unblock := make(chan struct{})
t.Cleanup(func() {
close(unblock)
_ = c.Stop(context.Background())
})
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
<-unblock
return nil
}))
_ = c.Start()
time.Sleep(2 * time.Second)
synctest.Wait()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
err := c.Stop(ctx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Stop err = %v, want DeadlineExceeded", err)
}
})
}
func TestCron_Trigger(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
var calls atomic.Int64
id, _ := c.AddSchedule(cron.TriggeredSchedule(), cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}), cron.WithName("manual"))
_ = c.Start()
time.Sleep(5 * time.Second)
synctest.Wait()
if got := calls.Load(); got != 0 {
t.Fatalf("auto fires for triggered schedule: %d", got)
}
if err := c.Trigger(id); err != nil {
t.Fatalf("Trigger: %v", err)
}
synctest.Wait()
if got := calls.Load(); got != 1 {
t.Fatalf("after trigger calls = %d", got)
}
_ = c.Stop(context.Background())
})
}
func TestCron_Timeout_CancelsViaCause(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
var seenCause atomic.Pointer[error]
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
<-ctx.Done()
cause := context.Cause(ctx)
seenCause.CompareAndSwap(nil, &cause)
return ctx.Err()
}), cron.WithTimeout(500*time.Millisecond))
_ = c.Start()
time.Sleep(1700 * time.Millisecond)
synctest.Wait()
_ = c.Stop(context.Background())
got := seenCause.Load()
if got == nil {
t.Fatal("no cause captured")
}
if !errors.Is(*got, cron.ErrJobTimeout) {
t.Fatalf("cause = %v, want ErrJobTimeout", *got)
}
})
}
func TestCron_Entries_OrderedByNext(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
_, _ = c.Add("@every 5m", cron.JobFunc(noop), cron.WithName("slow"))
_, _ = c.Add("@every 1m", cron.JobFunc(noop), cron.WithName("fast"))
got := slices.Collect(c.Entries())
if len(got) != 2 {
t.Fatalf("len = %d", len(got))
}
if !got[0].Next.Before(got[1].Next) {
t.Fatalf("not sorted: %v %v", got[0].Next, got[1].Next)
}
if got[0].Name != "fast" {
t.Fatalf("first = %q", got[0].Name)
}
}
func TestCron_Entries_TriggeredEntriesSortLast(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
_, _ = c.AddSchedule(cron.TriggeredSchedule(), cron.JobFunc(noop), cron.WithName("manual"))
_, _ = c.Add("@every 1m", cron.JobFunc(noop), cron.WithName("auto"))
got := slices.Collect(c.Entries())
if len(got) != 2 {
t.Fatalf("len = %d", len(got))
}
if got[0].Name != "auto" || got[1].Name != "manual" {
t.Fatalf("order = [%q, %q], want [auto, manual]", got[0].Name, got[1].Name)
}
if !got[1].Next.IsZero() {
t.Fatalf("triggered entry Next should be zero, got %v", got[1].Next)
}
}
func TestCron_MissedRunOnce_FiresFirstMissedWhenOnlyOneMissed(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithMissedFire(cron.MissedRunOnce),
cron.WithMissedTolerance(100*time.Millisecond),
)
var calls atomic.Int32
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
time.Sleep(1500 * time.Millisecond)
synctest.Wait()
_ = c.Start()
time.Sleep(100 * time.Millisecond)
synctest.Wait()
_ = c.Stop(context.Background())
if got := calls.Load(); got < 1 {
t.Fatalf("MissedRunOnce did not fire the single missed firing; calls=%d", got)
}
})
}
func TestCron_StopBeforeStartLocksOutFutureStart(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
var calls atomic.Int32
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
_ = c.Stop(context.Background())
if err := c.Start(); !errors.Is(err, cron.ErrSchedulerStopped) {
t.Fatalf("Start err = %v, want ErrSchedulerStopped", err)
}
time.Sleep(5 * time.Second)
synctest.Wait()
_ = c.Stop(context.Background())
if got := calls.Load(); got != 0 {
t.Fatalf("Start after Stop should not dispatch; calls=%d", got)
}
})
}
func TestCron_StopSuppressedFiringDoesNotEmitMissed(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var missed atomic.Int32
hk := &countingObserver{missed: &missed}
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithObservers(hk),
)
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
return nil
}))
_ = c.Start()
synctest.Wait()
_ = c.Stop(context.Background())
if got := missed.Load(); got != 0 {
t.Fatalf("Stop-suppressed firing recorded as missed: missed=%d", got)
}
})
}
type countingObserver struct {
missed *atomic.Int32
}
func (o *countingObserver) Observe(event cron.Event) {
if _, ok := event.(cron.MissedFireEvent); ok {
o.missed.Add(1)
}
}
func TestCron_TriggerLosesRaceWithRemove(t *testing.T) {
for trial := range 200 {
c := cron.MustNew(cron.WithLocation(time.UTC))
var ran atomic.Bool
id, _ := c.AddSchedule(cron.TriggeredSchedule(),
cron.JobFunc(func(ctx context.Context) error {
ran.Store(true)
return nil
}))
_ = c.Start()
var triggerOK, removeOK atomic.Bool
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); triggerOK.Store(c.Trigger(id) == nil) }()
go func() { defer wg.Done(); removeOK.Store(c.Remove(id) == nil) }()
wg.Wait()
_ = c.Stop(context.Background())
if removeOK.Load() && triggerOK.Load() {
continue
}
if !triggerOK.Load() && ran.Load() {
t.Fatalf("trial %d: Trigger errored but Job still ran", trial)
}
}
}
func TestCron_MaxConcurrentSaturatedDropsTrigger(t *testing.T) {
release := make(chan struct{})
hk := &recordingObserver{}
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithMaxConcurrent(1),
cron.WithObservers(hk),
)
var ran atomic.Int32
id, _ := c.AddSchedule(cron.TriggeredSchedule(),
cron.JobFunc(func(ctx context.Context) error {
ran.Add(1)
<-release
return nil
}))
_ = c.Start()
if err := c.Trigger(id); err != nil {
t.Fatalf("first Trigger: %v", err)
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) && ran.Load() < 1 {
time.Sleep(5 * time.Millisecond)
}
if ran.Load() < 1 {
close(release)
_ = c.Stop(context.Background())
t.Fatal("first job never started")
}
if err := c.Trigger(id); !errors.Is(err, cron.ErrConcurrencyLimit) {
t.Fatalf("second Trigger err = %v, want ErrConcurrencyLimit", err)
}
close(release)
_ = c.Stop(context.Background())
if hk.rejected.Load() == 0 {
t.Fatal("rejected Trigger should emit RejectedFireEvent")
}
}
func TestCron_MaxConcurrentSchedulerSaturationEmitsRejected(t *testing.T) {
r := &counterRecorder{}
release := make(chan struct{})
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithMaxConcurrent(1),
cron.WithRecorder(r),
)
_, _ = c.Add("@every 100ms", cron.JobFunc(func(ctx context.Context) error {
<-release
return nil
}))
_ = c.Start()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) && r.rejected.Load() == 0 {
time.Sleep(20 * time.Millisecond)
}
close(release)
_ = c.Stop(context.Background())
if r.rejected.Load() == 0 {
t.Fatal("expected RejectedFireEvent when MaxConcurrent saturates")
}
}
func TestCron_TriggerOnUnknownIDReturnsErr(t *testing.T) {
c := cron.MustNew()
_ = c.Start()
defer func() { _ = c.Stop(context.Background()) }()
if err := c.Trigger(cron.EntryID(999)); !errors.Is(err, cron.ErrEntryNotFound) {
t.Fatalf("Trigger err = %v, want ErrEntryNotFound", err)
}
}
func TestCron_TriggerWhenNotRunning(t *testing.T) {
c := cron.MustNew()
id, _ := c.AddSchedule(cron.TriggeredSchedule(), cron.JobFunc(noop))
if err := c.Trigger(id); !errors.Is(err, cron.ErrSchedulerNotRunning) {
t.Fatalf("Trigger err = %v, want ErrSchedulerNotRunning", err)
}
}
func TestCron_AddCacheHitErrorReturned(t *testing.T) {
c := cron.MustNew()
if _, err := c.Add("@nope", cron.JobFunc(noop)); err == nil {
t.Fatal("first Add expected ParseError")
}
if _, err := c.Add("@nope", cron.JobFunc(noop)); err == nil {
t.Fatal("cache-hit on bad spec should still return error")
}
}
func TestCron_AddCacheHitSuccess(t *testing.T) {
c := cron.MustNew(cron.WithLocation(time.UTC))
id1, err := c.Add("@every 1m", cron.JobFunc(noop))
if err != nil {
t.Fatal(err)
}
id2, err := c.Add("@every 1m", cron.JobFunc(noop))
if err != nil {
t.Fatal(err)
}
if id1 == id2 {
t.Fatal("entry IDs must differ")
}
}
func TestCron_JitterSucceedsBeforeStop(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithJitter(10*time.Millisecond),
)
var calls atomic.Int64
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
_ = c.Start()
time.Sleep(3 * time.Second)
synctest.Wait()
_ = c.Stop(context.Background())
if calls.Load() < 2 {
t.Fatalf("jitter timer success path never hit; calls=%d", calls.Load())
}
})
}
func TestCron_JitterZeroDurationIsNoop(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithJitter(1),
)
var calls atomic.Int64
_, _ = c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
_ = c.Start()
time.Sleep(2 * time.Second)
synctest.Wait()
_ = c.Stop(context.Background())
if calls.Load() < 1 {
t.Fatalf("jitter d<=0 fast path skipped firing; calls=%d", calls.Load())
}
})
}
func TestCron_PrevNotAdvancedWhenJitterCancelsBeforeRun(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := cron.MustNew(
cron.WithLocation(time.UTC),
cron.WithJitter(10*time.Second),
)
var calls atomic.Int32
id, _ := c.Add("@every 1s", cron.JobFunc(func(ctx context.Context) error {
calls.Add(1)
return nil
}))
_ = c.Start()
time.Sleep(1100 * time.Millisecond)
synctest.Wait()
_ = c.Stop(context.Background())
if calls.Load() != 0 {
t.Fatalf("expected job to be cancelled in jitter; calls=%d", calls.Load())
}
view, ok := c.Entry(id)
if !ok {
t.Fatal("entry vanished")
}
if !view.Prev.IsZero() {
t.Fatalf("Prev advanced for a fire that never ran: %v", view.Prev)
}
})
}
func TestAdd_InvalidSpecReturnsError(t *testing.T) {
c := cron.MustNew()
if _, err := c.Add("definitely not a spec", cron.JobFunc(noop)); err == nil {
t.Fatal("expected a parse error for an invalid spec")
}
}
func TestAdd_NilJobAndSchedule(t *testing.T) {
c := cron.MustNew()
if _, err := c.Add("@every 1s", nil); !errors.Is(err, cron.ErrNilJob) {
t.Fatalf("Add(nil job) = %v, want ErrNilJob", err)
}
if _, err := c.AddSchedule(nil, cron.JobFunc(noop)); !errors.Is(err, cron.ErrNilSchedule) {
t.Fatalf("AddSchedule(nil schedule) = %v, want ErrNilSchedule", err)
}
var nilJob cron.JobFunc
if _, err := c.Add("@every 1s", nilJob); !errors.Is(err, cron.ErrNilJob) {
t.Fatalf("Add(typed-nil job) = %v, want ErrNilJob", err)
}
var nilSchedule *typedNilSchedule
if _, err := c.AddSchedule(nilSchedule, cron.JobFunc(noop)); !errors.Is(err, cron.ErrNilSchedule) {
t.Fatalf("AddSchedule(typed-nil schedule) = %v, want ErrNilSchedule", err)
}
badParser := parserFunc(func(string) (cron.Schedule, error) { return nilSchedule, nil })
if _, err := cron.MustNew(cron.WithParser(badParser)).Add("ignored", cron.JobFunc(noop)); !errors.Is(err, cron.ErrNilSchedule) {
t.Fatalf("typed-nil parsed schedule = %v, want ErrNilSchedule", err)
}
nilWrapping := cron.MustNew(cron.WithChain(func(cron.Job) cron.Job { return nil }))
if _, err := nilWrapping.Add("@every 1s", cron.JobFunc(noop)); !errors.Is(err, cron.ErrNilJob) {
t.Fatalf("nil wrapper output = %v, want ErrNilJob", err)
}
}