forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub_test.go
103 lines (90 loc) · 2.28 KB
/
hub_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
package centrifuge
import (
"context"
"io"
"sync"
"testing"
"github.com/centrifugal/centrifuge/internal/proto"
"github.com/stretchr/testify/assert"
)
type testTransport struct {
mu sync.Mutex
sink chan *preparedReply
closed bool
}
func newTestTransport() *testTransport {
return &testTransport{}
}
func (t *testTransport) Send(rep *preparedReply) error {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return io.EOF
}
if t.sink != nil {
t.sink <- rep
}
return nil
}
func (t *testTransport) Name() string {
return "test_transport"
}
func (t *testTransport) Encoding() Encoding {
return proto.EncodingJSON
}
func (t *testTransport) Info() TransportInfo {
return TransportInfo{}
}
func (t *testTransport) Close(disconnect *Disconnect) error {
t.mu.Lock()
defer t.mu.Unlock()
t.closed = true
return nil
}
func TestHub(t *testing.T) {
h := newHub()
c, err := newClient(context.Background(), nodeWithMemoryEngine(), newTestTransport())
assert.NoError(t, err)
c.user = "test"
h.add(c)
assert.Equal(t, len(h.users), 1)
conns := h.userConnections("test")
assert.Equal(t, 1, len(conns))
assert.Equal(t, 1, h.NumClients())
assert.Equal(t, 1, h.NumUsers())
h.remove(c)
assert.Equal(t, len(h.users), 0)
assert.Equal(t, 1, len(conns))
}
func TestHubShutdown(t *testing.T) {
h := newHub()
err := h.shutdown(context.Background())
assert.NoError(t, err)
h = newHub()
c, err := newClient(context.Background(), nodeWithMemoryEngine(), newTestTransport())
assert.NoError(t, err)
h.add(c)
err = h.shutdown(context.Background())
assert.NoError(t, err)
}
func TestHubSubscriptions(t *testing.T) {
h := newHub()
c, err := newClient(context.Background(), nodeWithMemoryEngine(), newTestTransport())
assert.NoError(t, err)
h.addSub("test1", c)
h.addSub("test2", c)
assert.Equal(t, 2, h.NumChannels())
channels := []string{}
for _, ch := range h.Channels() {
channels = append(channels, string(ch))
}
assert.True(t, stringInSlice("test1", channels))
assert.True(t, stringInSlice("test2", channels))
assert.True(t, h.NumSubscribers("test1") > 0)
assert.True(t, h.NumSubscribers("test2") > 0)
h.removeSub("test1", c)
h.removeSub("test2", c)
assert.Equal(t, h.NumChannels(), 0)
assert.False(t, h.NumSubscribers("test1") > 0)
assert.False(t, h.NumSubscribers("test2") > 0)
}