Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use tornado.testing for creating WebSocket unit tests?

I'm working on a project that works with tornado's websocket functionality. I see a decent amount of documentation for working with asychronous code, but nothing on how this can be used to create unit tests that work with their WebSocket implementation.

Does tornado.testing provide the functionality to do this? If so, could someone provide a brief example of how to make it happen?

Thanks in advance.

like image 703
Steve Gattuso Avatar asked Feb 17 '12 22:02

Steve Gattuso


2 Answers

As @Vladimir said, you can still use AsyncHTTPTestCase to create/manage the test webserver instance, but you can still test WebSockets in much the same way as you would normal HTTP requests - there's just no syntactic sugar to help you.

Tornado also has its own WebSocket client so there's no need (as far as I've seen) to use a third party client - perhaps it's a recent addition though. So try something like:

import tornado

class TestWebSockets(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        # Required override for AsyncHTTPTestCase, sets up a dummy
        # webserver for this test.
        app = tornado.web.Application([
            (r'/path/to/websocket', MyWebSocketHandler)
        ])
        return app

    @tornado.testing.gen_test
    def test_websocket(self):
        # self.get_http_port() gives us the port of the running test server.
        ws_url = "ws://localhost:" + str(self.get_http_port()) + "/path/to/websocket"
        # We need ws_url so we can feed it into our WebSocket client.
        # ws_url will read (eg) "ws://localhost:56436/path/to/websocket

        ws_client = yield tornado.websocket.websocket_connect(ws_url)

        # Now we can run a test on the WebSocket.
        ws_client.write_message("Hi, I'm sending a message to the server.")
        response = yield ws_client.read_message()
        self.assertEqual(response, "Hi client! This is a response from the server.")
        # ...etc

Hopefully that's a good starting point anyway.

like image 123
Ben Avatar answered Oct 12 '22 15:10

Ben


I've attempted to implement some unit tests on tornado.websocket.WebSocketHandler based handlers and got the following results:

First of all AsyncHTTPTestCase definitely has lack of web sockets support.

Still, one can use it at least to manage IOLoop and application stuff which is significant. Unfortunately, there is no WebSocket client provided with tornado, so here enter side-developed library.

Here is unit test on Web Sockets using Jef Balog's tornado websocket client.

like image 33
Vladimir Avatar answered Oct 12 '22 15:10

Vladimir