-
Notifications
You must be signed in to change notification settings - Fork 25
/
parallel_test.go
113 lines (95 loc) · 1.83 KB
/
parallel_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
package parallel_test
import (
"fmt"
"github.com/buptmiao/parallel"
"testing"
"time"
)
/*
jobA jobB jobC
\ \ /
\ \ /
\ middle
\ /
\ /
final
*/
type middle struct {
B int
C int
}
type testResult struct {
A string
M middle
}
func testJobA() string {
return fmt.Sprintf("job")
}
func testJobB(x, y int) int {
return x + y
}
func testJobC(x int) int {
return -x
}
func TestNewParallel(t *testing.T) {
p := parallel.NewParallel()
var res testResult
p.Register(testJobA).SetReceivers(&res.A)
child := p.NewChild()
child.Register(testJobB, 1, 2).SetReceivers(&res.M.B)
child.Register(testJobC, 2).SetReceivers(&res.M.C)
p.Run()
expect := testResult{
"job",
middle{
3, -2,
},
}
if res != expect {
panic("unexpected result")
}
}
func TestParallelPanic(t *testing.T) {
p := parallel.NewParallel()
p.Register(testJobA).SetReceivers()
s := make(chan struct{}, 1)
go func() {
defer EatPanic(s)
p.Run()
}()
<-s
}
func exceptionHandler(topic string, e interface{}) {
fmt.Println(topic, e)
}
func exceptionJob() {
var a map[string]int
//assignment to entry in nil map
a["123"] = 1
}
func TestException(t *testing.T) {
p := parallel.NewParallel()
p.Register(exceptionJob)
p.Except(exceptionHandler, "topic1")
p.Run()
}
func TestTimeout(t *testing.T) {
p := parallel.NewParallel()
s := time.Now()
p.Register(time.Sleep, time.Second*5)
p.RunWithTimeOut(time.Second * 3)
elapse := time.Now().Sub(s)
if elapse > time.Second*4 || elapse < time.Second*2 {
panic("timeout is not accurate")
}
}
func TestTimeout2(t *testing.T) {
p := parallel.NewParallel()
s := time.Now()
p.Register(time.Sleep, time.Second*3)
p.RunWithTimeOut(time.Second * 5)
elapse := time.Now().Sub(s)
if elapse > time.Second*4 || elapse < time.Second*2 {
panic("timeout is not accurate")
}
}