-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscheduler_test.go
117 lines (107 loc) · 2.08 KB
/
scheduler_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
package gojob_test
import (
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"testing"
"github.com/WangYihang/gojob"
)
type safeWriter struct {
writer *strings.Builder
lock sync.Mutex
}
func newSafeWriter() *safeWriter {
return &safeWriter{
writer: new(strings.Builder),
lock: sync.Mutex{},
}
}
func (sw *safeWriter) WriteString(s string) {
sw.lock.Lock()
defer sw.lock.Unlock()
sw.writer.WriteString(s)
}
func (sw *safeWriter) String() string {
return sw.writer.String()
}
type schedulerTestTask struct {
I int
writer *safeWriter
}
func newTask(i int, writer *safeWriter) *schedulerTestTask {
return &schedulerTestTask{
I: i,
writer: writer,
}
}
func (t *schedulerTestTask) Do() error {
t.writer.WriteString(fmt.Sprintf("%d\n", t.I))
return nil
}
func TestSharding(t *testing.T) {
testcases := []struct {
numShards int64
shard int64
expected []int
}{
{
numShards: 2,
shard: 0,
expected: []int{0, 2, 4, 6, 8, 10, 12, 14},
},
{
numShards: 2,
shard: 1,
expected: []int{1, 3, 5, 7, 9, 11, 13, 15},
},
{
numShards: 3,
shard: 0,
expected: []int{0, 3, 6, 9, 12, 15},
},
{
numShards: 3,
shard: 1,
expected: []int{1, 4, 7, 10, 13},
},
{
numShards: 3,
shard: 2,
expected: []int{2, 5, 8, 11, 14},
},
}
for _, tc := range testcases {
safeWriter := newSafeWriter()
scheduler := gojob.New(
gojob.WithNumShards(tc.numShards),
gojob.WithShard(tc.shard),
gojob.WithResultFilePath("-"),
gojob.WithStatusFilePath("-"),
gojob.WithMetadataFilePath("-"),
).Start()
for i := 0; i < 16; i++ {
scheduler.Submit(newTask(i, safeWriter))
}
scheduler.Wait()
output := safeWriter.String()
lines := strings.Split(output, "\n")
numbers := []int{}
for _, line := range lines {
if line == "" {
continue
}
number, err := strconv.Atoi(line)
if err != nil {
t.Fatal(err)
}
numbers = append(numbers, number)
}
sort.Ints(numbers)
if !reflect.DeepEqual(numbers, tc.expected) {
t.Errorf("Expected %v, got %v", tc.expected, numbers)
}
}
}