-
Notifications
You must be signed in to change notification settings - Fork 0
/
broker_test.go
122 lines (102 loc) · 2.37 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package gotelem
import (
"log/slog"
"os"
"sync"
"testing"
"time"
"github.com/kschamplin/gotelem/skylab"
)
func makeEvent() skylab.BusEvent {
var pkt skylab.Packet = &skylab.BmsMeasurement{
BatteryVoltage: 12000,
AuxVoltage: 24000,
Current: 1.23,
}
return skylab.BusEvent{
Timestamp: time.Now(),
Name: pkt.String(),
Data: pkt,
}
}
func TestBroker(t *testing.T) {
t.Parallel()
t.Run("test send", func(t *testing.T) {
flog := slog.New(slog.NewTextHandler(os.Stderr, nil))
broker := NewBroker(10, flog)
sub, err := broker.Subscribe("testSub")
if err != nil {
t.Fatalf("error subscribing: %v", err)
}
testEvent := makeEvent()
go func() {
time.Sleep(time.Millisecond * 1)
broker.Publish("other", testEvent)
}()
var recvEvent skylab.BusEvent
select {
case recvEvent = <-sub:
if !testEvent.Equals(&recvEvent) {
t.Fatalf("events not equal, want %v got %v", testEvent, recvEvent)
}
case <-time.After(1 * time.Second):
t.Fatalf("timeout waiting for packet")
}
})
t.Run("multiple broadcast", func(t *testing.T) {
flog := slog.New(slog.NewTextHandler(os.Stderr, nil))
broker := NewBroker(10, flog)
testEvent := makeEvent()
wg := sync.WaitGroup{}
clientFn := func(name string) {
sub, err := broker.Subscribe(name)
if err != nil {
t.Log(err)
return
}
<-sub
wg.Done()
}
wg.Add(2)
go clientFn("client1")
go clientFn("client2")
// yes this is stupid. otherwise we race.
time.Sleep(10 * time.Millisecond)
broker.Publish("sender", testEvent)
done := make(chan bool)
go func() {
wg.Wait()
done <- true
}()
select {
case <-done:
case <-time.After(1 * time.Second):
t.Fatal("timeout waiting for clients")
}
})
t.Run("name collision", func(t *testing.T) {
flog := slog.New(slog.NewTextHandler(os.Stderr, nil))
broker := NewBroker(10, flog)
_, err := broker.Subscribe("collide")
if err != nil {
t.Fatal(err)
}
_, err = broker.Subscribe("collide")
if err == nil {
t.Fatal("expected error, got nil")
}
})
t.Run("unsubscribe", func(t *testing.T) {
flog := slog.New(slog.NewTextHandler(os.Stderr, nil))
broker := NewBroker(10, flog)
ch, err := broker.Subscribe("test")
if err != nil {
t.Fatal(err)
}
broker.Unsubscribe("test")
_, ok := <-ch
if ok {
t.Fatal("expected dead channel, but channel returned result")
}
})
}