-
Notifications
You must be signed in to change notification settings - Fork 1
/
memtask_test.go
123 lines (95 loc) · 2.13 KB
/
memtask_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
package memtask
import (
"errors"
"testing"
"time"
"github.com/matryer/is"
"golang.org/x/net/context"
)
func TestRun(t *testing.T) {
is := is.New(t)
ctx := context.Background()
now := time.Now()
m := NewManager(4 * time.Second)
id := m.Run(ctx, func(ctx context.Context, task Task) error {
time.Sleep(1 * time.Second)
task.Data = "raw data"
task.Store()
return nil
})
task, ok := m.Get(id)
is.True(ok)
is.True(task.Started.After(now))
// wait to finish
wait(m, id)
task, ok = m.Get(id)
is.True(ok)
is.Equal(task.Status, TaskStatusComplete)
is.Equal(task.Err, nil)
is.Equal(task.Data, "raw data")
is.True(task.Finished.After(task.Started))
}
func TestError(t *testing.T) {
is := is.New(t)
ctx := context.Background()
now := time.Now()
m := NewManager(4 * time.Second)
id := m.Run(ctx, func(ctx context.Context, task Task) error {
task.Data = "raw data"
task.Store()
return errors.New("some error here")
})
task, ok := m.Get(id)
is.True(ok)
is.True(task.Started.After(now))
// wait to finish
wait(m, id)
task, ok = m.Get(id)
is.True(ok)
is.Equal(task.Status, TaskStatusFailed)
is.Equal(task.Err.Error(), "some error here")
is.Equal(task.Data, "raw data")
is.True(task.Finished.After(task.Started))
}
func TestMultiRun(t *testing.T) {
is := is.New(t)
ctx := context.Background()
m := NewManager(1 * time.Second)
fn := func(ctx context.Context, task Task) error {
task.Data = task.ID
task.Store()
return nil
}
id1 := m.Run(ctx, fn)
id2 := m.Run(ctx, fn)
id3 := m.Run(ctx, fn)
tasks := m.GetAll()
is.Equal(len(tasks), 3)
is.Equal(tasks[0].Status, TaskStatusProcessing)
// wait to finish
wait(m, id1)
wait(m, id2)
wait(m, id3)
tasks = m.GetAll()
is.Equal(len(tasks), 3)
is.Equal(tasks[0].Status, TaskStatusComplete)
is.Equal(tasks[0].Err, nil)
is.Equal(tasks[0].Data, tasks[0].ID)
// wait expiration
time.Sleep(2 * time.Second)
tasks = m.GetAll()
is.Equal(len(tasks), 0)
}
// poll waiting for testing
func wait(m *Manager, taskID string) {
for {
task, ok := m.Get(taskID)
if !ok {
return
}
if task.IsFinished() {
return
}
time.Sleep(500 * time.Millisecond)
}
}