-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub_test.go
65 lines (48 loc) · 1.21 KB
/
pubsub_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
package pubsub
import (
"testing"
"time"
)
type TestPubSubSubscriber struct {
messages int
}
func (t *TestPubSubSubscriber) OnMessage(data any) {
t.messages++
}
func TestPubSub(t *testing.T) {
ps := NewPubSub()
s1 := new(TestPubSubSubscriber)
s2 := new(TestPubSubSubscriber)
s3 := new(TestPubSubSubscriber)
ps.Subscribe(s1, "first topic")
ps.Subscribe(s2, "first topic")
ps.Subscribe(s3, "second topic")
if len(ps.topics) != 2 {
t.FailNow()
}
ps.BroadcastAll("first topic", 1)
ps.BroadcastAll("first topic", 1)
if (s1.messages != 2 || s2.messages != 2) && s3.messages != 0 {
t.FailNow()
}
ps.BroadcastAll("second topic", 1)
time.Sleep(10 * time.Millisecond)
if (s1.messages != 2 || s2.messages != 2) && s3.messages != 1 {
t.FailNow()
}
ps.Broadcast(s1, "first topic", 1)
time.Sleep(10 * time.Millisecond)
if (s1.messages != 2 || s2.messages != 3) && s3.messages != 1 {
t.FailNow()
}
}
func BenchmarkPubSub(b *testing.B) {
ps := NewPubSub()
s1 := new(TestPubSubSubscriber)
s2 := new(TestPubSubSubscriber)
ps.Subscribe(s1, "topic")
ps.Subscribe(s2, "topic")
for i := 0; i < b.N; i++ {
ps.Broadcast(s1, "topic", i)
}
}