-
Notifications
You must be signed in to change notification settings - Fork 0
/
broker_test.go
99 lines (82 loc) · 2.15 KB
/
broker_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
//
package concurrency
import (
"fmt"
"github.com/difof/goul/generics/containers"
"testing"
"time"
)
func TestNewBroker(t *testing.T) {
b := NewBroker[string, string]("::")
numSubs := 20
subReceived := containers.NewMap[int, bool]()
// create and subscribe 3 clients:
subFactory := func(id int) {
sub := b.SubscribeChannel("testchannel")
for range sub.Channel() {
subReceived.Set(id, true)
}
}
for i := 0; i < numSubs; i++ {
go subFactory(i)
}
// wait for subscribers to fully subscribe!
time.Sleep(10 * time.Millisecond)
// start publishing messages:
go func() {
for msgId := 0; ; msgId++ {
b.PublishChannel("testchannel", fmt.Sprintf("msg#%d", msgId))
time.Sleep(time.Millisecond)
}
}()
// let the messages flow for a while:
time.Sleep(time.Second)
b.Close()
unhandledClients := make([]int, 0, numSubs)
handledClients := make([]int, 0, numSubs)
for i := 0; i < numSubs; i++ {
if _, ok := subReceived.GetE(i); !ok {
unhandledClients = append(unhandledClients, i)
} else {
handledClients = append(handledClients, i)
}
}
if subReceived.Len() != numSubs {
t.Logf("Expected %d clients to receive messages, but got %d", numSubs, subReceived.Len())
t.Logf("Unhandled clients: %v", unhandledClients)
t.Logf("Handled clients: %v", handledClients)
t.Fail()
}
}
func TestBroker_Unsubscribe(t *testing.T) {
b := NewBroker[string, struct{}]("::")
go b.start()
// id -> num received
receives := containers.NewMap[int, int]()
subFactory := func(id int, ch chan struct{}) {
for range ch {
receives.Set(id, receives.Get(id)+1)
}
}
numSubs := 20
subs := make([]*Subscription[string, struct{}], 0, numSubs)
for i := 0; i < numSubs; i++ {
sub := b.SubscribeChannel("testchannel")
subs = append(subs, sub)
receives.Set(i, 0)
go subFactory(i, sub.Channel())
}
b.PublishChannel("testchannel", struct{}{})
time.Sleep(time.Second)
for _, sub := range subs {
sub.Close()
}
time.Sleep(time.Second)
b.PublishChannel("testchannel", struct{}{})
for i := 0; i < numSubs; i++ {
if receives.Get(i) != 1 {
t.Logf("Expected client %d to receive 1 message, but got %d", i, receives.Get(i))
t.Fail()
}
}
}