-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjobQueue_test.go
More file actions
101 lines (82 loc) · 2.08 KB
/
jobQueue_test.go
File metadata and controls
101 lines (82 loc) · 2.08 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
// SPDX-FileCopyrightText: 2024 Greenbone AG <https://greenbone.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
package jobQueue
import (
"context"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type queueTestCase struct {
test func(t *testing.T, q *JobQueue)
expectedCount int
}
func TestExecutor(t *testing.T) {
tests := map[string]queueTestCase{
"no request": {
test: func(t *testing.T, q *JobQueue) {
time.Sleep(50 * time.Millisecond)
},
expectedCount: 0,
},
"one request": {
test: func(t *testing.T, q *JobQueue) {
q.AddQueueRequest(Request{ID: "1"})
time.Sleep(50 * time.Millisecond)
},
expectedCount: 1,
},
"two requests in a row": {
test: func(t *testing.T, q *JobQueue) {
q.AddQueueRequest(Request{ID: "1"})
q.AddQueueRequest(Request{ID: "2"})
time.Sleep(50 * time.Millisecond)
},
expectedCount: 1,
},
"add several requests while the first one is working": {
test: func(t *testing.T, q *JobQueue) {
q.AddQueueRequest(Request{ID: "1"})
time.Sleep(50 * time.Millisecond)
// Request 2 to 4 are added both without any delay
q.AddQueueRequest(Request{ID: "2"})
q.AddQueueRequest(Request{ID: "3"})
q.AddQueueRequest(Request{ID: "4"})
time.Sleep(50 * time.Millisecond)
q.AddQueueRequest(Request{ID: "5"})
time.Sleep(50 * time.Millisecond)
},
expectedCount: 3,
},
}
// Here i will add several requests while the first one is working
for name := range tests {
t.Run(name, func(t *testing.T) {
mu := sync.Mutex{}
count := 0
running := false
q := NewJobQueue(jobTestFunc(t, &mu, &running, &count), context.Background())
tests[name].test(t, q)
assert.Equal(t, tests[name].expectedCount, count)
})
}
}
func jobTestFunc(t *testing.T, mu *sync.Mutex, running *bool, count *int) func() error {
return func() error {
mu.Lock()
if *running {
t.Errorf("Job is already running!")
} else {
*running = true
}
*count++
mu.Unlock()
time.Sleep(25 * time.Millisecond)
mu.Lock()
*running = false
mu.Unlock()
return nil
}
}