-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent_stream_test.go
More file actions
96 lines (81 loc) · 1.86 KB
/
concurrent_stream_test.go
File metadata and controls
96 lines (81 loc) · 1.86 KB
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
package cstream_test
import (
"context"
"fmt"
"sync"
"testing"
cstream "github.com/planxnx/concurrent-stream"
)
func TestStream(t *testing.T) {
ctx := context.Background()
goroutines := []int{-8, -4, -2, -1, 0, 1, 2, 4, 8}
n := []int{10, 100, 1000}
basicStream := func(t *testing.T, n int, goroutine int) {
results := make(chan int)
stream := cstream.NewStream(ctx, goroutine, results)
go func() {
for i := 0; i < n; i++ {
if !stream.IsRunning() {
t.Error("expected stream to be running")
}
if stream.IsDone() {
t.Error("expected stream to be not done")
}
i := i
stream.Go(func() int {
return factorial(i)
})
}
// Close the stream after all the tasks are submitted.
stream.Close()
if !stream.IsDone() {
t.Error("expected stream to be done after close")
}
if stream.IsRunning() {
t.Error("expected stream to be not running after close")
}
}()
i := 0
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for result := range results {
if expected := factorial(i); result != expected {
t.Errorf("expected %d, got %d", expected, result)
}
i++
}
}()
if err := stream.Wait(); err != nil {
t.Error("unexpected error:", err)
}
close(results)
if !stream.IsDone() {
t.Error("expected stream to be done after Wait() is returned")
}
if stream.IsRunning() {
t.Error("expected stream to be not running")
}
wg.Wait()
if i != n {
t.Errorf("expected %d results, got %d", n, i)
}
// Multiple calls to Close should not panic.
stream.Close()
stream.Close()
}
for _, goroutine := range goroutines {
for _, n := range n {
t.Run(fmt.Sprintf("%dgouroutines,%dn", goroutine, n), func(t *testing.T) {
basicStream(t, n, goroutine)
})
}
}
}
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}