1
- from tornado .testing import AsyncHTTPTestCase , gen_test
2
- from tornado .web import Application
3
- from tornado .websocket import WebSocketHandler , websocket_connect
1
+ from tornado .httpclient import HTTPError
2
+ from tornado .log import gen_log
3
+ from tornado .testing import AsyncHTTPTestCase , gen_test , bind_unused_port , ExpectLog
4
+ from tornado .web import Application , RequestHandler
5
+ from tornado .websocket import WebSocketHandler , websocket_connect , WebSocketError
4
6
5
7
6
8
class EchoHandler (WebSocketHandler ):
7
9
def on_message (self , message ):
8
10
self .write_message (message , isinstance (message , bytes ))
9
11
12
+ class NonWebSocketHandler (RequestHandler ):
13
+ def get (self ):
14
+ self .write ('ok' )
15
+
10
16
11
17
class WebSocketTest (AsyncHTTPTestCase ):
12
18
def get_app (self ):
13
19
return Application ([
14
20
('/echo' , EchoHandler ),
21
+ ('/non_ws' , NonWebSocketHandler ),
15
22
])
16
23
17
24
@gen_test
@@ -32,14 +39,30 @@ def test_websocket_callbacks(self):
32
39
ws .read_message (self .stop )
33
40
response = self .wait ().result ()
34
41
self .assertEqual (response , 'hello' )
35
-
42
+
36
43
@gen_test
37
- def test_websocket_fail (self ):
38
- try :
39
- ws = yield websocket_connect (
40
- 'ws://localhost:%d/no_websock ' % self .get_http_port (),
44
+ def test_websocket_http_fail (self ):
45
+ with self . assertRaises ( HTTPError ) as cm :
46
+ yield websocket_connect (
47
+ 'ws://localhost:%d/notfound ' % self .get_http_port (),
41
48
io_loop = self .io_loop )
42
- except :
43
- pass
44
- else :
45
- self .fail ('Should\' ve caught an Exception' )
49
+ self .assertEqual (cm .exception .code , 404 )
50
+
51
+ @gen_test
52
+ def test_websocket_http_success (self ):
53
+ with self .assertRaises (WebSocketError ):
54
+ yield websocket_connect (
55
+ 'ws://localhost:%d/non_ws' % self .get_http_port (),
56
+ io_loop = self .io_loop )
57
+
58
+ @gen_test
59
+ def test_websocket_network_fail (self ):
60
+ sock , port = bind_unused_port ()
61
+ sock .close ()
62
+ with self .assertRaises (HTTPError ) as cm :
63
+ with ExpectLog (gen_log , ".*" ):
64
+ yield websocket_connect (
65
+ 'ws://localhost:%d/' % port ,
66
+ io_loop = self .io_loop ,
67
+ connect_timeout = 0.01 )
68
+ self .assertEqual (cm .exception .code , 599 )
0 commit comments