forked from davidfowl/signalr-ports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestingconnection_test.go
291 lines (269 loc) · 7.92 KB
/
testingconnection_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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package signalr
import (
"bytes"
"encoding/json"
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io"
"sync"
"time"
)
type testingConnection struct {
connectionID string
srvWriter io.Writer
srvReader io.Reader
cliWriter io.Writer
cliReader io.Reader
received chan interface{}
cnMutex sync.Mutex
connected bool
cliSendChan chan string
srvSendChan chan []byte
}
var connNum = 0
func (t *testingConnection) ConnectionID() string {
if t.connectionID == "" {
connNum++
t.connectionID = fmt.Sprintf("test%v", connNum)
}
return t.connectionID
}
func (t *testingConnection) Read(b []byte) (n int, err error) {
return t.srvReader.Read(b)
}
func (t *testingConnection) Write(b []byte) (n int, err error) {
t.srvSendChan <- b
return len(b), nil
}
func (t *testingConnection) Connected() bool {
t.cnMutex.Lock()
defer t.cnMutex.Unlock()
return t.connected
}
func (t *testingConnection) SetConnected(connected bool) {
t.cnMutex.Lock()
defer t.cnMutex.Unlock()
t.connected = connected
}
func newTestingConnection() *testingConnection {
conn := newTestingConnectionBeforeHandshake()
// Send initial Handshake
conn.ClientSend(`{"protocol": "json","version": 1}`)
conn.SetConnected(true)
return conn
}
func newTestingConnectionBeforeHandshake() *testingConnection {
cliReader, srvWriter := io.Pipe()
srvReader, cliWriter := io.Pipe()
conn := testingConnection{
srvWriter: srvWriter,
srvReader: srvReader,
cliWriter: cliWriter,
cliReader: cliReader,
received: make(chan interface{}, 20),
cliSendChan: make(chan string, 20),
srvSendChan: make(chan []byte, 20),
}
// client receive loop
go receiveLoop(&conn)()
// client send loop
go func() {
for {
_, _ = conn.cliWriter.Write(append([]byte(<-conn.cliSendChan), 30))
}
}()
// server send loop
go func() {
for {
_, _ = conn.srvWriter.Write(<-conn.srvSendChan)
}
}()
return &conn
}
func (t *testingConnection) ClientSend(message string) {
t.cliSendChan <- message
}
func (t *testingConnection) ClientReceive() (string, error) {
var buf bytes.Buffer
var data = make([]byte, 1<<15) // 32K
var n int
for {
if message, err := buf.ReadString(30); err != nil {
buf.Write(data[:n])
if n, err = t.cliReader.Read(data); err == nil {
buf.Write(data[:n])
} else {
return "", err
}
} else {
return message[:len(message)-1], nil
}
}
}
func (t *testingConnection) ReceiveChan() chan interface{} {
return t.received
}
type clientReceiver interface {
ClientReceive() (string, error)
ReceiveChan() chan interface{}
SetConnected(bool)
}
func receiveLoop(conn clientReceiver) func() {
return func() {
defer GinkgoRecover()
errorHandler := func(err error) { Fail(fmt.Sprintf("received invalid message from server %v", err.Error())) }
for {
if message, err := conn.ClientReceive(); err == nil {
var hubMessage hubMessage
if err = json.Unmarshal([]byte(message), &hubMessage); err == nil {
switch hubMessage.Type {
case 1, 4:
var invocationMessage invocationMessage
if err = json.Unmarshal([]byte(message), &invocationMessage); err == nil {
conn.ReceiveChan() <- invocationMessage
} else {
errorHandler(err)
}
case 2:
var streamItemMessage streamItemMessage
if err = json.Unmarshal([]byte(message), &streamItemMessage); err == nil {
conn.ReceiveChan() <- streamItemMessage
} else {
errorHandler(err)
}
case 3:
var completionMessage completionMessage
if err = json.Unmarshal([]byte(message), &completionMessage); err == nil {
conn.ReceiveChan() <- completionMessage
} else {
errorHandler(err)
}
case 7:
var closeMessage closeMessage
if err = json.Unmarshal([]byte(message), &closeMessage); err == nil {
conn.SetConnected(false)
conn.ReceiveChan() <- closeMessage
} else {
errorHandler(err)
}
}
} else {
errorHandler(err)
}
}
}
}
}
var _ = Describe("Connection", func() {
Describe("Connection closed", func() {
Context("When the connection is closed", func() {
It("should close the connection and not answer an invocation", func() {
conn := connect(&Hub{})
conn.ClientSend(`{"type":7}`)
conn.ClientSend(`{"type":1,"invocationId": "123","target":"simple"}`)
// When the connection is closed, the server should either send a closeMessage or nothing at all
select {
case message := <-conn.received:
Expect(message.(closeMessage)).NotTo(BeNil())
case <-time.After(100 * time.Millisecond):
}
})
})
Context("When the connection is closed with an invalid close message", func() {
It("should close the connection and not should not answer an invocation", func() {
conn := connect(&Hub{})
conn.ClientSend(`{"type":7,"error":1}`)
conn.ClientSend(`{"type":1,"invocationId": "123","target":"simple"}`)
// When the connection is closed, the server should either send a closeMessage or nothing at all
select {
case message := <-conn.received:
Expect(message.(closeMessage)).NotTo(BeNil())
case <-time.After(100 * time.Millisecond):
}
})
})
})
})
var _ = Describe("Protocol", func() {
Describe("Invalid messages", func() {
Context("When a message with invalid id is sent", func() {
It("should close the connection with an error", func() {
conn := connect(&Hub{})
conn.ClientSend(`{"type":99}`)
select {
case message := <-conn.received:
Expect(message).To(BeAssignableToTypeOf(closeMessage{}))
Expect(message.(closeMessage).Error).NotTo(BeNil())
case <-time.After(100 * time.Millisecond):
Fail("timed out")
}
})
})
})
Describe("Ping", func() {
Context("When a ping is received", func() {
It("should ignore it", func() {
conn := connect(&Hub{})
conn.ClientSend(`{"type":6}`)
select {
case <-conn.received:
Fail("ping not ignored")
case <-time.After(100 * time.Millisecond):
}
})
})
})
})
var _ = Describe("Handshake", func() {
Context("When the handshake is sent as partial message to the server", func() {
It("should be connected", func() {
server, _ := NewServer(SimpleHubFactory(&invocationHub{}))
conn := newTestingConnectionBeforeHandshake()
go server.Run(conn)
conn.cliWriter.Write([]byte(`{"protocol"`))
conn.ClientSend(`: "json","version": 1}`)
conn.SetConnected(true)
conn.ClientSend(`{"type":1,"invocationId": "123","target":"simple"}`)
Expect(<-invocationQueue).To(Equal("Simple()"))
})
})
Context("When an invalid handshake is sent as partial message to the server", func() {
It("should not be connected", func() {
server, _ := NewServer(SimpleHubFactory(&invocationHub{}))
conn := newTestingConnectionBeforeHandshake()
go server.Run(conn)
conn.cliWriter.Write([]byte(`{"protocol"`))
// Opening curly brace is invalid
conn.ClientSend(`{: "json","version": 1}`)
conn.SetConnected(true)
conn.ClientSend(`{"type":1,"invocationId": "123","target":"simple"}`)
select {
case <-invocationQueue:
Fail("server connected with invalid handshake")
case <-time.After(100 * time.Millisecond):
}
})
})
Context("When a handshake is sent with an unsupported protocol", func() {
It("should return an error handshake response and be not connected", func() {
server, _ := NewServer(SimpleHubFactory(&invocationHub{}))
conn := newTestingConnectionBeforeHandshake()
go server.Run(conn)
conn.ClientSend(`{"protocol": "bson","version": 1}`)
response, err := conn.ClientReceive()
Expect(err).To(BeNil())
Expect(response).NotTo(BeNil())
jsonMap := make(map[string]interface{})
err = json.Unmarshal([]byte(response), &jsonMap)
Expect(err).To(BeNil())
Expect(jsonMap["error"]).NotTo(BeNil())
conn.ClientSend(`{"type":1,"invocationId": "123","target":"simple"}`)
select {
case <-invocationQueue:
Fail("server connected with invalid handshake")
case <-time.After(100 * time.Millisecond):
}
})
})
})