-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_test.go
More file actions
61 lines (50 loc) · 1.51 KB
/
worker_test.go
File metadata and controls
61 lines (50 loc) · 1.51 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
package workers
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewWorker(t *testing.T) {
called := false
w := NewWorker("test", func(ctx WorkerContext) error {
called = true
assert.Equal(t, "test", ctx.Name())
assert.Equal(t, 0, ctx.Attempt())
return nil
})
require.NotNil(t, w)
assert.Equal(t, "test", w.name)
assert.False(t, w.restartOnFail)
// Run it directly to verify
wctx := newWorkerContext(context.Background(), "test", 0, nil, nil, nil)
err := w.run(wctx)
assert.NoError(t, err)
assert.True(t, called)
}
func TestWorker_WithRestart(t *testing.T) {
w := NewWorker("test", func(ctx WorkerContext) error { return nil })
assert.False(t, w.restartOnFail)
w.WithRestart(true)
assert.True(t, w.restartOnFail)
}
func TestWorker_Every(t *testing.T) {
count := 0
w := NewWorker("ticker", func(ctx WorkerContext) error {
count++
return nil
}).Every(10 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 55*time.Millisecond)
defer cancel()
wctx := newWorkerContext(ctx, "ticker", 0, nil, nil, nil)
_ = w.run(wctx)
assert.GreaterOrEqual(t, count, 3, "should tick at least 3 times in 55ms with 10ms interval")
}
func TestWorkerContext(t *testing.T) {
ctx := context.WithValue(context.Background(), "key", "value")
wctx := newWorkerContext(ctx, "myworker", 3, nil, nil, nil)
assert.Equal(t, "myworker", wctx.Name())
assert.Equal(t, 3, wctx.Attempt())
assert.Equal(t, "value", wctx.Value("key"))
}