-
Notifications
You must be signed in to change notification settings - Fork 0
/
plexer_test.go
103 lines (86 loc) · 1.76 KB
/
plexer_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
package multiplex
import (
"fmt"
"strconv"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestPlexer(t *testing.T) {
var chans []chan []byte
for i := 0; i < 10; i++ {
chans = append(chans, make(chan []byte, 1000))
}
plexer := New(chConv(chans...)...)
for i := 0; i < 100; i++ {
chans[i%10] <- []byte(fmt.Sprintf("%d", i))
}
go func() {
plexer.Run()
}()
var values [][]byte
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for msg := range plexer.Out() {
values = append(values, msg)
}
}()
for i := 0; i < 10; i++ {
close(chans[i])
}
wg.Wait()
// Ensure that we read the values out in the right order
mod := 0
for i := 0; i < 100; i++ {
if i%10 == 0 && i != 0 {
mod++
}
val, err := strconv.Atoi(string(values[i]))
require.NoError(t, err)
require.True(t, val%10 == mod)
}
}
func TestPlexerCloseChan(t *testing.T) {
var chans []chan []byte
for i := 0; i < 10; i++ {
chans = append(chans, make(chan []byte, 1000))
}
plexer := New(chConv(chans...)...)
go func() {
plexer.Run()
}()
var values [][]byte
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for msg := range plexer.Out() {
values = append(values, msg)
}
}()
// Publish a message, close a channel, publish another message
time.Sleep(100 * time.Millisecond)
close(chans[1])
chans[0] <- []byte("foo")
time.Sleep(100 * time.Millisecond)
chans[2] <- []byte("bar")
for i := 0; i < 10; i++ {
if i == 1 {
continue
}
close(chans[i])
}
wg.Wait()
require.Equal(t, []byte("foo"), values[0])
require.Equal(t, []byte("bar"), values[1])
}
func chConv(channels ...chan []byte) []<-chan []byte {
ret := make([]<-chan []byte, len(channels))
for n, ch := range channels {
ret[n] = ch
}
return ret
}