-
Notifications
You must be signed in to change notification settings - Fork 1
/
broadcastme_test.go
114 lines (95 loc) · 2.57 KB
/
broadcastme_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
package broadcastme_test
import (
"broadcastme"
"context"
"sync"
"testing"
"time"
)
func TestBroadcastServer(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan string)
broadCastKeyTest := "key1"
broadCastVal1 := "testval1"
broadCast := broadcastme.NewBroadcast(ch, broadCastKeyTest)
broadcastServer := broadcastme.NewBroadcastServerWithContext(ctx, broadCast)
listener1 := broadcastServer.Subscribe(broadCastKeyTest, 100)
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
name := "listener1"
t.Logf("%s wait for recive...", name)
msg1 := <-listener1.Listen()
t.Logf("%s received %v", name, msg1)
if msg1 != broadCastVal1 {
t.Errorf("%s expected %v got %v", name, broadCastVal1, msg1)
}
}()
go func() {
defer wg.Done()
name := "listener2"
listener2 := broadcastServer.Subscribe(broadCastKeyTest, 100)
t.Logf("%s wait for recive...", name)
msg2 := <-listener2.Listen()
t.Logf("%s received %v", name, msg2)
if msg2 != broadCastVal1 {
t.Errorf("%s expected %v got %v", name, broadCastVal1, msg2)
}
}()
time.Sleep(time.Millisecond * 10)
t.Logf("sending %v", broadCastVal1)
ch <- broadCastVal1
go func() {
defer wg.Done()
name := "noReciver"
t.Logf("%s wait for recive...", name)
c := time.NewTicker(time.Millisecond * 20)
select {
case msg := <-listener1.Listen():
if msg != "" {
t.Errorf("%s should NOT recive anyting but got %v", name, msg)
}
case <-c.C:
}
t.Logf("%s didn't recive anyting it's ok", name)
}()
wg.Wait()
broadcastServer.Unsubscribe(listener1)
ch <- broadCastVal1
msg4 := <-listener1.Listen()
if msg4 != "" {
t.Errorf("closed channel should not get somthing but it got %v", msg4)
}
wg.Add(1)
go func() {
defer wg.Done()
name := "listener with cancled context"
listener2 := broadcastServer.Subscribe(broadCastKeyTest, 100)
tc := time.NewTicker(time.Second)
select {
case <-tc.C:
t.Errorf("%s is still listening but context is canceld", name)
case <-listener2.Listen():
}
t.Logf("%s stop listen becuse cantext has been canceled", name)
}()
cancel()
wg.Wait()
ch2 := make(chan string)
broadCastKeyTest2 := "key2"
broadCastVal2 := "testval2"
broadCast2 := broadcastme.NewBroadcast(ch2, broadCastKeyTest2)
broadcastServer.AddNewBroadcast(broadCast2)
listener := broadcastServer.Subscribe(broadCastKeyTest2, 100)
wg.Add(1)
go func() {
defer wg.Done()
newMsg := <-listener.Listen()
if newMsg != broadCastVal2 {
t.Errorf("listener expected %v got %v", broadCastVal2, newMsg)
}
}()
ch2 <- broadCastVal2
wg.Wait()
}