forked from stakwork/sphinx-tribes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
853 lines (770 loc) · 22.5 KB
/
main_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
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
package main
import (
"context"
"errors"
"fmt"
"os"
"reflect"
"sync"
"syscall"
"testing"
"time"
"github.com/robfig/cron"
"github.com/stretchr/testify/assert"
)
type MockDB struct {
initDBFunc func() error
processUpdateTicketsWithoutGroupFunc func()
}
func (m *MockDB) InitDB() error { return m.initDBFunc() }
func (m *MockDB) ProcessUpdateTicketsWithoutGroup() { m.processUpdateTicketsWithoutGroupFunc() }
type MockRedis struct{ initFunc func() error }
type MockCache struct{ initFunc func() error }
type MockRoles struct{ initFunc func() error }
type MockWebsocketPool struct{ startFunc func() }
type MockConfig struct{ initFunc func() }
type MockAuth struct{ initFunc func() }
type MockValidator struct{ newFunc func() }
type MockHandlers struct {
processTwitterFunc func()
processGithubFunc func()
}
func (m *MockRedis) InitRedis() error { return m.initFunc() }
func (m *MockCache) InitCache() error { return m.initFunc() }
func (m *MockRoles) InitRoles() error { return m.initFunc() }
func (m *MockWebsocketPool) Start() { m.startFunc() }
func (m *MockConfig) InitConfig() { m.initFunc() }
func (m *MockAuth) InitJwt() { m.initFunc() }
func (m *MockValidator) New() { m.newFunc() }
func (m *MockHandlers) ProcessTwitterConfirmationsLoop() { m.processTwitterFunc() }
func (m *MockHandlers) ProcessGithubIssuesLoop() { m.processGithubFunc() }
func TestMain(t *testing.T) {
tests := []struct {
name string
setupMocks func(*MockDB, *MockRedis, *MockCache, *MockRoles, *MockWebsocketPool, *MockConfig, *MockAuth, *MockValidator, *MockHandlers)
skipLoops string
expectedError bool
}{
{
name: "Basic Functionality: Successful Initialization",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "false",
expectedError: false,
},
{
name: "Edge Case: Missing .env File",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "",
expectedError: false,
},
{
name: "Error Condition: Database Initialization Failure",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return errors.New("database initialization failed") }
},
skipLoops: "false",
expectedError: true,
},
{
name: "Error Condition: Redis Initialization Failure",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return errors.New("redis initialization failed") }
},
skipLoops: "false",
expectedError: true,
},
{
name: "Edge Case: SKIP_LOOPS Environment Variable Set",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() { t.Error("Twitter loop should not be called") }
h.processGithubFunc = func() { t.Error("Github loop should not be called") }
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "true",
expectedError: false,
},
{
name: "Edge Case: SKIP_LOOPS Environment Variable Not Set",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "",
expectedError: false,
},
{
name: "Special Case: JWT Initialization Order",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
configInitialized := false
conf.initFunc = func() { configInitialized = true }
auth.initFunc = func() {
if !configInitialized {
t.Error("JWT initialized before config")
}
}
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "false",
expectedError: false,
},
{
name: "Error Condition: Validator Initialization Failure",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() { panic("validator initialization failed") }
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "false",
expectedError: true,
},
{
name: "Error Condition: Cron Job Initialization Failure",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() { panic("cron job failed") }
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "false",
expectedError: true,
},
{
name: "Error Condition: Application Run Failure",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() { panic("websocket start failed") }
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "false",
expectedError: true,
},
{
name: "Edge Case: Empty Environment Variables",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
db.initDBFunc = func() error { return nil }
redis.initFunc = func() error { return nil }
cache.initFunc = func() error { return nil }
roles.initFunc = func() error { return nil }
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
},
skipLoops: "",
expectedError: false,
},
{
name: "Concurrency: Simultaneous Initialization",
setupMocks: func(db *MockDB, redis *MockRedis, cache *MockCache, roles *MockRoles, ws *MockWebsocketPool, conf *MockConfig, auth *MockAuth, val *MockValidator, h *MockHandlers) {
initOrder := make([]string, 0, 4)
var mu sync.Mutex
db.initDBFunc = func() error {
mu.Lock()
initOrder = append(initOrder, "db")
mu.Unlock()
return nil
}
redis.initFunc = func() error {
mu.Lock()
initOrder = append(initOrder, "redis")
mu.Unlock()
return nil
}
cache.initFunc = func() error {
mu.Lock()
initOrder = append(initOrder, "cache")
mu.Unlock()
return nil
}
roles.initFunc = func() error {
mu.Lock()
initOrder = append(initOrder, "roles")
mu.Unlock()
return nil
}
ws.startFunc = func() {}
conf.initFunc = func() {}
auth.initFunc = func() {}
val.newFunc = func() {}
h.processTwitterFunc = func() {}
h.processGithubFunc = func() {}
db.processUpdateTicketsWithoutGroupFunc = func() {}
t.Cleanup(func() {
expected := []string{"db", "redis", "cache", "roles"}
if !reflect.DeepEqual(initOrder, expected) {
t.Errorf("Wrong initialization order. Expected %v, got %v", expected, initOrder)
}
})
},
skipLoops: "false",
expectedError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &MockDB{}
mockRedis := &MockRedis{}
mockCache := &MockCache{}
mockRoles := &MockRoles{}
mockWS := &MockWebsocketPool{}
mockConfig := &MockConfig{}
mockAuth := &MockAuth{}
mockValidator := &MockValidator{}
mockHandlers := &MockHandlers{}
tt.setupMocks(mockDB, mockRedis, mockCache, mockRoles, mockWS, mockConfig, mockAuth, mockValidator, mockHandlers)
os.Setenv("SKIP_LOOPS", tt.skipLoops)
defer os.Unsetenv("SKIP_LOOPS")
var initErr error
func() {
defer func() {
if r := recover(); r != nil {
initErr = fmt.Errorf("panic occurred: %v", r)
}
}()
if err := mockDB.InitDB(); err != nil {
initErr = err
return
}
if err := mockRedis.InitRedis(); err != nil {
initErr = err
return
}
if err := mockCache.InitCache(); err != nil {
initErr = err
return
}
if err := mockRoles.InitRoles(); err != nil {
initErr = err
return
}
mockDB.ProcessUpdateTicketsWithoutGroup()
mockConfig.InitConfig()
mockAuth.InitJwt()
func() {
defer func() {
if r := recover(); r != nil {
initErr = fmt.Errorf("panic occurred: %v", r)
}
}()
mockValidator.New()
mockWS.Start()
if tt.skipLoops != "true" {
mockHandlers.ProcessTwitterConfirmationsLoop()
mockHandlers.ProcessGithubIssuesLoop()
}
}()
}()
if tt.expectedError {
assert.Error(t, initErr, "Expected an error but got none")
} else {
assert.NoError(t, initErr, "Expected no error but got: %v", initErr)
}
})
}
}
func TestRun(t *testing.T) {
tests := []struct {
name string
setupMock func() (*MockRouter, chan os.Signal)
signalActions func(chan os.Signal)
expectedError bool
expectedResult string
}{
{
name: "Standard Shutdown Signal Handling",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 1)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
sigChan <- syscall.SIGTERM
},
expectedError: false,
},
{
name: "Router Shutdown Error",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return errors.New("shutdown error")
},
}
sigChan := make(chan os.Signal, 1)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
sigChan <- syscall.SIGTERM
},
expectedError: true,
},
{
name: "Invalid Signal Type",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 1)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
sigChan <- syscall.SIGHUP
},
expectedError: false,
},
{
name: "Multiple Signal Types",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 3)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
go func() {
sigChan <- syscall.SIGTERM
sigChan <- syscall.SIGINT
sigChan <- syscall.SIGHUP
}()
},
expectedError: false,
},
{
name: "Immediate Shutdown Signal",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 1)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
sigChan <- syscall.SIGTERM
},
expectedError: false,
},
{
name: "Delayed Shutdown Signal",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 1)
go func() {
time.Sleep(100 * time.Millisecond)
sigChan <- syscall.SIGTERM
}()
return router, sigChan
},
expectedError: false,
},
{
name: "High Volume of Signals",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 100)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
go func() {
for i := 0; i < 100; i++ {
sigChan <- syscall.SIGTERM
}
}()
},
expectedError: false,
},
{
name: "Context Timeout",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(6 * time.Second):
return nil
}
},
}
sigChan := make(chan os.Signal, 1)
return router, sigChan
},
signalActions: func(sigChan chan os.Signal) {
sigChan <- syscall.SIGTERM
},
expectedError: true,
},
{
name: "No Signal Received",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
return nil
},
}
sigChan := make(chan os.Signal, 1)
go func() {
time.Sleep(100 * time.Millisecond)
close(sigChan)
}()
return router, sigChan
},
expectedError: false,
},
{
name: "Signal Handling During Router Initialization",
setupMock: func() (*MockRouter, chan os.Signal) {
router := &MockRouter{
shutdownFunc: func(ctx context.Context) error {
time.Sleep(100 * time.Millisecond)
return nil
},
}
sigChan := make(chan os.Signal, 1)
go func() {
sigChan <- syscall.SIGTERM
}()
return router, sigChan
},
expectedError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockRouter, sigChan := tt.setupMock()
done := make(chan bool)
go func() {
defer close(done)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if tt.signalActions != nil {
tt.signalActions(sigChan)
}
var err error
select {
case <-sigChan:
err = mockRouter.Shutdown(ctx)
case <-ctx.Done():
err = ctx.Err()
}
if tt.expectedError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
}()
select {
case <-done:
case <-time.After(6 * time.Second):
t.Fatal("Test timed out")
}
})
}
}
type MockRouter struct {
shutdownFunc func(context.Context) error
}
func (m *MockRouter) Shutdown(ctx context.Context) error {
if m.shutdownFunc != nil {
return m.shutdownFunc(ctx)
}
return nil
}
type safeCounter struct {
count int
mu sync.Mutex
}
func (c *safeCounter) increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func (c *safeCounter) getCount() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
func (c *safeCounter) reset() {
c.mu.Lock()
defer c.mu.Unlock()
c.count = 0
}
var counter = &safeCounter{}
func mockHandler() {
counter.increment()
}
func resetExecutionCount() {
counter.reset()
}
func TestRunCron(t *testing.T) {
tests := []struct {
name string
schedule string
wait time.Duration
want int
}{
{
name: "Basic Functionality: Cron Job Setup",
schedule: "@every 500ms",
wait: 1200 * time.Millisecond,
want: 2,
},
{
name: "Basic Functionality: Cron Job Execution",
schedule: "@every 250ms",
wait: 1500 * time.Millisecond,
want: 2,
},
{
name: "Edge Case: Immediate Execution",
schedule: "@every 1ms",
wait: 200 * time.Millisecond,
want: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resetExecutionCount()
c := cron.New()
started := make(chan bool, 1)
var mu sync.Mutex
firstExecution := true
err := c.AddFunc(tt.schedule, func() {
counter.increment()
mu.Lock()
if firstExecution {
firstExecution = false
mu.Unlock()
started <- true
} else {
mu.Unlock()
}
})
if err != nil {
t.Fatalf("Failed to add cron job: %v", err)
}
c.Start()
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("Cron job failed to start within timeout")
}
time.Sleep(tt.wait)
c.Stop()
execCount := counter.getCount()
t.Logf("Schedule: %s, Wait: %v, Executions: %d", tt.schedule, tt.wait, execCount)
if execCount < tt.want {
time.Sleep(500 * time.Millisecond)
execCount = counter.getCount()
}
assert.GreaterOrEqual(t, execCount, tt.want,
"Expected at least %d executions, got %d", tt.want, execCount)
})
}
}
func TestCronStopAndRestart(t *testing.T) {
resetExecutionCount()
c := cron.New()
started := make(chan bool, 1)
executed := make(chan bool, 1)
firstExecution := true
err := c.AddFunc("@every 100ms", func() {
counter.increment()
if firstExecution {
firstExecution = false
started <- true
}
executed <- true
})
if err != nil {
t.Fatalf("Failed to add cron job: %v", err)
}
c.Start()
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("Cron job failed to start within timeout")
}
select {
case <-executed:
case <-time.After(2 * time.Second):
t.Fatal("Cron job failed to execute within timeout")
}
c.Stop()
initialCount := counter.getCount()
t.Logf("Initial count after first run: %d", initialCount)
assert.Greater(t, initialCount, 0, "Should have at least one execution before stopping")
counter.reset()
firstExecution = true
c.Start()
select {
case <-executed:
case <-time.After(2 * time.Second):
t.Fatal("Cron job failed to execute after restart within timeout")
}
finalCount := counter.getCount()
t.Logf("Final count after restart: %d (initial: %d)", finalCount, initialCount)
assert.Greater(t, finalCount, 0,
"Cron should execute after restarting (initial: %d, final: %d)",
initialCount, finalCount)
}
func TestMultipleCronJobs(t *testing.T) {
resetExecutionCount()
c := cron.New()
var job1Count, job2Count int
var mu sync.Mutex
done := make(chan bool)
err := c.AddFunc("*/1 * * * * *", func() {
mu.Lock()
job1Count++
mu.Unlock()
})
if err != nil {
t.Fatalf("Failed to add first job: %v", err)
}
err = c.AddFunc("*/5 * * * * *", func() {
mu.Lock()
job2Count++
mu.Unlock()
})
if err != nil {
t.Fatalf("Failed to add second job: %v", err)
}
c.Start()
go func() {
time.Sleep(5 * time.Second)
c.Stop()
done <- true
}()
<-done
mu.Lock()
j1Count := job1Count
j2Count := job2Count
mu.Unlock()
t.Logf("Job1 executions: %d, Job2 executions: %d", j1Count, j2Count)
if j1Count == 0 {
t.Error("First job did not execute")
}
if j2Count == 0 {
t.Error("Second job did not execute")
}
if j1Count <= j2Count {
t.Errorf("Expected job1 (%d) to execute more times than job2 (%d)",
j1Count, j2Count)
}
}
func TestInvalidCronExpression(t *testing.T) {
c := cron.New()
err := c.AddFunc("invalid cron expression", mockHandler)
assert.Error(t, err, "Should return error for invalid cron expression")
}
func TestCronWithContext(t *testing.T) {
resetExecutionCount()
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
c := cron.New()
c.AddFunc("@every 50ms", mockHandler)
go func() {
c.Start()
<-ctx.Done()
c.Stop()
}()
time.Sleep(300 * time.Millisecond)
initialCount := counter.getCount()
time.Sleep(100 * time.Millisecond)
assert.Equal(t, initialCount, counter.getCount(), "Cron should stop after context cancellation")
}