-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver_test.go
92 lines (82 loc) · 2.13 KB
/
server_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
package msgkit
import (
"fmt"
"net/http"
"net/url"
"sync"
"sync/atomic"
"testing"
"github.com/gorilla/websocket"
"github.com/tidwall/gjson"
)
func TestHandler(t *testing.T) {
const addr = "localhost:17892"
const connsN = 10 // number of concurrent sockets
const msgsN = 1000 // number of messages per socket
s := NewServer(nil)
// create handlers
s.Handle("h0", func(so *Socket, msg *Message) { so.Send("h0", msg.Data) })
s.Handle("h1", func(so *Socket, msg *Message) { so.Send("h1", msg.Data) })
s.Handle("h2", func(so *Socket, msg *Message) { so.Send("h2", msg.Data) })
// count the number of opens
var opened int32
s.Handle("connected", func(_ *Socket, _ *Message) { atomic.AddInt32(&opened, 1) })
// count/wait on all closes
var cwg sync.WaitGroup
cwg.Add(connsN)
s.Handle("disconnected", func(_ *Socket, _ *Message) { cwg.Done() })
srv := &http.Server{Addr: addr}
http.Handle("/ws", s)
var swg sync.WaitGroup
swg.Add(1)
go func() {
defer swg.Done()
if err := srv.ListenAndServe(); err != nil {
if err.Error() != "http: Server closed" {
panic(err)
}
}
}()
var wg sync.WaitGroup
wg.Add(connsN)
for i := 0; i < connsN; i++ {
go func(i int) {
defer wg.Done()
u := url.URL{Scheme: "ws", Host: addr, Path: "/ws"}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
panic(err)
}
defer c.Close()
// send and receive back basic messages
msgm := make(map[string]bool)
for j := 0; j < msgsN; j++ {
msg := fmt.Sprintf(`{"type":"h%d","data":"%d%d"}`, j%3, j, i)
c.WriteMessage(1, []byte(msg))
msgm[msg] = true
}
for j := 0; j < msgsN; j++ {
_, msgb, _ := c.ReadMessage()
if !msgm[string(msgb)] {
panic("bad read")
}
delete(msgm, string(msgb))
}
// send an invalid type
c.WriteMessage(1, []byte(`{"type":"invalid"}`))
_, msgb, _ := c.ReadMessage()
if gjson.GetBytes(msgb, "type").String() != "error" {
panic("expected error")
}
}(i)
}
wg.Wait()
if err := srv.Shutdown(nil); err != nil {
t.Fatal(err)
}
swg.Wait()
cwg.Wait()
if opened != connsN {
t.Fatalf("expected '%v', got '%v'", connsN, opened)
}
}