-
Notifications
You must be signed in to change notification settings - Fork 5
/
channel_test.go
102 lines (84 loc) · 2.53 KB
/
channel_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
package websocket
import (
"context"
"encoding/json"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/stretchr/testify/require"
"net/url"
"strings"
"testing"
"time"
)
func TestChannel_Add(t *testing.T) {
ts, wsServer, shutdown := server(t)
defer shutdown()
ch := wsServer.NewChannel("test-channel-add")
wsServer.OnConnect(func(c *Conn) {
ch.Add(c)
require.Equal(t, 1, ch.Count(), "channel must contain only 1 connection")
})
u := url.URL{Scheme: "ws", Host: strings.Replace(ts.URL, "http://", "", 1), Path: "/ws"}
c, _, _, err := ws.Dial(context.Background(), u.String())
require.NoError(t, err)
defer func() {
require.NoError(t, c.Close())
}()
}
func TestChannel_Emit(t *testing.T) {
ts, wsServer, shutdown := server(t)
defer shutdown()
ch := wsServer.NewChannel("test-channel-emit")
_message := Message{
Name: "test-channel-emit",
Data: []byte("message"),
}
messageBytes, err := json.Marshal(_message)
require.NoError(t, err)
wsServer.OnConnect(func(c *Conn) {
ch.Add(c)
time.Sleep(300 * time.Millisecond)
ch.Emit(_message.Name, _message.Data)
})
u := url.URL{Scheme: "ws", Host: strings.Replace(ts.URL, "http://", "", 1), Path: "/ws"}
c, _, _, err := ws.Dial(context.Background(), u.String())
require.NoError(t, err)
err = c.SetDeadline(time.Now().Add(3000 * time.Millisecond))
require.NoError(t, err)
defer func() {
require.NoError(t, c.Close())
}()
for {
mes, op, err := wsutil.ReadServerData(c)
require.NoError(t, err)
require.Equal(t, true, op.IsData())
require.Equal(t, messageBytes, mes, "response and request must be the same")
var msg Message
require.NoError(t, json.Unmarshal(mes, &msg))
require.Equal(t, _message, msg, "response message must be the same as send")
break
}
}
func TestChannel_Remove(t *testing.T) {
ts, wsServer, shutdown := server(t)
defer shutdown()
ch := wsServer.NewChannel("test-channel-add")
wsServer.OnConnect(func(c *Conn) {
ch.Add(c)
require.Equal(t, 1, ch.Count(), "channel must contain only 1 connection")
ch.Remove(c)
require.Equal(t, 0, ch.Count(), "channel must contain only 1 connection")
})
u := url.URL{Scheme: "ws", Host: strings.Replace(ts.URL, "http://", "", 1), Path: "/ws"}
c, _, _, err := ws.Dial(context.Background(), u.String())
require.NoError(t, err)
defer func() {
require.NoError(t, c.Close())
}()
}
func TestChannel_Id(t *testing.T) {
_, wsServer, shutdown := server(t)
defer shutdown()
ch := wsServer.NewChannel("test-channel-id")
require.Equal(t, "test-channel-id", ch.ID(), "channel must have same id")
}