-
Notifications
You must be signed in to change notification settings - Fork 0
/
broadcast_test.go
142 lines (122 loc) · 2.32 KB
/
broadcast_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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package broadcastchannel
import (
"reflect"
"sync"
"testing"
"time"
)
func TestBroadcast(t *testing.T) {
b := New[int](0)
defer b.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
// Create two subscribers.
r1 := []int{}
ch1 := make(chan int)
b.Subscribe(ch1)
go func() {
for v := range ch1 {
r1 = append(r1, v)
}
wg.Done()
}()
r2 := []int{}
ch2 := make(chan int)
b.Subscribe(ch2)
go func() {
for v := range ch2 {
r2 = append(r2, v)
}
wg.Done()
}()
// Send a value.
b.Chan() <- 1
b.Close()
wg.Wait()
if !reflect.DeepEqual(r1, []int{1}) {
t.Errorf("r1 = %v, want %v", r1, []int{1})
}
if !reflect.DeepEqual(r2, []int{1}) {
t.Errorf("r2 = %v, want %v", r2, []int{1})
}
}
func TestWithWrongReceiver(t *testing.T) {
b := New[int](0).WithTimeout(1 * time.Second)
defer b.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
// Create two subscribers.
r1 := []int{}
ch1 := make(chan int)
b.Subscribe(ch1)
go func() {
for v := range ch1 {
r1 = append(r1, v)
}
wg.Done()
}()
r2 := []int{}
ch2 := make(chan int)
b.Subscribe(ch2)
go func() {
// Here, ch2 is read only once.
r2 = append(r2, <-ch2)
wg.Done()
}()
// Send two value.
b.Chan() <- 1
b.Chan() <- 2
b.Close()
wg.Wait()
if !reflect.DeepEqual(r1, []int{1, 2}) {
t.Errorf("r1 = %v, want %v", r1, []int{1, 2})
}
if !reflect.DeepEqual(r2, []int{1}) {
t.Errorf("r2 = %v, want %v", r2, []int{1})
}
}
func TestWithClosingReceiver(t *testing.T) {
b := New[int](0)
defer b.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
// Create two subscribers.
r1 := []int{}
ch1 := make(chan int)
b.Subscribe(ch1)
go func() {
for v := range ch1 {
r1 = append(r1, v)
}
wg.Done()
}()
r2 := []int{}
ch2 := make(chan int)
b.Subscribe(ch2)
go func() {
// Here, ch2 is read only once and is closed after the read.
r2 = append(r2, <-ch2)
close(ch2)
wg.Done()
}()
// Send two value.
b.Chan() <- 1
b.Chan() <- 2
b.Close()
wg.Wait()
if !reflect.DeepEqual(r1, []int{1, 2}) {
t.Errorf("r1 = %v, want %v", r1, []int{1, 2})
}
if !reflect.DeepEqual(r2, []int{1}) {
t.Errorf("r2 = %v, want %v", r2, []int{1})
}
}
func TestCloseTwice(t *testing.T) {
b := New[int](0)
if err := b.Close(); err != nil {
t.Errorf("err = %v, want %v", err, nil)
}
if err := b.Close(); err == nil {
t.Errorf("err = %v, want non-nil error", err)
}
}