-
Notifications
You must be signed in to change notification settings - Fork 2
/
subscription_test.go
93 lines (77 loc) · 1.72 KB
/
subscription_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
package main
import (
"fmt"
"sync"
"testing"
)
func TestPublishIsNonblocking(t *testing.T) {
pb := NewPubSub()
subscriber := pb.Subscribe()
defer subscriber.Close()
for i := 0; i < 100; i++ {
pb.Publish(fmt.Sprintf("hello, world! %d", i))
}
lastMessage := <-subscriber.C
if lastMessage != "hello, world! 99" {
t.Errorf("Got incorrect last message: %s", lastMessage)
}
}
func TestSubscribeAlwaysSeesFirstMessage(t *testing.T) {
// Run a publish and subscribe in parallel and verify that the message doesn't get lost
for i := 0; i < 100; i++ {
wg := sync.WaitGroup{}
wg.Add(1)
pb := NewPubSub()
go pb.Publish("hello, world!")
go func() {
s := pb.Subscribe()
defer s.Close()
msg := <-s.C
if msg != "hello, world!" {
t.Errorf("Got unexpected message: %s", msg)
}
wg.Add(-1)
}()
wg.Wait()
}
}
func TestAllSubscribersSeePublication(t *testing.T) {
pb := NewPubSub()
wg := sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
s := pb.Subscribe()
defer s.Close()
msg := <-s.C
if msg != "hello, world!" {
t.Errorf("Got unexpected message: %s", msg)
}
wg.Add(-1)
}()
}
pb.Publish("hello, world!")
wg.Wait()
}
func TestClosedSubscriberDoesNotGetPublication(t *testing.T) {
pb := NewPubSub()
s1 := pb.Subscribe()
defer s1.Close()
s2 := pb.Subscribe()
defer s2.Close()
pb.Publish("msg1")
if msg := <-s1.C; msg != "msg1" {
t.Errorf("Got unexpected message: %s", msg)
}
if msg := <-s2.C; msg != "msg1" {
t.Errorf("Got unexpected message: %s", msg)
}
s1.Close()
pb.Publish("msg2")
if msg := <-s1.C; msg != nil {
t.Errorf("Got unexpected message: %s", msg)
}
if msg := <-s2.C; msg != "msg2" {
t.Errorf("Got unexpected message: %s", msg)
}
}