Test driving Tornado development

The past week I have had the pleasure to write a small web based system in python. Being a devout TDD practitioner the first step in learning python was of cause to understand the unittest module. Next thing was to see what mocking frameworks are available. To my delight I found that mockito is available for python as well (here).

The application I'm working on is a web service API to access our application using Cloud to device messaging (c2dm) from Google. To provide the web API I am using the Tornado framework.

As web frameworks goes they are usually tricky to test drive. Not so with Tornado. It ships with it's own testing framework that allows the developer to set up a round trip request/response cycle within a unit test using the tornado.testing module. Given clear module boundaries and mockito to stub out dependencies it's an easy thing to test drive Tornado web application development.

The tornado.testing module comes with a couple of very useful classes. I used AsyncHTTPTestCase to test the RequestHandler classes. To make sure that only failing tests writes to the log I also inherited LogTrapTestCase.

Below is some sample code written to allow device registration with our application server. First is the test in it's entirety and then the implementation.

The tests are in the module c2dm_registration_service_test.py:

The production code is in the module c2dm_registration_service.py:

Added to this one more class in the mondule c2dm.py. So far it is just a stub:

With this knowledge I can't find any excuses not to test drive web development in Python. It is such an easy task and takes no time at all. It is well worth the effort even when creating pilots, which most likely will end up becoming production code in the not to distant future.

  • Anonymous

    Thanks for the great code samples!  I hope you're still enjoying python.  FYI, your code would be more readable (and pythonic) if you refrained from "import *" statements, except in the rarest of cases.

    Polluting the module-level namespace is dangerous in a complex application, but hard to follow even in a simple one like this one!

  • Good that you liked it.

    Yes, I am still enjoying python. And test driving it. It's an interesting language.

    The import * is indeed sloppy and they prove a bad example. I will edit
    the article to remove them. I would actually go so far as to say it's a
    code smell.

    Thanks for pointing it out