-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueuerJob_test.go
More file actions
978 lines (792 loc) · 38.9 KB
/
queuerJob_test.go
File metadata and controls
978 lines (792 loc) · 38.9 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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
package queuer
import (
"context"
"fmt"
"log"
"strconv"
"testing"
"time"
"github.com/google/uuid"
"github.com/siherrmann/queuer/helper"
"github.com/siherrmann/queuer/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Short running example task function
func TaskMock(duration int, param2 string) (int, error) {
// Simulate some work
time.Sleep(time.Duration(duration) * time.Second)
// Example for some error handling
param2Int, err := strconv.Atoi(param2)
if err != nil {
return 0, err
}
return duration + param2Int, nil
}
type MockFailer struct {
count int
}
func (m *MockFailer) TaskMockFailing(duration int, maxFailCount string) (int, error) {
m.count++
// Simulate some work
time.Sleep(time.Duration(duration) * time.Second)
// Example for some error handling
maxFailCountInt, err := strconv.Atoi(maxFailCount)
if err != nil {
return 0, err
}
if m.count < maxFailCountInt {
return 0, fmt.Errorf("fake fail max count reached: %d", maxFailCountInt)
}
return duration + maxFailCountInt, nil
}
func TestAddJob(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
log.Println("Starting test queuer without worker")
testQueuer.StartWithoutWorker(ctx, cancel, false)
log.Println("Adding task to test queuer")
t.Run("Successfully adds a job with nil options", func(t *testing.T) {
expectedJob := &model.Job{
TaskName: "github.com/siherrmann/queuer.TaskMock",
Parameters: model.Parameters{1.0, "2"},
}
params := []interface{}{1, "2"}
job, err := testQueuer.AddJob(TaskMock, nil, params...)
log.Printf("Job added 1: %v", job)
assert.NoError(t, err, "AddJob should not return an error on success")
assert.Equal(t, expectedJob.TaskName, job.TaskName, "AddJob should return the correct task name")
assert.EqualValues(t, expectedJob.Parameters, job.Parameters, "AddJob should return the correct parameters")
assert.Equal(t, expectedJob.Options, job.Options, "AddJob should return the correct options")
})
t.Run("Returns error for nil function", func(t *testing.T) {
var nilTask func() // Invalid nil function
job, err := testQueuer.AddJob(nilTask, nil, "param1")
log.Printf("Job added 2: %v", job)
assert.Error(t, err, "AddJob should return an error for nil task (via addJobFn)")
assert.Nil(t, job, "Job should be nil for nil task")
assert.Contains(t, err.Error(), "task value must not be nil", "Error message should reflect nil task handling")
})
t.Run("Returns error for invalid task type", func(t *testing.T) {
invalidTask := 123 // Invalid integer type instead of a function
job, err := testQueuer.AddJob(invalidTask, nil, "param1")
log.Printf("Job added 3: %v", job)
assert.Error(t, err, "AddJob should return an error for invalid task type")
assert.Nil(t, job, "Job should be nil for invalid task type")
assert.Contains(t, err.Error(), "task must be a function, got int", "Error message should reflect invalid task type handling")
})
testQueuer.Stop()
}
func TestAddJobRunning(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully runs a job without options", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
queuedJob, err := testQueuer.GetJob(job.RID)
assert.NoError(t, err, "GetJob should not return an error")
assert.NotNil(t, queuedJob, "GetJob should return the job that is currently running")
job = testQueuer.WaitForJobFinished(job.RID, 5*time.Second)
assert.NotNil(t, job, "WaitForJobFinished should return the finished job")
assert.Equal(t, model.JobStatusSucceeded, job.Status, "WaitForJobFinished should return job with status Succeeded")
jobNotExisting, err := testQueuer.GetJob(job.RID)
assert.Error(t, err, "GetJob should return an error for ended job")
assert.Nil(t, jobNotExisting, "GetJob should return nil for ended job")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
assert.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, jobArchived.Status, model.JobStatusSucceeded, "Archived job should have status Succeeded")
})
t.Run("Successfully runs a job with schedule options once", func(t *testing.T) {
options := &model.Options{
Schedule: &model.Schedule{
Start: time.Now().Add(2 * time.Second),
MaxCount: 1,
Interval: 15 * time.Second,
},
}
job, err := testQueuer.AddJobWithOptions(options, TaskMock, nil, 1, "2")
require.NoError(t, err, "AddJob should not return an error on success")
queuedJob, err := testQueuer.GetJob(job.RID)
require.NoError(t, err, "GetJob should not return an error")
require.NotNil(t, queuedJob, "GetJob should return the scheduled job")
assert.Equal(t, model.JobStatusScheduled, queuedJob.Status, "Job should be in Scheduled status")
job = testQueuer.WaitForJobFinished(job.RID, 5*time.Second)
assert.NotNil(t, job, "WaitForJobFinished should return the finished job")
assert.Equal(t, model.JobStatusSucceeded, job.Status, "WaitForJobFinished should return job with status Succeeded")
// Check if the job is archived
jobNotExisting, err := testQueuer.GetJob(job.RID)
assert.Error(t, err, "GetJob should return an error for ended job")
assert.Nil(t, jobNotExisting, "GetJob should return nil for ended job")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
require.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, jobArchived.Status, model.JobStatusSucceeded, "Archived job should have status Succeeded")
})
t.Run("Successfully runs a job with schedule options multiple times", func(t *testing.T) {
options := &model.Options{
Schedule: &model.Schedule{
Start: time.Now().Add(1 * time.Second),
MaxCount: 2,
Interval: 3 * time.Second,
},
}
job, err := testQueuer.AddJobWithOptions(options, TaskMock, nil, 1, "2")
require.NoError(t, err, "AddJob should not return an error on success")
require.NotNil(t, job, "GetJob should return the job that is currently running")
assert.Equal(t, model.JobStatusScheduled, job.Status, "Job should be in Scheduled status")
job = testQueuer.WaitForJobFinished(job.RID, 5*time.Second)
assert.NotNil(t, job, "WaitForJobFinished should return the finished job")
assert.Equal(t, model.JobStatusSucceeded, job.Status, "WaitForJobFinished should return job with status Succeeded")
// Check if the job is archived
jobNotExisting, err := testQueuer.GetJob(job.RID)
assert.Error(t, err, "GetJob should return an error for ended job")
assert.Nil(t, jobNotExisting, "GetJob should return nil for ended job")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
require.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, jobArchived.Status, model.JobStatusSucceeded, "Archived job should have status Succeeded")
assert.Equal(t, 1, jobArchived.ScheduleCount, "Archived job should have ScheduleCount of 1")
})
testQueuer.Stop()
}
func TestAddJobTx(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, true)
t.Run("Successfully adds a job with nil options in transaction", func(t *testing.T) {
expectedJob := &model.Job{
TaskName: "github.com/siherrmann/queuer.TaskMock",
Parameters: model.Parameters{1.0, "2"},
}
params := []interface{}{1, "2"}
tx, err := testQueuer.DB.Begin()
require.NoError(t, err, "Begin transaction should not return an error")
job, err := testQueuer.AddJobTx(tx, TaskMock, nil, params...)
assert.NoError(t, err, "AddJobTx should not return an error on success")
assert.Equal(t, expectedJob.TaskName, job.TaskName, "AddJobTx should return the correct task name")
assert.EqualValues(t, expectedJob.Parameters, job.Parameters, "AddJobTx should return the correct parameters")
assert.Equal(t, expectedJob.Options, job.Options, "AddJobTx should return the correct options")
err = tx.Commit()
assert.NoError(t, err, "Commit transaction should not return an error")
})
t.Run("Returns error for nil function in transaction", func(t *testing.T) {
var nilTask func() // Invalid nil function
tx, err := testQueuer.DB.Begin()
require.NoError(t, err, "Begin transaction should not return an error")
job, err := testQueuer.AddJobTx(tx, nilTask, nil, "param1")
assert.Error(t, err, "AddJobTx should return an error for nil task (via addJobFn)")
assert.Nil(t, job, "Job should be nil for nil task")
err = tx.Rollback()
assert.NoError(t, err, "Rollback transaction should not return an error")
})
t.Run("Returns error for invalid task type in transaction", func(t *testing.T) {
invalidTask := 123 // Invalid integer type instead of a function
tx, err := testQueuer.DB.Begin()
require.NoError(t, err, "Begin transaction should not return an error")
job, err := testQueuer.AddJobTx(tx, invalidTask, nil, "param1")
assert.Error(t, err, "AddJobTx should return an error for invalid task type")
assert.Nil(t, job, "Job should be nil for invalid task type")
assert.Contains(t, err.Error(), "task must be a function, got int", "Error message should reflect invalid task type handling")
err = tx.Rollback()
assert.NoError(t, err, "Rollback transaction should not return an error")
})
testQueuer.Stop()
}
func TestAddJobWithOptions(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, true)
t.Run("Successfully adds a job with options", func(t *testing.T) {
options := &model.Options{
OnError: &model.OnError{
Timeout: 5,
MaxRetries: 3,
RetryDelay: 1,
RetryBackoff: model.RETRY_BACKOFF_EXPONENTIAL,
},
Schedule: &model.Schedule{
Start: time.Now().Add(10 * time.Minute),
MaxCount: 3,
Interval: 15 * time.Minute,
},
}
expectedJob := &model.Job{
TaskName: "github.com/siherrmann/queuer.TaskMock",
Parameters: model.Parameters{1.0, "2"},
Options: options,
}
params := []interface{}{1, "2"}
job, err := testQueuer.AddJobWithOptions(options, TaskMock, nil, params...)
assert.NoError(t, err, "AddJobWithOptions should not return an error on success")
assert.Equal(t, expectedJob.TaskName, job.TaskName, "AddJobWithOptions should return the correct task name")
assert.EqualValues(t, expectedJob.Parameters, job.Parameters, "AddJobWithOptions should return the correct parameters")
assert.EqualValues(t, expectedJob.Options.OnError, job.Options.OnError, "AddJobWithOptions should return the correct OnError options")
assert.EqualExportedValues(t, expectedJob.Options.Schedule, job.Options.Schedule, "AddJobWithOptions should return the correct Schedule options")
})
t.Run("Successfully adds a job with nil options", func(t *testing.T) {
expectedJob := &model.Job{
TaskName: "github.com/siherrmann/queuer.TaskMock",
Parameters: model.Parameters{1.0, "2"},
}
params := []interface{}{1, "2"}
job, err := testQueuer.AddJobWithOptions(nil, TaskMock, nil, params...)
assert.NoError(t, err, "AddJobWithOptions should not return an error on success")
assert.Equal(t, expectedJob.TaskName, job.TaskName, "AddJobWithOptions should return the correct task name")
assert.EqualValues(t, expectedJob.Parameters, job.Parameters, "AddJobWithOptions should return the correct parameters")
})
t.Run("Return error for invalid options", func(t *testing.T) {
options := &model.Options{
OnError: &model.OnError{
Timeout: -5, // Invalid timeout
MaxRetries: 3,
RetryDelay: 1,
RetryBackoff: model.RETRY_BACKOFF_EXPONENTIAL,
},
Schedule: &model.Schedule{
Start: time.Now().Add(10 * time.Minute),
MaxCount: 3,
Interval: 15 * time.Minute,
},
}
params := []interface{}{1, "2"}
job, err := testQueuer.AddJobWithOptions(options, TaskMock, nil, params...)
assert.Error(t, err, "AddJobWithOptions should return an error for invalid options")
assert.Nil(t, job, "Job should be nil for invalid options")
})
testQueuer.Stop()
}
func TestAddJobWithOptionsRunning(t *testing.T) {
newMockFailer := &MockFailer{}
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(newMockFailer.TaskMockFailing)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully retries a job with options", func(t *testing.T) {
options := &model.Options{
OnError: &model.OnError{
Timeout: 5,
MaxRetries: 3,
RetryDelay: 1,
RetryBackoff: model.RETRY_BACKOFF_NONE,
},
}
job, err := testQueuer.AddJobWithOptions(options, newMockFailer.TaskMockFailing, nil, 1, "3")
assert.NoError(t, err, "AddJobWithOptions should not return an error on success")
time.Sleep(4 * time.Second)
jobRunning, err := testQueuer.GetJob(job.RID)
assert.NoError(t, err, "GetJob should not return an error for running job")
require.NotNil(t, jobRunning, "GetJob should return the job that is currently running")
assert.Equal(t, model.JobStatusRunning, jobRunning.Status, "Job should be in Running status")
time.Sleep(2 * time.Second)
jobNotExisting, err := testQueuer.GetJob(job.RID)
assert.Error(t, err, "GetJob should return an error for ended job")
assert.Nil(t, jobNotExisting, "GetJob should return nil for ended job")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
assert.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, model.JobStatusSucceeded, jobArchived.Status, "Archived job should have status Succeeded")
})
t.Run("Fails after max retries", func(t *testing.T) {
options := &model.Options{
OnError: &model.OnError{
Timeout: 5,
MaxRetries: 2, // Runs 3 times, first is not a retry
RetryDelay: 1,
RetryBackoff: model.RETRY_BACKOFF_NONE,
},
}
job, err := testQueuer.AddJobWithOptions(options, newMockFailer.TaskMockFailing, nil, 1, "100")
assert.NoError(t, err, "AddJobWithOptions should not return an error on success")
time.Sleep(4 * time.Second)
jobRunning, err := testQueuer.GetJob(job.RID)
assert.NoError(t, err, "GetJob should not return an error for running job")
require.NotNil(t, jobRunning, "GetJob should return the job that is currently running")
assert.Equal(t, model.JobStatusRunning, jobRunning.Status, "Job should be in Running status")
time.Sleep(2 * time.Second)
jobNotExisting, err := testQueuer.GetJob(job.RID)
assert.Error(t, err, "GetJob should return an error for ended job")
assert.Nil(t, jobNotExisting, "GetJob should return nil for ended job")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
assert.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, model.JobStatusFailed, jobArchived.Status, "Archived job should have status Failed")
})
t.Run("Does not run a job with a non-existing next interval function", func(t *testing.T) {
options := &model.Options{
Schedule: &model.Schedule{
Start: time.Now().Add(1 * time.Second),
MaxCount: 2,
NextInterval: "nonExistingFunc",
},
}
job, err := testQueuer.AddJobWithOptions(options, TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJobWithOptions should work")
assert.NotNil(t, job, "Job should be added successfully")
time.Sleep(3 * time.Second)
jobs, err := testQueuer.GetJobs(0, 10)
assert.NoError(t, err, "GetJobs should not return an error")
require.Len(t, jobs, 1, "GetJobs should return one jobs")
assert.Equal(t, model.JobStatusScheduled, jobs[0].Status, "Job should have status Scheduled due to non-existing next interval function")
})
testQueuer.Stop()
}
func TestAddJobWithScheduleOptionsRunning(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
nextIntervalFuncCalled := false
nextIntervalFunc := func(start time.Time, currentCount int) time.Time {
nextIntervalFuncCalled = true
return start.Add(time.Duration(currentCount) * time.Second)
}
testQueuer.AddNextIntervalFuncWithName(nextIntervalFunc, "nextIntervalFunc")
require.Contains(t, testQueuer.worker.AvailableNextIntervalFuncs, "nextIntervalFunc", "NextIntervalFunc should be added to worker's AvailableNextIntervalFuncs")
worker, err := testQueuer.GetWorker(testQueuer.worker.RID)
require.NoError(t, err, "GetWorker should not return an error")
require.NotNil(t, worker, "GetWorker should return the worker")
assert.Contains(t, worker.AvailableNextIntervalFuncs, "nextIntervalFunc", "Worker should have the nextIntervalFunc in AvailableNextIntervalFuncs")
options := &model.Options{
Schedule: &model.Schedule{
Start: time.Now().Add(1 * time.Second),
MaxCount: 2,
NextInterval: "nextIntervalFunc",
},
}
job, err := testQueuer.AddJobWithOptions(options, TaskMock, nil, 1, "2")
require.NoError(t, err, "AddJobWithOptions should not return an error on success")
require.NotNil(t, job, "AddJobWithOptions should return a job")
require.NotNil(t, job.Options, "Job options should not be nil")
require.NotNil(t, job.Options.Schedule, "Job schedule options should not be nil")
assert.Equal(t, "nextIntervalFunc", job.Options.Schedule.NextInterval, "Job should have the correct next interval function")
time.Sleep(500 * time.Millisecond)
secondJobFinished := make(chan struct{})
go func() {
secondJob := testQueuer.WaitForJobAdded()
assert.NotNil(t, secondJob, "WaitForJobAdded should return the second job")
log.Printf("Second job started: %v", secondJob)
secondJob = testQueuer.WaitForJobFinished(secondJob.RID, 10*time.Second)
assert.Equal(t, model.JobStatusSucceeded, secondJob.Status, "Second job should have status Succeeded")
close(secondJobFinished)
}()
job = testQueuer.WaitForJobFinished(job.RID, 10*time.Second)
assert.NotNil(t, job, "WaitForJobFinished should return the finished job")
assert.Equal(t, model.JobStatusSucceeded, job.Status, "WaitForJobFinished should return job with status Succeeded")
// Check if both jobs are archived
<-secondJobFinished
assert.Equal(t, nextIntervalFuncCalled, true, "NextIntervalFunc should be called during job execution")
jobs, err := testQueuer.GetJobs(0, 10)
log.Printf("Jobs after running: %v", jobs)
assert.NoError(t, err, "GetJobs should not return an error")
assert.Len(t, jobs, 0, "GetJobs should return no jobs")
jobsArchived, err := testQueuer.GetJobsEnded(0, 10)
log.Printf("Jobs archive after running: %v", jobs)
assert.NoError(t, err, "GetJobsEnded should not return an error")
assert.Len(t, jobsArchived, 2, "GetJobsEnded should return two archived jobs")
for _, j := range jobs {
assert.Equal(t, model.JobStatusSucceeded, j.Status, "All jobs should have status Succeeded")
}
testQueuer.Stop()
}
func TestAddJobWithOptionsTx(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, true)
t.Run("Successfully adds a job with options in transaction", func(t *testing.T) {
options := &model.Options{
OnError: &model.OnError{
Timeout: 5,
MaxRetries: 3,
RetryDelay: 1,
RetryBackoff: model.RETRY_BACKOFF_EXPONENTIAL,
},
Schedule: &model.Schedule{
Start: time.Now().Add(10 * time.Minute),
MaxCount: 3,
Interval: 15 * time.Minute,
},
}
expectedJob := &model.Job{
TaskName: "github.com/siherrmann/queuer.TaskMock",
Parameters: model.Parameters{1.0, "2"},
Options: options,
}
params := []interface{}{1, "2"}
tx, err := testQueuer.DB.Begin()
require.NoError(t, err, "Begin transaction should not return an error")
job, err := testQueuer.AddJobWithOptionsTx(tx, options, TaskMock, nil, params...)
assert.NoError(t, err, "AddJobWithOptionsTx should not return an error on success")
assert.Equal(t, expectedJob.TaskName, job.TaskName, "AddJobWithOptionsTx should return the correct task name")
assert.EqualValues(t, expectedJob.Parameters, job.Parameters, "AddJobWithOptionsTx should return the correct parameters")
assert.EqualValues(t, expectedJob.Options.OnError, job.Options.OnError, "AddJobWithOptionsTx should return the correct OnError options")
assert.EqualExportedValues(t, expectedJob.Options.Schedule, job.Options.Schedule, "AddJobWithOptionsTx should return the correct Schedule options")
err = tx.Commit()
assert.NoError(t, err, "Commit transaction should not return an error")
})
t.Run("Returns error for nil function in transaction", func(t *testing.T) {
var nilTask func() // Invalid nil function
tx, err := testQueuer.DB.Begin()
require.NoError(t, err, "Begin transaction should not return an error")
job, err := testQueuer.AddJobWithOptionsTx(tx, nil, nilTask, nil)
assert.Error(t, err, "AddJobWithOptionsTx should return an error for nil task (via addJobFn)")
assert.Nil(t, job, "Job should be nil for nil task")
assert.Contains(t, err.Error(), "task value must not be nil", "Error message should reflect nil task handling")
err = tx.Rollback()
assert.NoError(t, err, "Rollback transaction should not return an error")
})
t.Run("Returns error for invalid task type in transaction", func(t *testing.T) {
invalidTask := 123 // Invalid integer type instead of a function
tx, err := testQueuer.DB.Begin()
require.NoError(t, err, "Begin transaction should not return an error")
job, err := testQueuer.AddJobWithOptionsTx(tx, nil, invalidTask, nil, "param1")
assert.Error(t, err, "AddJobWithOptionsTx should return an error for invalid task type")
assert.Nil(t, job, "Job should be nil for invalid task type")
assert.Contains(t, err.Error(), "task must be a function, got int", "Error message should reflect invalid task type handling")
err = tx.Rollback()
assert.NoError(t, err, "Rollback transaction should not return an error")
})
testQueuer.Stop()
}
func TestAddJobs(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, true)
t.Run("Successfully adds multiple jobs with nil options", func(t *testing.T) {
batchJobs := []model.BatchJob{
{
Task: TaskMock,
Parameters: []interface{}{1, "2"},
Options: nil,
},
{
Task: TaskMock,
Parameters: []interface{}{3, "4"},
Options: nil,
},
}
err := testQueuer.AddJobs(batchJobs)
assert.NoError(t, err, "AddJobs should not return an error on success")
jobs, err := testQueuer.GetJobs(0, 10)
assert.NoError(t, err, "GetJobs should not return an error")
assert.Len(t, jobs, 2, "AddJobs should return the correct number of jobs")
})
t.Run("Returns error for invalid batch job", func(t *testing.T) {
batchJobs := []model.BatchJob{
{
Task: nil, // Invalid nil function
Parameters: []interface{}{1, "2"},
Options: nil,
},
}
err := testQueuer.AddJobs(batchJobs)
assert.Error(t, err, "AddJobs should return an error for invalid batch job")
})
testQueuer.Stop()
}
func TestWaitForJobStarted(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, false)
testEnded := make(chan struct{})
go func() {
startedJob := testQueuer.WaitForJobAdded()
assert.NotNil(t, startedJob, "WaitForJobStarted should return the started job")
close(testEnded)
}()
job, err := testQueuer.AddJob(TaskMock, nil, 2, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
assert.NotNil(t, job, "AddJob should return a valid job")
<-testEnded
testQueuer.Stop()
}
func TestWaitForJobStartedRunning(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
testEnded := make(chan struct{})
go func() {
startedJob := testQueuer.WaitForJobAdded()
assert.NotNil(t, startedJob, "WaitForJobStarted should return the started job")
runningJob, err := testQueuer.GetJob(startedJob.RID)
assert.NoError(t, err, "GetJob should not return an error for running job")
assert.NotNil(t, runningJob, "GetJob should return the job that is currently running")
assert.Equal(t, model.JobStatusQueued, startedJob.Status, "WaitForJobStarted should return job with status Running")
close(testEnded)
}()
job, err := testQueuer.AddJob(TaskMock, nil, 2, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
assert.NotNil(t, job, "AddJob should return a valid job")
<-testEnded
testQueuer.Stop()
}
func TestWaitForJobFinished(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully waits for a job to finish", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
job = testQueuer.WaitForJobFinished(job.RID, 5*time.Second)
assert.NotNil(t, job, "WaitForJobFinished should return the finished job")
assert.Equal(t, model.JobStatusSucceeded, job.Status, "WaitForJobFinished should return job with status Succeeded")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
assert.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, model.JobStatusSucceeded, jobArchived.Status, "Archived job should have status Succeeded")
})
t.Run("Successfully cancel context while waiting for job", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 10, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
go func() {
time.Sleep(500 * time.Millisecond)
cancel()
}()
job = testQueuer.WaitForJobFinished(job.RID, 5*time.Second)
assert.Nil(t, job, "WaitForJobFinished should return nil when context is cancelled")
})
testQueuer.Stop()
}
func TestCancelJob(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, true)
t.Run("Successfully cancels a queued job", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
cancelledJob, err := testQueuer.CancelJob(job.RID)
assert.NoError(t, err, "CancelJob should not return an error on success")
assert.NoError(t, err, "GetJobs should not return an error")
assert.Equal(t, job.RID, cancelledJob.RID, "CancelJob should return the correct job RID")
jobs, err := testQueuer.GetJobs(0, 10)
assert.NoError(t, err, "GetJobs should not return an error")
assert.NotContains(t, jobs, cancelledJob, "Cancelled job should not be in the job list")
})
t.Run("Returns error for non-existent job", func(t *testing.T) {
cancelledJob, err := testQueuer.CancelJob(uuid.New())
assert.Error(t, err, "CancelJob should return an error for non-existent job")
assert.Nil(t, cancelledJob, "Cancelled job should be nil for non-existent job")
})
testQueuer.Stop()
}
func TestCancelJobRunning(t *testing.T) {
// Only works with a running queuer because the worker needs to process jobs
// to be able to cancel them.
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully cancels a running job", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 3, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
queuedJob, err := testQueuer.GetJob(job.RID)
assert.NoError(t, err, "GetJob should not return an error")
assert.NotNil(t, queuedJob, "GetJob should return the job that is currently running")
time.Sleep(1 * time.Second)
cancelledJob, err := testQueuer.CancelJob(job.RID)
assert.NoError(t, err, "CancelJob should not return an error on success")
assert.Equal(t, job.RID, cancelledJob.RID, "CancelJob should return the correct job RID")
jobNotExisting, err := testQueuer.GetJob(job.RID)
assert.Error(t, err, "GetJob should return an error for cancelled job")
assert.Nil(t, jobNotExisting, "GetJob should return nil for cancelled job")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
assert.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, jobArchived.Status, model.JobStatusCancelled, "Archived job should have status Cancelled")
})
testQueuer.Stop()
}
func TestCancelAllJobsByWorkerRunning(t *testing.T) {
// Only works with a running queuer because the worker needs to process jobs
// to be able to cancel them.
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully cancels all jobs by worker RID", func(t *testing.T) {
job1, err := testQueuer.AddJob(TaskMock, nil, 10, "2")
require.NoError(t, err, "AddJob should not return an error on success")
job2, err := testQueuer.AddJob(TaskMock, nil, 10, "4")
require.NoError(t, err, "AddJob should not return an error on success")
time.Sleep(1 * time.Second)
jobs, err := testQueuer.GetJobsByWorkerRID(testQueuer.worker.RID, 0, 10)
assert.NoError(t, err, "SelectAllJobsByWorkerRID should not return an error")
require.Len(t, jobs, 2, "There should be two jobs for the worker")
assert.Equal(t, model.JobStatusRunning, jobs[0].Status, "Job1 should be in Running status")
assert.Equal(t, model.JobStatusRunning, jobs[1].Status, "Job2 should be in Running status")
err = testQueuer.CancelAllJobsByWorker(testQueuer.worker.RID, 10)
assert.NoError(t, err, "CancelAllJobsByWorker should not return an error on success")
jobs, err = testQueuer.GetJobs(0, 10)
assert.NoError(t, err, "GetJobs should not return an error")
assert.NotContains(t, jobs, job1, "Cancelled job1 should not be in the job list")
assert.NotContains(t, jobs, job2, "Cancelled job2 should not be in the job list")
jobArchived1, err := testQueuer.dbJob.SelectJobFromArchive(job1.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job1")
require.NotNil(t, jobArchived1, "SelectJobFromArchive should return the archived job1")
assert.Equal(t, jobArchived1.Status, model.JobStatusCancelled, "Archived job1 should have status Cancelled")
jobArchived2, err := testQueuer.dbJob.SelectJobFromArchive(job2.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job2")
require.NotNil(t, jobArchived2, "SelectJobFromArchive should return the archived job2")
assert.Equal(t, jobArchived2.Status, model.JobStatusCancelled, "Archived job2 should have status Cancelled")
})
testQueuer.Stop()
}
func TestReaddJobFromArchive(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.StartWithoutWorker(ctx, cancel, true)
t.Run("Successfully readds a job from archive", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
job, err = testQueuer.GetJob(job.RID)
assert.NoError(t, err, "GetJob should not return an error")
assert.NotNil(t, job, "GetJob should return the job that is currently queued")
// Cancel the job to archive it
cancelledJob, err := testQueuer.CancelJob(job.RID)
assert.NoError(t, err, "CancelJob should not return an error on success")
assert.Equal(t, job.RID, cancelledJob.RID, "CancelJob should return the correct job RID")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(cancelledJob.RID)
assert.NoError(t, err, "SelectJobFromArchive should not return an error for archived job")
assert.NotNil(t, jobArchived, "SelectJobFromArchive should return the archived job")
assert.Equal(t, model.JobStatusCancelled, jobArchived.Status, "Archived job should have status Cancelled")
readdedJob, err := testQueuer.ReaddJobFromArchive(job.RID)
assert.NoError(t, err, "ReaddJobFromArchive should not return an error on success")
assert.NotNil(t, readdedJob, "ReaddJobFromArchive should return the readded job")
// Readded job should have a new RID and status
job, err = testQueuer.GetJob(readdedJob.RID)
assert.NoError(t, err, "GetJob should not return an error")
require.NotNil(t, job, "GetJob should return the readded job")
assert.Equal(t, model.JobStatusQueued, job.Status, "Readded job should have status Queued")
assert.NotEqual(t, cancelledJob.RID, job.RID, "Readded job should have a new RID")
})
testQueuer.Stop()
}
func TestGetJobsBySearch(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully search for jobs", func(t *testing.T) {
// Add multiple jobs with different task names
job1, err := testQueuer.AddJob(TaskMock, nil, 1, "1")
assert.NoError(t, err, "AddJob should not return an error")
require.NotNil(t, job1, "Job1 should not be nil")
job2, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error")
require.NotNil(t, job2, "Job2 should not be nil")
// Search for jobs by task name
jobs, err := testQueuer.GetJobsBySearch("TaskMock", 0, 10)
assert.NoError(t, err, "GetJobsBySearch should not return an error")
assert.GreaterOrEqual(t, len(jobs), 2, "Should find at least 2 jobs matching TaskMock")
// Search for jobs by status
jobs, err = testQueuer.GetJobsBySearch("QUEUED", 0, 10)
assert.NoError(t, err, "GetJobsBySearch should not return an error")
assert.GreaterOrEqual(t, len(jobs), 0, "Should not error when searching for QUEUED status")
})
t.Run("Returns empty result for non-matching search", func(t *testing.T) {
jobs, err := testQueuer.GetJobsBySearch("NonExistentTask", 0, 10)
assert.NoError(t, err, "GetJobsBySearch should not return an error")
if jobs != nil {
assert.Len(t, jobs, 0, "Should return empty slice for non-matching search")
}
})
testQueuer.Stop()
}
func TestGetJobsEndedBySearch(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully search for ended jobs", func(t *testing.T) {
// Add jobs and wait for them to finish
job1, err := testQueuer.AddJob(TaskMock, nil, 1, "1")
assert.NoError(t, err, "AddJob should not return an error")
require.NotNil(t, job1, "Job1 should not be nil")
job2, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error")
require.NotNil(t, job2, "Job2 should not be nil")
// Wait for jobs to finish
finishedJob1 := testQueuer.WaitForJobFinished(job1.RID, 30*time.Second)
require.NotNil(t, finishedJob1, "Job1 should finish within timeout")
assert.Contains(t, []string{model.JobStatusSucceeded, model.JobStatusFailed}, finishedJob1.Status, "Job1 should have finished")
finishedJob2 := testQueuer.WaitForJobFinished(job2.RID, 30*time.Second)
require.NotNil(t, finishedJob2, "Job2 should finish within timeout")
assert.Contains(t, []string{model.JobStatusSucceeded, model.JobStatusFailed}, finishedJob2.Status, "Job2 should have finished")
// Search for ended jobs by task name
jobs, err := testQueuer.GetJobsEndedBySearch("TaskMock", 0, 10)
assert.NoError(t, err, "GetJobsEndedBySearch should not return an error")
assert.GreaterOrEqual(t, len(jobs), 2, "Should find at least 2 ended jobs matching TaskMock")
// Search for ended jobs by status - just verify no error
_, err = testQueuer.GetJobsEndedBySearch("SUCCEEDED", 0, 10)
assert.NoError(t, err, "GetJobsEndedBySearch should not return an error when searching by status")
})
t.Run("Returns empty result for non-matching search in archive", func(t *testing.T) {
jobs, err := testQueuer.GetJobsEndedBySearch("NonExistentEndedTask", 0, 10)
assert.NoError(t, err, "GetJobsEndedBySearch should not return an error")
if jobs != nil {
assert.Len(t, jobs, 0, "Should return empty slice for non-matching search")
}
})
testQueuer.Stop()
}
func TestDeleteJob(t *testing.T) {
helper.SetTestDatabaseConfigEnvs(t, dbPort)
testQueuer := NewQueuer("TestQueuer", 100)
testQueuer.AddTask(TaskMock)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testQueuer.Start(ctx, cancel)
t.Run("Successfully deletes a job", func(t *testing.T) {
job, err := testQueuer.AddJob(TaskMock, nil, 1, "2")
assert.NoError(t, err, "AddJob should not return an error on success")
job = testQueuer.WaitForJobFinished(job.RID, 5*time.Second)
assert.NotNil(t, job, "WaitForJobFinished should return the finished job")
assert.Equal(t, model.JobStatusSucceeded, job.Status, "WaitForJobFinished should return job with status Succeeded")
err = testQueuer.DeleteJob(job.RID)
assert.NoError(t, err, "DeleteJob should not return an error on success")
jobArchived, err := testQueuer.dbJob.SelectJobFromArchive(job.RID)
assert.Error(t, err, "SelectJobFromArchive should return an error for deleted job")
assert.Nil(t, jobArchived, "SelectJobFromArchive should return nil for deleted job")
})
testQueuer.Stop()
}