-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjobqueue_test.go
241 lines (193 loc) · 5.51 KB
/
jobqueue_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
package jobqueue
import (
"fmt"
"os"
"testing"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/goccy/go-json"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const BadgerDBPath = "/tmp/badger"
func init() { //nolint:gochecknoinits // for testing
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
type testJob struct {
Msg string
}
func testJobHandler() func(JobContext, testJob) error {
return func(ctx JobContext, job testJob) error {
fmt.Println("Test job processed:", job.Msg, ctx.JobID(), //nolint:forbidigo // for testing
ctx.JobCreatedAt().Unix())
return nil
}
}
func TestNewJobQueue(t *testing.T) {
t.Parallel()
// Test cases
testCases := []struct {
name string
dbPath string
queueName string
workers int
options []Option[testJob]
expectedError bool
cleanupNeeded bool
}{
{
name: "Valid configuration",
dbPath: "/tmp/test_jobqueue_1",
queueName: "test-queue-1",
workers: 2,
options: []Option[testJob]{WithInmemDB[testJob]()},
expectedError: false,
},
{
name: "Invalid workers count",
dbPath: "/tmp/test_jobqueue_2",
queueName: "test-queue-2",
workers: -1,
options: []Option[testJob]{WithInmemDB[testJob]()},
expectedError: true,
},
{
name: "Zero workers",
dbPath: "/tmp/test_jobqueue_3",
queueName: "test-queue-3",
workers: 0,
options: []Option[testJob]{WithInmemDB[testJob]()},
expectedError: false,
},
}
for _, tc := range testCases {
tc := tc // capture range variable
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// Act
jq, err := New[testJob](tc.dbPath, tc.queueName, tc.workers, testJobHandler(), tc.options...)
// Assert
if tc.expectedError {
assert.Error(t, err)
assert.Nil(t, jq)
} else {
require.NoError(t, err)
require.NotNil(t, jq)
assert.NotNil(t, jq.db)
assert.NotNil(t, jq.jobID)
assert.NotNil(t, jq.isJobIDInQueue)
assert.NotNil(t, jq.jobs)
// Cleanup
err = jq.Stop()
assert.NoError(t, err)
}
})
}
}
func TestJobQueue_Enqueue(t *testing.T) {
cleanupBadgerDB(t)
jq, err := New[testJob](BadgerDBPath, "test-job", 0, testJobHandler(), WithInmemDB[testJob]())
assert.NoError(t, err)
t.Cleanup(func() {
assert.NoError(t, jq.Stop())
})
for i := 0; i < 10; i++ {
j := testJob{Msg: fmt.Sprintf("hello %d", i)}
id, err := jq.Enqueue(j)
assert.NoError(t, err)
// Verify that the job was stored in badger DB
value, err := readJob(jq.db, id)
assert.NoError(t, err)
var dbJob job[testJob]
err = json.Unmarshal(value, &dbJob)
assert.NoError(t, err)
// Verify that the job is what we're expecting
assert.Equal(t, id, dbJob.ID)
assert.Equal(t, j, dbJob.Payload)
assert.Equal(t, JobStatusPending, dbJob.Status)
assert.WithinDuration(t, time.Now(), dbJob.CreatedAt, time.Second)
}
}
func TestJobQueue_ProcessJob(t *testing.T) {
cleanupBadgerDB(t)
jq, err := New[testJob](BadgerDBPath, "test-job", 0, testJobHandler(), WithInmemDB[testJob]())
assert.NoError(t, err)
t.Cleanup(func() {
assert.NoError(t, jq.Stop())
})
// Queue a bunch of jobs
ids := make([]uint64, 0)
for i := 0; i < 10; i++ {
j := testJob{Msg: fmt.Sprintf("hello %d", i)}
id, err := jq.Enqueue(j)
assert.NoError(t, err)
ids = append(ids, id)
}
// Blocks until the job is fetched from badger
for i := 0; i < 10; i++ {
j := <-jq.jobs
// Check that the job is what we're expecting
assert.Equal(t, ids[i], j.ID)
assert.Equal(t, testJob{Msg: fmt.Sprintf("hello %d", i)}, j.Payload)
assert.Equal(t, JobStatusPending, j.Status)
assert.WithinDuration(t, time.Now(), j.CreatedAt, time.Second)
// Process the job
assert.NoError(t, jq.processJob(j))
// Check that the job is removed from the in-memory index
_, ok := jq.isJobIDInQueue.Load(ids[i])
assert.False(t, ok)
// Check that the job is no longer in the badger DB
value, err := readJob(jq.db, ids[i])
assert.Error(t, err, badger.ErrKeyNotFound)
assert.Nil(t, value)
}
}
func TestJobQueue_Recovery(t *testing.T) {
cleanupBadgerDB(t)
// Create initial job queue
jq, err := New[testJob]("/tmp/badger", "test-job", 0, testJobHandler())
assert.NoError(t, err)
t.Cleanup(func() {
cleanupBadgerDB(t)
})
// Enqueue job to initial job queue
id, err := jq.Enqueue(testJob{Msg: "hello"})
assert.NoError(t, err)
// Stop initial job queue
assert.NoError(t, jq.Stop())
// Create recovered job queue
recoveredJq, err := New[testJob]("/tmp/badger", "test-job", 0, testJobHandler())
assert.NoError(t, err)
j := <-recoveredJq.jobs
// Verify that the job is recovered correctly
assert.Equal(t, id, j.ID)
assert.Equal(t, j.Payload, testJob{Msg: "hello"})
// Process the job in recovered job queue
assert.NoError(t, recoveredJq.processJob(j))
// Stop recovered job queue
assert.NoError(t, recoveredJq.Stop())
}
func readJob(db *badger.DB, id uint64) ([]byte, error) {
return readKey(db, fmt.Sprintf("%s%d", jobDBKeyPrefix, id))
}
func readKey(db *badger.DB, key string) ([]byte, error) {
var valCopy []byte
err := db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte(key))
if err != nil {
return err
}
valCopy, err = item.ValueCopy(nil)
return err
})
if err != nil {
return nil, err
}
return valCopy, nil
}
func cleanupBadgerDB(t *testing.T) {
assert.NoError(t, os.RemoveAll(BadgerDBPath))
}