generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline_test.go
92 lines (78 loc) · 1.92 KB
/
pipeline_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
package hw06_pipeline_execution //nolint:golint,stylecheck
import (
"strconv"
"testing"
"time"
"github.com/stretchr/testify/require"
)
const (
sleepPerStage = time.Millisecond * 100
fault = sleepPerStage / 2
)
func TestPipeline(t *testing.T) {
// Stage generator
g := func(name string, f func(v I) I) Stage {
return func(in In) Out {
out := make(Bi)
go func() {
defer close(out)
for v := range in {
time.Sleep(sleepPerStage)
out <- f(v)
}
}()
return out
}
}
stages := []Stage{
g("Dummy", func(v I) I { return v }),
g("Multiplier (* 2)", func(v I) I { return v.(int) * 2 }),
g("Adder (+ 100)", func(v I) I { return v.(int) + 100 }),
g("Stringifier", func(v I) I { return strconv.Itoa(v.(int)) }),
}
t.Run("simple case", func(t *testing.T) {
in := make(Bi)
data := []int{1, 2, 3, 4, 5}
go func() {
for _, v := range data {
in <- v
}
close(in)
}()
result := make([]string, 0, 10)
start := time.Now()
for s := range ExecutePipeline(in, nil, stages...) {
result = append(result, s.(string))
}
elapsed := time.Since(start)
require.Equal(t, result, []string{"102", "104", "106", "108", "110"})
require.Less(t,
int64(elapsed),
// ~0.8s for processing 5 values in 4 stages (100ms every) concurrently
int64(sleepPerStage)*int64(len(stages)+len(data)-1)+int64(fault))
})
t.Run("done case", func(t *testing.T) {
in := make(Bi)
done := make(Bi)
data := []int{1, 2, 3, 4, 5}
// Abort after 200ms
abortDur := sleepPerStage * 2
go func() {
done <- <-time.After(abortDur)
}()
go func() {
for _, v := range data {
in <- v
}
close(in)
}()
result := make([]string, 0, 10)
start := time.Now()
for s := range ExecutePipeline(in, done, stages...) {
result = append(result, s.(string))
}
elapsed := time.Since(start)
require.Len(t, result, 0)
require.Less(t, int64(elapsed), int64(abortDur)+int64(fault))
})
}