tornado.testing — Unit testing support for asynchronous code

Support classes for automated testing.

  • ExpectLog: Make test logs less spammy.

Asynchronous test cases

class tornado.testing.AsyncTestCase(methodName: str = 'runTest')[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 means that asynchronous code cannot be used in quite the same way as usual and must be adapted to fit. To write your tests with coroutines, decorate your test methods with tornado.testing.gen_test instead of tornado.gen.coroutine.

This class also provides the (deprecated) stop() and wait() methods for a more manual style of testing. 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. If the code being tested requires a global IOLoop, subclasses should override get_new_ioloop to return it.



# This test uses coroutine style.
class MyTestCase(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient()
        response = yield client.fetch("")
        # Test contents of response
        self.assertIn("FriendFeed", response.body)

# This test uses argument passing between self.stop and self.wait.
class MyTestCase2(AsyncTestCase):
    def test_http_fetch(self):
        client = AsyncHTTPClient()
        client.fetch("", self.stop)
        response = self.wait()
        # Test contents of response
        self.assertIn("FriendFeed", response.body)
get_new_ioloop() → tornado.ioloop.IOLoop[source]

Returns the IOLoop to use for this test.

By default, a new IOLoop is created for each test. Subclasses may override this method to return IOLoop.current() if it is not appropriate to use a new IOLoop in each tests (for example, if there are global singletons using the default IOLoop) or if a per-test event loop is being provided by another system (such as pytest-asyncio).

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



Deprecated since version 5.1: stop and wait are deprecated; use @gen_test instead.

wait(condition: Callable[[...], bool] = None, timeout: float = None) → None[source]

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


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

Changed in version 3.1: Added the ASYNC_TEST_TIMEOUT environment variable.


class tornado.testing.AsyncHTTPTestCase(methodName: str = 'runTest')[source]

A test case that starts up an HTTP server.


Example, assuming the “Hello, world” example from the user guide is in

import hello

class TestHelloApp(AsyncHTTPTestCase):
    def get_app(self):
        return hello.make_app()

    def test_homepage(self):
        response = self.fetch('/')
        self.assertEqual(response.code, 200)
        self.assertEqual(response.body, 'Hello, world')

That call to self.fetch() is equivalent to

self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()

which illustrates how AsyncTestCase can turn an asynchronous operation, like http_client.fetch(), into a synchronous operation. If you need to do other asynchronous operations in tests, you’ll probably need to use stop() and wait() yourself.

get_app() → tornado.web.Application[source]


fetch(path: str, raise_error: bool = False, **kwargs) → tornado.httpclient.HTTPResponse[source]

Convenience method to synchronously fetch a URL.

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

If the path begins with http:// or https://, it will be treated as a full URL and will be fetched as-is.

If raise_error is True, a tornado.httpclient.HTTPError will be raised if the response code is not 200. This is the same behavior as the raise_error argument to AsyncHTTPClient.fetch, but the default is False here (it’s True in AsyncHTTPClient) because tests often need to deal with non-200 response codes.

Changed in version 5.0: Added support for absolute URLs.

Changed in version 5.1: Added the raise_error argument.

Deprecated since version 5.1: This method currently turns any exception into an HTTPResponse with status code 599. In Tornado 6.0, errors other than tornado.httpclient.HTTPError will be passed through, and raise_error=False will only suppress errors that would be raised due to non-200 response codes.

get_httpserver_options() → Dict[str, Any][source]


get_http_port() → int[source]

Returns the port used by the server.

A new port is chosen for each test.

get_url(path: str) → str[source]


class tornado.testing.AsyncHTTPSTestCase(methodName: str = 'runTest')[source]

A test case that starts an HTTPS server.

Interface is generally the same as AsyncHTTPTestCase.

get_ssl_options() → Dict[str, Any][source]

May be overridden by subclasses to select SSL options.

By default includes a self-signed testing certificate.

tornado.testing.gen_test(func: Callable[[...], Union[, Coroutine]] = None, timeout: float = None) → Union[Callable[[...], None], Callable[[Callable[[...], Union[, Coroutine]]], Callable[[...], None]]][source]




class MyTest(AsyncHTTPTestCase):
    def test_something(self):
        response = yield self.http_client.fetch(self.get_url('/'))


class MyTest(AsyncHTTPTestCase):
    def test_something_slow(self):
        response = yield self.http_client.fetch(self.get_url('/'))

Note that @gen_test is incompatible with AsyncTestCase.stop, AsyncTestCase.wait, and AsyncHTTPTestCase.fetch. Use yield self.http_client.fetch(self.get_url()) as shown above instead.


Changed in version 4.0: The wrapper now passes along *args, **kwargs so it can be used on functions with arguments.

Controlling log output

class tornado.testing.ExpectLog(logger: Union[logging.Logger, str], regex: str, required: bool = True)[source]

Context manager to capture and suppress expected log output.


The attribute logged_stack is set to True if any exception stack trace was logged.


    error_response = self.fetch("/some_page")

Changed in version 4.3: Added the logged_stack attribute.

Constructs an ExpectLog context manager.

  • required – If true, an exception will be raised if the end of the with statement is reached without matching any log entries.

Test runner

tornado.testing.main(**kwargs) → None[source]

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. It is not necessary to use this main function to run tests using AsyncTestCase; these tests are self-contained and can run with any test runner.


python -m tornado.testing tornado.test.web_test



# Runs all tests
python -m tornado.test.runtests
# Runs one test
python -m tornado.test.runtests tornado.test.web_test


Changed in version 5.0: This function produces no output of its own; only that produced by the unittest module (previously it would add a PASS or FAIL log message).

Helper functions

tornado.testing.bind_unused_port(reuse_port: bool = False) → Tuple[socket.socket, int][source]

Binds a server socket to an available port on localhost.

Returns a tuple (socket, port).

Changed in version 4.4: Always binds to without resolving the name localhost.

tornado.testing.get_async_test_timeout() → float[source]

Get the global timeout setting for async tests.

Returns a float, the timeout in seconds.

New in version 3.1.