tornado.testing — Unit testing support for asynchronous code¶
Support classes for automated testing.
AsyncHTTPTestCase: Subclasses of unittest.TestCase with additional support for testing asynchronous (
ExpectLog: Make test logs less spammy.
main(): A simple test runner (wrapper around unittest.main()) with support for the tornado.autoreload module to rerun the tests when code changes.
Asynchronous test cases¶
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
This class also provides the (deprecated)
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.
stopmethods should not be called directly. Instead, use
self.wait. Arguments passed to
self.stopare returned from
self.wait. It is possible to have multiple
stopcycles in the same test.
# This test uses coroutine style. class MyTestCase(AsyncTestCase): @tornado.testing.gen_test def test_http_fetch(self): client = AsyncHTTPClient() response = yield client.fetch("http://www.tornadoweb.org") # 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("http://www.tornadoweb.org/", self.stop) response = self.wait() # Test contents of response self.assertIn("FriendFeed", response.body)
IOLoopto use for this test.
By default, a new
IOLoopis created for each test. Subclasses may override this method to return
IOLoop.current()if it is not appropriate to use a new
IOLoopin 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
IOLoopuntil stop is called or timeout has passed.
In the event of a timeout, an exception will be thrown. The default timeout is 5 seconds; it may be overridden with a
timeoutkeyword argument or globally with the
Changed in version 3.1: Added the
A test case that starts up an HTTP server.
Subclasses must override
get_app(), which returns the
HTTPServercallback) to be tested. Tests will typically use the provided
self.http_clientto fetch URLs from this 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
fetch(path, raise_error=False, **kwargs)¶
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
raise_erroris True, a
tornado.httpclient.HTTPErrorwill be raised if the response code is not 200. This is the same behavior as the
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
Deprecated since version 5.1: This method currently turns any exception into an
HTTPResponsewith status code 599. In Tornado 6.0, errors other than
tornado.httpclient.HTTPErrorwill be passed through, and
raise_error=Falsewill only suppress errors that would be raised due to non-200 response codes.
May be overridden by subclasses to return additional keyword arguments for the server.
Returns the port used by the server.
A new port is chosen for each test.
Returns an absolute url for the given path on the test server.
A test case that starts an HTTPS server.
Interface is generally the same as
May be overridden by subclasses to select SSL options.
By default includes a self-signed testing certificate.
Testing equivalent of
@gen.coroutine, to be applied to test methods.
class MyTest(AsyncHTTPTestCase): @gen_test def test_something(self): response = yield self.http_client.fetch(self.get_url('/'))
@gen_testtimes out after 5 seconds. The timeout may be overridden globally with the
ASYNC_TEST_TIMEOUTenvironment variable, or for each test with the
class MyTest(AsyncHTTPTestCase): @gen_test(timeout=10) def test_something_slow(self): response = yield self.http_client.fetch(self.get_url('/'))
New in version 3.1: The
Changed in version 4.0: The wrapper now passes along
*args, **kwargsso it can be used on functions with arguments.
Controlling log output¶
ExpectLog(logger, regex, required=True)¶
Context manager to capture and suppress expected log output.
Useful to make tests of error conditions less noisy, while still leaving unexpected log entries visible. Not thread safe.
logged_stackis set to true if any exception stack trace was logged.
with ExpectLog('tornado.application', "Uncaught exception"): error_response = self.fetch("/some_page")
Changed in version 4.3: Added the
Constructs an ExpectLog context manager.
- logger – Logger object (or name of logger) to watch. Pass an empty string to watch the root logger.
- regex – Regular expression to match. Any log entries on the specified logger that match this regex will be suppressed.
- required – If true, an exception will be raised if the end of
withstatement is reached without matching any log entries.
A simple test runner.
This test runner is essentially equivalent to
unittest.mainfrom the standard library, but adds support for tornado-style option parsing and log formatting. It is not necessary to use this
mainfunction to run tests using
AsyncTestCase; these tests are self-contained and can run with any test runner.
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/runtests.py. 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 python -m tornado.test.runtests # Runs one test python -m tornado.test.runtests tornado.test.stack_context_test
Additional keyword arguments passed through to
unittest.main(). For example, use
tornado.testing.main(verbosity=2)to show many test details as they are run. See http://docs.python.org/library/unittest.html#unittest.main for full argument list.
Changed in version 5.0: This function produces no output of its own; only that produced by the
unittestmodule (Previously it would add a PASS or FAIL log message).
Binds a server socket to an available port on localhost.
Returns a tuple (socket, port).
Changed in version 4.4: Always binds to
127.0.0.1without resolving the name
Get the global timeout setting for async tests.
Returns a float, the timeout in seconds.
New in version 3.1.