tornado.testing — Unit testing support for asynchronous code

Support classes for automated testing.

This module contains three parts:

  • AsyncTestCase/AsyncHTTPTestCase: Subclasses of unittest.TestCase with additional support for testing asynchronous (IOLoop-based) code.
  • LogTrapTestCase: Subclass of unittest.TestCase that discards log output from tests that pass and only produces output for failing tests.
  • main(): A simple test runner (wrapper around unittest.main()) with support for the tornado.autoreload module to rerun the tests when code changes.

These components may be used together or independently. In particular, it is safe to combine AsyncTestCase and LogTrapTestCase via multiple inheritance. See the docstrings for each class/function below for more information.

Asynchronous test cases

class tornado.testing.AsyncTestCase(*args, **kwargs)[source]

TestCase subclass for testing IOLoop-based asynchronous code.

The unittest framework is synchronous, so the test must be complete by the time the test method returns. This method provides the stop() and wait() methods for this purpose. The test method itself must call self.wait(), and asynchronous callbacks should call self.stop() to signal completion.

By default, a new IOLoop is constructed for each test and is available as self.io_loop. This IOLoop should be used in the construction of HTTP clients/servers, etc. If the code being tested requires a global IOLoop, subclasses should override get_new_ioloop to return it.

The IOLoop’s start and stop methods should not be called directly. Instead, use self.stop self.wait. Arguments passed to self.stop are returned from self.wait. It is possible to have multiple wait/stop cycles in the same test.


# This test uses an asynchronous style similar to most async
# application code.
class MyTestCase(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient(self.io_loop)
        client.fetch("", self.handle_fetch)

    def handle_fetch(self, response)
        # Test contents of response (failures and exceptions here
        # will cause self.wait() to throw an exception and end the
        # test).

# This test uses the argument passing between self.stop and self.wait
# for a simpler, more synchronous style
class MyTestCase2(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient(self.io_loop)
        client.fetch("", self.stop)
        response = self.wait()
        # Test contents of response

Creates a new IOLoop for this test. May be overridden in subclasses for tests that require a specific IOLoop (usually the singleton).

stop(_arg=None, **kwargs)[source]

Stops the ioloop, causing one pending (or future) call to wait() to return.

Keyword arguments or a single positional argument passed to stop() are saved and will be returned by wait().

wait(condition=None, timeout=5)[source]

Runs the IOLoop until stop is called or timeout has passed.

In the event of a timeout, an exception will be thrown.

If condition is not None, the IOLoop will be restarted after stop() until condition() returns true.

class tornado.testing.AsyncHTTPTestCase(*args, **kwargs)[source]

A test case that starts up an HTTP server.

Subclasses must override get_app(), which returns the tornado.web.Application (or other HTTPServer callback) to be tested. Tests will typically use the provided self.http_client to fetch URLs from this server.


class MyHTTPTest(AsyncHTTPTestCase):
    def get_app(self):
        return Application([('/', MyHandler)...])

    def test_homepage(self):
        # The following two lines are equivalent to
        #   response = self.fetch('/')
        # but are shown in full here to demonstrate explicit use
        # of self.stop and self.wait.
        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()
        # test contents of response

Should be overridden by subclasses to return a tornado.web.Application or other HTTPServer callback.

fetch(path, **kwargs)[source]

Convenience method to synchronously fetch a url.

The given path will be appended to the local server’s host and port. Any additional kwargs will be passed directly to AsyncHTTPClient.fetch (and so could be used to pass method=”POST”, body=”...”, etc).


May be overridden by subclasses to return additional keyword arguments for HTTPServer.


Returns the port used by the HTTPServer.

A new port is chosen for each test.


Returns an absolute url for the given path on the test server.

Controlling log output

class tornado.testing.LogTrapTestCase(methodName='runTest')[source]

A test case that captures and discards all logging output if the test passes.

Some libraries can produce a lot of logging output even when the test succeeds, so this class can be useful to minimize the noise. Simply use it as a base class for your test case. It is safe to combine with AsyncTestCase via multiple inheritance (“class MyTestCase(AsyncHTTPTestCase, LogTrapTestCase):”)

This class assumes that only one log handler is configured and that it is a StreamHandler. This is true for both logging.basicConfig and the “pretty logging” configured by tornado.options.

Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.

Test runner


A simple test runner.

This test runner is essentially equivalent to unittest.main from the standard library, but adds support for tornado-style option parsing and log formatting.

The easiest way to run a test is via the command line:

python -m tornado.testing tornado.test.stack_context_test

See the standard library unittest module for ways in which tests can be specified.

Projects with many tests may wish to define a test script like tornado/test/ This script should define a method all() which returns a test suite and then call tornado.testing.main(). Note that even when a test script is used, the all() test suite may be overridden by naming a single test on the command line:

# Runs all tests
# Runs one test
tornado/test/ tornado.test.stack_context_test

Helper functions


Returns a (hopefully) unused port number.