Tornado Testing

Tornado testing can get complex. Below is a simple snippet for testing a POST request that accesses a suppliedĀ argument. Took me ages to figure out the arguments needed to be urlencoded. Hope this saves you some time when testing your Tornado code.

from tornado import ioloop
from tornado.testing import AsyncHTTPTestCase
from tornado.web import Application, RequestHandler
import urllib


class MainHandler(RequestHandler):
    def get(self):
        self.write("Hello, world")

    def post(self):
        name = self.get_argument('name')
        self.write("Hello, {0}".format(name))


class TestHelloWorld(AsyncHTTPTestCase):

    def get_app(self):
        return Application([(r"/", MainHandler)])

    def test_hello_world(self):
        # add any useful header stuff here
        headers = {}

        data = {'name':'Tony'}
        body = urllib.urlencode(data)

        self.http_client.fetch(
            self.get_url('/'),
            self.stop,
            method="POST",
            body=body,
            headers=headers
        )
        response = self.wait()
        self.assertEquals(response.body, 'Hello, Tony')


if __name__ == "__main__":
    application = Application([
        (r"/", MainHandler),
    ])
    application.listen(8888)
    ioloop.IOLoop.instance().start()