from tornado import gen
from tornado.httpclient import HTTPError, HTTPRequest
from tornado.log import gen_log, app_log
+from tornado.template import DictLoader
from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog
from tornado.test.util import unittest, skipBefore35, exec_test
from tornado.web import Application, RequestHandler
self.write_message(message)
+class RenderMessageHandler(TestWebSocketHandler):
+ def on_message(self, message):
+ self.write_message(self.render_string('message.html', message=message))
+
+
class WebSocketBaseTestCase(AsyncHTTPTestCase):
@gen.coroutine
def ws_connect(self, path, **kwargs):
dict(close_future=self.close_future)),
('/coroutine', CoroutineOnMessageHandler,
dict(close_future=self.close_future)),
- ])
+ ('/render', RenderMessageHandler,
+ dict(close_future=self.close_future)),
+ ], template_loader=DictLoader({
+ 'message.html': '<b>{{ message }}</b>',
+ }))
+
+ def tearDown(self):
+ super(WebSocketTest, self).tearDown()
+ RequestHandler._template_loaders.clear()
def test_http_request(self):
# WS server, HTTP client.
self.assertEqual(response, u'hello \u00e9')
yield self.close(ws)
+ @gen_test
+ def test_render_message(self):
+ ws = yield self.ws_connect('/render')
+ ws.write_message('hello')
+ response = yield ws.read_message()
+ self.assertEqual(response, '<b>hello</b>')
+ yield self.close(ws)
+
@gen_test
def test_error_in_on_message(self):
ws = yield self.ws_connect('/error_in_on_message')
if not self._on_close_called:
self._on_close_called = True
self.on_close()
+ self._break_cycles()
+
+ def _break_cycles(self):
+ # WebSocketHandlers call finish() early, but we don't want to
+ # break up reference cycles (which makes it impossible to call
+ # self.render_string) until after we've really closed the
+ # connection (if it was established in the first place,
+ # indicated by status code 101).
+ if self.get_status() != 101 or self._on_close_called:
+ super(WebSocketHandler, self)._break_cycles()
def send_error(self, *args, **kwargs):
if self.stream is None: