forked from rlotun/txWebSocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_websocket.py
502 lines (405 loc) · 16.5 KB
/
test_websocket.py
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# Copyright (c) 2009 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.web.websocket}.
"""
from twisted.internet.main import CONNECTION_DONE
from twisted.internet.error import ConnectionDone
from twisted.python.failure import Failure
from websocket import WebSocketHandler, WebSocketFrameDecoder
from websocket import WebSocketSite, WebSocketTransport
from twisted.web.resource import Resource
from twisted.web.server import Request, Site
from twisted.web.test.test_web import DummyChannel
from twisted.trial.unittest import TestCase
class DummyChannel(DummyChannel):
"""
A L{DummyChannel} supporting the C{setRawMode} method.
@ivar raw: C{bool} indicating if C{setRawMode} has been called.
"""
raw = False
def setRawMode(self):
self.raw = True
class TestHandler(WebSocketHandler):
"""
A L{WebSocketHandler} recording every frame received.
@ivar frames: C{list} of frames received.
@ivar lostReason: reason for connection closing.
"""
def __init__(self, request):
WebSocketHandler.__init__(self, request)
self.frames = []
self.lostReason = None
def frameReceived(self, frame):
self.frames.append(frame)
def connectionLost(self, reason):
self.lostReason = reason
class WebSocketSiteTestCase(TestCase):
"""
Tests for L{WebSocketSite}.
"""
def setUp(self):
self.site = WebSocketSite(Resource())
self.site.addHandler("/test", TestHandler)
def renderRequest(self, headers=None, url="/test", ssl=False,
queued=False, body=None):
"""
Render a request against C{self.site}, writing the WebSocket
handshake.
"""
if headers is None:
headers = [
("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost"), ("Origin", "http://localhost/")]
channel = DummyChannel()
if ssl:
channel.transport = channel.SSL()
channel.site = self.site
request = self.site.requestFactory(channel, queued)
for k, v in headers:
request.requestHeaders.addRawHeader(k, v)
request.gotLength(0)
request.requestReceived("GET", url, "HTTP/1.1")
if body:
request.channel._transferDecoder.finishCallback(body)
return channel
def test_multiplePostpath(self):
"""
A resource name can consist of several path elements.
"""
handlers = []
def handlerFactory(request):
handler = TestHandler(request)
handlers.append(handler)
return handler
self.site.addHandler("/foo/bar", handlerFactory)
channel = self.renderRequest(url="/foo/bar")
self.assertEquals(len(handlers), 1)
self.assertFalse(channel.transport.disconnected)
def test_queryArguments(self):
"""
A resource name may contain query arguments.
"""
handlers = []
def handlerFactory(request):
handler = TestHandler(request)
handlers.append(handler)
return handler
self.site.addHandler("/test?foo=bar&egg=spam", handlerFactory)
channel = self.renderRequest(url="/test?foo=bar&egg=spam")
self.assertEquals(len(handlers), 1)
self.assertFalse(channel.transport.disconnected)
def test_noOriginHeader(self):
"""
If no I{Origin} header is present, the connection is closed.
"""
channel = self.renderRequest(
headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost")])
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_multipleOriginHeaders(self):
"""
If more than one I{Origin} header is present, the connection is
dropped.
"""
channel = self.renderRequest(
headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost"), ("Origin", "foo"),
("Origin", "bar")])
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_noHostHeader(self):
"""
If no I{Host} header is present, the connection is dropped.
"""
channel = self.renderRequest(
headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Origin", "http://localhost/")])
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_multipleHostHeaders(self):
"""
If more than one I{Host} header is present, the connection is
dropped.
"""
channel = self.renderRequest(
headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Origin", "http://localhost/"), ("Host", "foo"),
("Host", "bar")])
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_missingHandler(self):
"""
If no handler is registered for the given resource, the connection is
dropped.
"""
channel = self.renderRequest(url="/foo")
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_noConnectionUpgrade(self):
"""
If the I{Connection: Upgrade} header is not present, the connection is
dropped.
"""
channel = self.renderRequest(
headers=[("Upgrade", "WebSocket"), ("Host", "localhost"),
("Origin", "http://localhost/")])
self.assertIn("404 Not Found", channel.transport.written.getvalue())
def test_noUpgradeWebSocket(self):
"""
If the I{Upgrade: WebSocket} header is not present, the connection is
dropped.
"""
channel = self.renderRequest(
headers=[("Connection", "Upgrade"), ("Host", "localhost"),
("Origin", "http://localhost/")])
self.assertIn("404 Not Found", channel.transport.written.getvalue())
def test_render(self):
"""
If the handshake is successful, we can read back the server handshake,
and the channel is setup for raw mode.
"""
channel = self.renderRequest()
self.assertTrue(channel.raw)
self.assertEquals(
channel.transport.written.getvalue(),
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"WebSocket-Origin: http://localhost/\r\n"
"WebSocket-Location: ws://localhost/test\r\n\r\n")
self.assertFalse(channel.transport.disconnected)
def test_render_handShake76(self):
"""
Test a hixie-76 handShake.
"""
# we need to construct a challenge
key1 = '1x0x0 0y00 0' # 1000000
key2 = '1b0b0 000 0' # 1000000
body = '12345678'
headers = [
("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost"), ("Origin", "http://localhost/"),
("Sec-WebSocket-Key1", key1), ("Sec-WebSocket-Key2", key2)]
channel = self.renderRequest(headers=headers, body=body)
self.assertTrue(channel.raw)
result = channel.transport.written.getvalue()
headers, response = result.split('\r\n\r\n')
self.assertEquals(
headers,
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Origin: http://localhost/\r\n"
"Sec-WebSocket-Location: ws://localhost/test")
# check challenge is correct
from hashlib import md5
import struct
self.assertEquals(md5(struct.pack('>ii8s', 500000, 500000, body)).digest(), response)
self.assertFalse(channel.transport.disconnected)
def test_secureRender(self):
"""
If the WebSocket connection is over SSL, the I{WebSocket-Location}
header specified I{wss} as scheme.
"""
channel = self.renderRequest(ssl=True)
self.assertTrue(channel.raw)
self.assertEquals(
channel.transport.written.getvalue(),
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"WebSocket-Origin: http://localhost/\r\n"
"WebSocket-Location: wss://localhost/test\r\n\r\n")
self.assertFalse(channel.transport.disconnected)
def test_frameReceived(self):
"""
C{frameReceived} is called with the received frames after handshake.
"""
handlers = []
def handlerFactory(request):
handler = TestHandler(request)
handlers.append(handler)
return handler
self.site.addHandler("/test2", handlerFactory)
channel = self.renderRequest(url="/test2")
self.assertEquals(len(handlers), 1)
handler = handlers[0]
channel._transferDecoder.dataReceived("\x00hello\xff\x00boy\xff")
self.assertEquals(handler.frames, ["hello", "boy"])
def test_websocketProtocolAccepted(self):
"""
The I{WebSocket-Protocol} header is echoed by the server if the
protocol is among the supported protocols.
"""
self.site.supportedProtocols.append("pixiedust")
channel = self.renderRequest(
headers = [
("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost"), ("Origin", "http://localhost/"),
("WebSocket-Protocol", "pixiedust")])
self.assertTrue(channel.raw)
self.assertEquals(
channel.transport.written.getvalue(),
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"WebSocket-Origin: http://localhost/\r\n"
"WebSocket-Location: ws://localhost/test\r\n"
"WebSocket-Protocol: pixiedust\r\n\r\n")
self.assertFalse(channel.transport.disconnected)
def test_tooManyWebSocketProtocol(self):
"""
If more than one I{WebSocket-Protocol} headers are specified, the
connection is dropped.
"""
self.site.supportedProtocols.append("pixiedust")
channel = self.renderRequest(
headers = [
("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost"), ("Origin", "http://localhost/"),
("WebSocket-Protocol", "pixiedust"),
("WebSocket-Protocol", "fairymagic")])
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_unsupportedProtocols(self):
"""
If the I{WebSocket-Protocol} header specified an unsupported protocol,
the connection is dropped.
"""
self.site.supportedProtocols.append("pixiedust")
channel = self.renderRequest(
headers = [
("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
("Host", "localhost"), ("Origin", "http://localhost/"),
("WebSocket-Protocol", "fairymagic")])
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_queued(self):
"""
Queued requests are unsupported, thus closed by the
C{WebSocketSite}.
"""
channel = self.renderRequest(queued=True)
self.assertFalse(channel.transport.written.getvalue())
self.assertTrue(channel.transport.disconnected)
def test_addHandlerWithoutSlash(self):
"""
C{addHandler} raises C{ValueError} if the resource name doesn't start
with a slash.
"""
self.assertRaises(
ValueError, self.site.addHandler, "test", TestHandler)
class WebSocketFrameDecoderTestCase(TestCase):
"""
Test for C{WebSocketFrameDecoder}.
"""
def setUp(self):
self.channel = DummyChannel()
request = Request(self.channel, False)
transport = WebSocketTransport(request)
handler = TestHandler(transport)
transport._attachHandler(handler)
self.decoder = WebSocketFrameDecoder(request, handler)
self.decoder.MAX_LENGTH = 100
def test_oneFrame(self):
"""
We can send one frame handled with one C{dataReceived} call.
"""
self.decoder.dataReceived("\x00frame\xff")
self.assertEquals(self.decoder.handler.frames, ["frame"])
def test_oneFrameSplitted(self):
"""
A frame can be split into several C{dataReceived} calls, and will be
combined again when sent to the C{WebSocketHandler}.
"""
self.decoder.dataReceived("\x00fra")
self.decoder.dataReceived("me\xff")
self.assertEquals(self.decoder.handler.frames, ["frame"])
def test_multipleFrames(self):
"""
Several frames can be received in a single C{dataReceived} call.
"""
self.decoder.dataReceived("\x00frame1\xff\x00frame2\xff")
self.assertEquals(self.decoder.handler.frames, ["frame1", "frame2"])
def test_missingNull(self):
"""
If a frame not starting with C{\\x00} is received, the connection is
dropped.
"""
self.decoder.dataReceived("frame\xff")
self.assertTrue(self.channel.transport.disconnected)
def test_missingNullAfterGoodFrame(self):
"""
If a frame not starting with C{\\x00} is received after a correct
frame, the connection is dropped.
"""
self.decoder.dataReceived("\x00frame\xfffoo")
self.assertTrue(self.channel.transport.disconnected)
self.assertEquals(self.decoder.handler.frames, ["frame"])
def test_emptyReceive(self):
"""
Received an empty string doesn't do anything.
"""
self.decoder.dataReceived("")
self.assertFalse(self.channel.transport.disconnected)
def test_maxLength(self):
"""
If a frame is received which is bigger than C{MAX_LENGTH}, the
connection is dropped.
"""
self.decoder.dataReceived("\x00" + "x" * 101)
self.assertTrue(self.channel.transport.disconnected)
def test_maxLengthFrameCompleted(self):
"""
If a too big frame is received in several fragments, the connection is
dropped.
"""
self.decoder.dataReceived("\x00" + "x" * 90)
self.decoder.dataReceived("x" * 11 + "\xff")
self.assertTrue(self.channel.transport.disconnected)
def test_frameLengthReset(self):
"""
The length of frames is reset between frame, thus not creating an error
when the accumulated length exceeds the maximum frame length.
"""
for i in range(15):
self.decoder.dataReceived("\x00" + "x" * 10 + "\xff")
self.assertFalse(self.channel.transport.disconnected)
class WebSocketHandlerTestCase(TestCase):
"""
Tests for L{WebSocketHandler}.
"""
def setUp(self):
self.channel = DummyChannel()
self.request = request = Request(self.channel, False)
# Simulate request handling
request.startedWriting = True
transport = WebSocketTransport(request)
self.handler = TestHandler(transport)
transport._attachHandler(self.handler)
def test_write(self):
"""
L{WebSocketTransport.write} adds the required C{\\x00} and C{\\xff}
around sent frames, and write it to the request.
"""
self.handler.transport.write("hello")
self.handler.transport.write("world")
self.assertEquals(
self.channel.transport.written.getvalue(),
"\x00hello\xff\x00world\xff")
self.assertFalse(self.channel.transport.disconnected)
def test_close(self):
"""
L{WebSocketTransport.loseConnection} closes the underlying request.
"""
self.handler.transport.loseConnection()
self.assertTrue(self.channel.transport.disconnected)
def test_connectionLost(self):
"""
L{WebSocketHandler.connectionLost} is called with the reason of the
connection closing when L{Request.connectionLost} is called.
"""
self.request.connectionLost(Failure(CONNECTION_DONE))
self.handler.lostReason.trap(ConnectionDone)