-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker_test.go
91 lines (72 loc) · 1.62 KB
/
worker_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
package worker_test
import (
"context"
"log"
"testing"
"github.com/vitalie/worker"
)
var c chan int = make(chan int)
// addJob represets a test job which computes the sum of the
// X and Y and sends the result through out channel.
type addJob struct {
X, Y int
out chan<- int
}
func (j *addJob) Make(args *worker.Args) (worker.Job, error) {
job := &addJob{
X: args.Get("X").MustInt(-1),
Y: args.Get("Y").MustInt(-1),
out: c,
}
return job, nil
}
func (j *addJob) Run() error {
j.out <- j.X + j.Y
return nil
}
// badJob represets an background job which panics.
type badJob struct{}
func (j *badJob) Make(args *worker.Args) (worker.Job, error) { return &badJob{}, nil }
func (j *badJob) Run() error { panic("Boom!") }
func TestPool(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
q := worker.NewMemoryQueue()
var sumtests = []struct {
x, y int
want int
}{
{0, 1, 1},
{1, 0, 1},
{2, 3, 5},
}
pool := worker.NewPool(
worker.SetQueue(q),
)
pool.Add(&addJob{})
pool.Add(&badJob{})
go pool.Run(ctx)
if err := q.Put(&badJob{}); err != nil {
t.Fatal(err)
}
for _, tt := range sumtests {
if err := q.Put(&addJob{X: tt.x, Y: tt.y}); err != nil {
t.Fatal(err)
}
if got := <-c; got != tt.want {
t.Errorf("sum(%d, %d) = %d; got %d", tt.x, tt.y, tt.want, got)
} else {
log.Printf("sum(%d, %d) = %d\n", tt.x, tt.y, got)
}
}
ready, failed, err := q.Size()
if err != nil {
t.Error(err)
}
if ready != 0 {
t.Errorf("expecting size to be %v, got %v", 0, ready)
}
if failed != 1 {
t.Errorf("expecting failed to be %v, got %v", 1, failed)
}
}