testing.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. #!/usr/bin/env python
  2. """Support classes for automated testing.
  3. * `AsyncTestCase` and `AsyncHTTPTestCase`: Subclasses of unittest.TestCase
  4. with additional support for testing asynchronous (`.IOLoop` based) code.
  5. * `ExpectLog` and `LogTrapTestCase`: Make test logs less spammy.
  6. * `main()`: A simple test runner (wrapper around unittest.main()) with support
  7. for the tornado.autoreload module to rerun the tests when code changes.
  8. """
  9. from __future__ import absolute_import, division, print_function, with_statement
  10. try:
  11. from tornado import gen
  12. from tornado.httpclient import AsyncHTTPClient
  13. from tornado.httpserver import HTTPServer
  14. from tornado.simple_httpclient import SimpleAsyncHTTPClient
  15. from tornado.ioloop import IOLoop, TimeoutError
  16. from tornado import netutil
  17. from tornado.process import Subprocess
  18. except ImportError:
  19. # These modules are not importable on app engine. Parts of this module
  20. # won't work, but e.g. LogTrapTestCase and main() will.
  21. AsyncHTTPClient = None
  22. gen = None
  23. HTTPServer = None
  24. IOLoop = None
  25. netutil = None
  26. SimpleAsyncHTTPClient = None
  27. Subprocess = None
  28. from tornado.log import gen_log, app_log
  29. from tornado.stack_context import ExceptionStackContext
  30. from tornado.util import raise_exc_info, basestring_type
  31. import functools
  32. import inspect
  33. import logging
  34. import os
  35. import re
  36. import signal
  37. import socket
  38. import sys
  39. try:
  40. from cStringIO import StringIO # py2
  41. except ImportError:
  42. from io import StringIO # py3
  43. try:
  44. from collections.abc import Generator as GeneratorType # py35+
  45. except ImportError:
  46. from types import GeneratorType
  47. if sys.version_info >= (3, 5):
  48. iscoroutine = inspect.iscoroutine
  49. iscoroutinefunction = inspect.iscoroutinefunction
  50. else:
  51. iscoroutine = iscoroutinefunction = lambda f: False
  52. # Tornado's own test suite requires the updated unittest module
  53. # (either py27+ or unittest2) so tornado.test.util enforces
  54. # this requirement, but for other users of tornado.testing we want
  55. # to allow the older version if unitest2 is not available.
  56. if sys.version_info >= (3,):
  57. # On python 3, mixing unittest2 and unittest (including doctest)
  58. # doesn't seem to work, so always use unittest.
  59. import unittest
  60. else:
  61. # On python 2, prefer unittest2 when available.
  62. try:
  63. import unittest2 as unittest
  64. except ImportError:
  65. import unittest
  66. _next_port = 10000
  67. def get_unused_port():
  68. """Returns a (hopefully) unused port number.
  69. This function does not guarantee that the port it returns is available,
  70. only that a series of get_unused_port calls in a single process return
  71. distinct ports.
  72. .. deprecated::
  73. Use bind_unused_port instead, which is guaranteed to find an unused port.
  74. """
  75. global _next_port
  76. port = _next_port
  77. _next_port = _next_port + 1
  78. return port
  79. def bind_unused_port(reuse_port=False):
  80. """Binds a server socket to an available port on localhost.
  81. Returns a tuple (socket, port).
  82. """
  83. [sock] = netutil.bind_sockets(None, 'localhost', family=socket.AF_INET,
  84. reuse_port=reuse_port)
  85. port = sock.getsockname()[1]
  86. return sock, port
  87. def get_async_test_timeout():
  88. """Get the global timeout setting for async tests.
  89. Returns a float, the timeout in seconds.
  90. .. versionadded:: 3.1
  91. """
  92. try:
  93. return float(os.environ.get('ASYNC_TEST_TIMEOUT'))
  94. except (ValueError, TypeError):
  95. return 5
  96. class _TestMethodWrapper(object):
  97. """Wraps a test method to raise an error if it returns a value.
  98. This is mainly used to detect undecorated generators (if a test
  99. method yields it must use a decorator to consume the generator),
  100. but will also detect other kinds of return values (these are not
  101. necessarily errors, but we alert anyway since there is no good
  102. reason to return a value from a test.
  103. """
  104. def __init__(self, orig_method):
  105. self.orig_method = orig_method
  106. def __call__(self, *args, **kwargs):
  107. result = self.orig_method(*args, **kwargs)
  108. if isinstance(result, GeneratorType) or iscoroutine(result):
  109. raise TypeError("Generator and coroutine test methods should be"
  110. " decorated with tornado.testing.gen_test")
  111. elif result is not None:
  112. raise ValueError("Return value from test method ignored: %r" %
  113. result)
  114. def __getattr__(self, name):
  115. """Proxy all unknown attributes to the original method.
  116. This is important for some of the decorators in the `unittest`
  117. module, such as `unittest.skipIf`.
  118. """
  119. return getattr(self.orig_method, name)
  120. class AsyncTestCase(unittest.TestCase):
  121. """`~unittest.TestCase` subclass for testing `.IOLoop`-based
  122. asynchronous code.
  123. The unittest framework is synchronous, so the test must be
  124. complete by the time the test method returns. This means that
  125. asynchronous code cannot be used in quite the same way as usual.
  126. To write test functions that use the same ``yield``-based patterns
  127. used with the `tornado.gen` module, decorate your test methods
  128. with `tornado.testing.gen_test` instead of
  129. `tornado.gen.coroutine`. This class also provides the `stop()`
  130. and `wait()` methods for a more manual style of testing. The test
  131. method itself must call ``self.wait()``, and asynchronous
  132. callbacks should call ``self.stop()`` to signal completion.
  133. By default, a new `.IOLoop` is constructed for each test and is available
  134. as ``self.io_loop``. This `.IOLoop` should be used in the construction of
  135. HTTP clients/servers, etc. If the code being tested requires a
  136. global `.IOLoop`, subclasses should override `get_new_ioloop` to return it.
  137. The `.IOLoop`'s ``start`` and ``stop`` methods should not be
  138. called directly. Instead, use `self.stop <stop>` and `self.wait
  139. <wait>`. Arguments passed to ``self.stop`` are returned from
  140. ``self.wait``. It is possible to have multiple ``wait``/``stop``
  141. cycles in the same test.
  142. Example::
  143. # This test uses coroutine style.
  144. class MyTestCase(AsyncTestCase):
  145. @tornado.testing.gen_test
  146. def test_http_fetch(self):
  147. client = AsyncHTTPClient(self.io_loop)
  148. response = yield client.fetch("http://www.tornadoweb.org")
  149. # Test contents of response
  150. self.assertIn("FriendFeed", response.body)
  151. # This test uses argument passing between self.stop and self.wait.
  152. class MyTestCase2(AsyncTestCase):
  153. def test_http_fetch(self):
  154. client = AsyncHTTPClient(self.io_loop)
  155. client.fetch("http://www.tornadoweb.org/", self.stop)
  156. response = self.wait()
  157. # Test contents of response
  158. self.assertIn("FriendFeed", response.body)
  159. # This test uses an explicit callback-based style.
  160. class MyTestCase3(AsyncTestCase):
  161. def test_http_fetch(self):
  162. client = AsyncHTTPClient(self.io_loop)
  163. client.fetch("http://www.tornadoweb.org/", self.handle_fetch)
  164. self.wait()
  165. def handle_fetch(self, response):
  166. # Test contents of response (failures and exceptions here
  167. # will cause self.wait() to throw an exception and end the
  168. # test).
  169. # Exceptions thrown here are magically propagated to
  170. # self.wait() in test_http_fetch() via stack_context.
  171. self.assertIn("FriendFeed", response.body)
  172. self.stop()
  173. """
  174. def __init__(self, methodName='runTest', **kwargs):
  175. super(AsyncTestCase, self).__init__(methodName, **kwargs)
  176. self.__stopped = False
  177. self.__running = False
  178. self.__failure = None
  179. self.__stop_args = None
  180. self.__timeout = None
  181. # It's easy to forget the @gen_test decorator, but if you do
  182. # the test will silently be ignored because nothing will consume
  183. # the generator. Replace the test method with a wrapper that will
  184. # make sure it's not an undecorated generator.
  185. setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName)))
  186. def setUp(self):
  187. super(AsyncTestCase, self).setUp()
  188. self.io_loop = self.get_new_ioloop()
  189. self.io_loop.make_current()
  190. def tearDown(self):
  191. # Clean up Subprocess, so it can be used again with a new ioloop.
  192. Subprocess.uninitialize()
  193. self.io_loop.clear_current()
  194. if (not IOLoop.initialized() or
  195. self.io_loop is not IOLoop.instance()):
  196. # Try to clean up any file descriptors left open in the ioloop.
  197. # This avoids leaks, especially when tests are run repeatedly
  198. # in the same process with autoreload (because curl does not
  199. # set FD_CLOEXEC on its file descriptors)
  200. self.io_loop.close(all_fds=True)
  201. super(AsyncTestCase, self).tearDown()
  202. # In case an exception escaped or the StackContext caught an exception
  203. # when there wasn't a wait() to re-raise it, do so here.
  204. # This is our last chance to raise an exception in a way that the
  205. # unittest machinery understands.
  206. self.__rethrow()
  207. def get_new_ioloop(self):
  208. """Creates a new `.IOLoop` for this test. May be overridden in
  209. subclasses for tests that require a specific `.IOLoop` (usually
  210. the singleton `.IOLoop.instance()`).
  211. """
  212. return IOLoop()
  213. def _handle_exception(self, typ, value, tb):
  214. if self.__failure is None:
  215. self.__failure = (typ, value, tb)
  216. else:
  217. app_log.error("multiple unhandled exceptions in test",
  218. exc_info=(typ, value, tb))
  219. self.stop()
  220. return True
  221. def __rethrow(self):
  222. if self.__failure is not None:
  223. failure = self.__failure
  224. self.__failure = None
  225. raise_exc_info(failure)
  226. def run(self, result=None):
  227. with ExceptionStackContext(self._handle_exception):
  228. super(AsyncTestCase, self).run(result)
  229. # As a last resort, if an exception escaped super.run() and wasn't
  230. # re-raised in tearDown, raise it here. This will cause the
  231. # unittest run to fail messily, but that's better than silently
  232. # ignoring an error.
  233. self.__rethrow()
  234. def stop(self, _arg=None, **kwargs):
  235. """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
  236. to return.
  237. Keyword arguments or a single positional argument passed to `stop()` are
  238. saved and will be returned by `wait()`.
  239. """
  240. assert _arg is None or not kwargs
  241. self.__stop_args = kwargs or _arg
  242. if self.__running:
  243. self.io_loop.stop()
  244. self.__running = False
  245. self.__stopped = True
  246. def wait(self, condition=None, timeout=None):
  247. """Runs the `.IOLoop` until stop is called or timeout has passed.
  248. In the event of a timeout, an exception will be thrown. The
  249. default timeout is 5 seconds; it may be overridden with a
  250. ``timeout`` keyword argument or globally with the
  251. ``ASYNC_TEST_TIMEOUT`` environment variable.
  252. If ``condition`` is not None, the `.IOLoop` will be restarted
  253. after `stop()` until ``condition()`` returns true.
  254. .. versionchanged:: 3.1
  255. Added the ``ASYNC_TEST_TIMEOUT`` environment variable.
  256. """
  257. if timeout is None:
  258. timeout = get_async_test_timeout()
  259. if not self.__stopped:
  260. if timeout:
  261. def timeout_func():
  262. try:
  263. raise self.failureException(
  264. 'Async operation timed out after %s seconds' %
  265. timeout)
  266. except Exception:
  267. self.__failure = sys.exc_info()
  268. self.stop()
  269. self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout, timeout_func)
  270. while True:
  271. self.__running = True
  272. self.io_loop.start()
  273. if (self.__failure is not None or
  274. condition is None or condition()):
  275. break
  276. if self.__timeout is not None:
  277. self.io_loop.remove_timeout(self.__timeout)
  278. self.__timeout = None
  279. assert self.__stopped
  280. self.__stopped = False
  281. self.__rethrow()
  282. result = self.__stop_args
  283. self.__stop_args = None
  284. return result
  285. class AsyncHTTPTestCase(AsyncTestCase):
  286. """A test case that starts up an HTTP server.
  287. Subclasses must override `get_app()`, which returns the
  288. `tornado.web.Application` (or other `.HTTPServer` callback) to be tested.
  289. Tests will typically use the provided ``self.http_client`` to fetch
  290. URLs from this server.
  291. Example, assuming the "Hello, world" example from the user guide is in
  292. ``hello.py``::
  293. import hello
  294. class TestHelloApp(AsyncHTTPTestCase):
  295. def get_app(self):
  296. return hello.make_app()
  297. def test_homepage(self):
  298. response = self.fetch('/')
  299. self.assertEqual(response.code, 200)
  300. self.assertEqual(response.body, 'Hello, world')
  301. That call to ``self.fetch()`` is equivalent to ::
  302. self.http_client.fetch(self.get_url('/'), self.stop)
  303. response = self.wait()
  304. which illustrates how AsyncTestCase can turn an asynchronous operation,
  305. like ``http_client.fetch()``, into a synchronous operation. If you need
  306. to do other asynchronous operations in tests, you'll probably need to use
  307. ``stop()`` and ``wait()`` yourself.
  308. """
  309. def setUp(self):
  310. super(AsyncHTTPTestCase, self).setUp()
  311. sock, port = bind_unused_port()
  312. self.__port = port
  313. self.http_client = self.get_http_client()
  314. self._app = self.get_app()
  315. self.http_server = self.get_http_server()
  316. self.http_server.add_sockets([sock])
  317. def get_http_client(self):
  318. return AsyncHTTPClient(io_loop=self.io_loop)
  319. def get_http_server(self):
  320. return HTTPServer(self._app, io_loop=self.io_loop,
  321. **self.get_httpserver_options())
  322. def get_app(self):
  323. """Should be overridden by subclasses to return a
  324. `tornado.web.Application` or other `.HTTPServer` callback.
  325. """
  326. raise NotImplementedError()
  327. def fetch(self, path, **kwargs):
  328. """Convenience method to synchronously fetch a url.
  329. The given path will be appended to the local server's host and
  330. port. Any additional kwargs will be passed directly to
  331. `.AsyncHTTPClient.fetch` (and so could be used to pass
  332. ``method="POST"``, ``body="..."``, etc).
  333. """
  334. self.http_client.fetch(self.get_url(path), self.stop, **kwargs)
  335. return self.wait()
  336. def get_httpserver_options(self):
  337. """May be overridden by subclasses to return additional
  338. keyword arguments for the server.
  339. """
  340. return {}
  341. def get_http_port(self):
  342. """Returns the port used by the server.
  343. A new port is chosen for each test.
  344. """
  345. return self.__port
  346. def get_protocol(self):
  347. return 'http'
  348. def get_url(self, path):
  349. """Returns an absolute url for the given path on the test server."""
  350. return '%s://localhost:%s%s' % (self.get_protocol(),
  351. self.get_http_port(), path)
  352. def tearDown(self):
  353. self.http_server.stop()
  354. self.io_loop.run_sync(self.http_server.close_all_connections,
  355. timeout=get_async_test_timeout())
  356. if (not IOLoop.initialized() or
  357. self.http_client.io_loop is not IOLoop.instance()):
  358. self.http_client.close()
  359. super(AsyncHTTPTestCase, self).tearDown()
  360. class AsyncHTTPSTestCase(AsyncHTTPTestCase):
  361. """A test case that starts an HTTPS server.
  362. Interface is generally the same as `AsyncHTTPTestCase`.
  363. """
  364. def get_http_client(self):
  365. return AsyncHTTPClient(io_loop=self.io_loop, force_instance=True,
  366. defaults=dict(validate_cert=False))
  367. def get_httpserver_options(self):
  368. return dict(ssl_options=self.get_ssl_options())
  369. def get_ssl_options(self):
  370. """May be overridden by subclasses to select SSL options.
  371. By default includes a self-signed testing certificate.
  372. """
  373. # Testing keys were generated with:
  374. # openssl req -new -keyout tornado/test/test.key -out tornado/test/test.crt -nodes -days 3650 -x509
  375. module_dir = os.path.dirname(__file__)
  376. return dict(
  377. certfile=os.path.join(module_dir, 'test', 'test.crt'),
  378. keyfile=os.path.join(module_dir, 'test', 'test.key'))
  379. def get_protocol(self):
  380. return 'https'
  381. def gen_test(func=None, timeout=None):
  382. """Testing equivalent of ``@gen.coroutine``, to be applied to test methods.
  383. ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not
  384. already running. ``@gen_test`` should be applied to test methods
  385. on subclasses of `AsyncTestCase`.
  386. Example::
  387. class MyTest(AsyncHTTPTestCase):
  388. @gen_test
  389. def test_something(self):
  390. response = yield gen.Task(self.fetch('/'))
  391. By default, ``@gen_test`` times out after 5 seconds. The timeout may be
  392. overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable,
  393. or for each test with the ``timeout`` keyword argument::
  394. class MyTest(AsyncHTTPTestCase):
  395. @gen_test(timeout=10)
  396. def test_something_slow(self):
  397. response = yield gen.Task(self.fetch('/'))
  398. .. versionadded:: 3.1
  399. The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment
  400. variable.
  401. .. versionchanged:: 4.0
  402. The wrapper now passes along ``*args, **kwargs`` so it can be used
  403. on functions with arguments.
  404. """
  405. if timeout is None:
  406. timeout = get_async_test_timeout()
  407. def wrap(f):
  408. # Stack up several decorators to allow us to access the generator
  409. # object itself. In the innermost wrapper, we capture the generator
  410. # and save it in an attribute of self. Next, we run the wrapped
  411. # function through @gen.coroutine. Finally, the coroutine is
  412. # wrapped again to make it synchronous with run_sync.
  413. #
  414. # This is a good case study arguing for either some sort of
  415. # extensibility in the gen decorators or cancellation support.
  416. @functools.wraps(f)
  417. def pre_coroutine(self, *args, **kwargs):
  418. result = f(self, *args, **kwargs)
  419. if isinstance(result, GeneratorType) or iscoroutine(result):
  420. self._test_generator = result
  421. else:
  422. self._test_generator = None
  423. return result
  424. if iscoroutinefunction(f):
  425. coro = pre_coroutine
  426. else:
  427. coro = gen.coroutine(pre_coroutine)
  428. @functools.wraps(coro)
  429. def post_coroutine(self, *args, **kwargs):
  430. try:
  431. return self.io_loop.run_sync(
  432. functools.partial(coro, self, *args, **kwargs),
  433. timeout=timeout)
  434. except TimeoutError as e:
  435. # run_sync raises an error with an unhelpful traceback.
  436. # Throw it back into the generator or coroutine so the stack
  437. # trace is replaced by the point where the test is stopped.
  438. self._test_generator.throw(e)
  439. # In case the test contains an overly broad except clause,
  440. # we may get back here. In this case re-raise the original
  441. # exception, which is better than nothing.
  442. raise
  443. return post_coroutine
  444. if func is not None:
  445. # Used like:
  446. # @gen_test
  447. # def f(self):
  448. # pass
  449. return wrap(func)
  450. else:
  451. # Used like @gen_test(timeout=10)
  452. return wrap
  453. # Without this attribute, nosetests will try to run gen_test as a test
  454. # anywhere it is imported.
  455. gen_test.__test__ = False
  456. class LogTrapTestCase(unittest.TestCase):
  457. """A test case that captures and discards all logging output
  458. if the test passes.
  459. Some libraries can produce a lot of logging output even when
  460. the test succeeds, so this class can be useful to minimize the noise.
  461. Simply use it as a base class for your test case. It is safe to combine
  462. with AsyncTestCase via multiple inheritance
  463. (``class MyTestCase(AsyncHTTPTestCase, LogTrapTestCase):``)
  464. This class assumes that only one log handler is configured and
  465. that it is a `~logging.StreamHandler`. This is true for both
  466. `logging.basicConfig` and the "pretty logging" configured by
  467. `tornado.options`. It is not compatible with other log buffering
  468. mechanisms, such as those provided by some test runners.
  469. .. deprecated:: 4.1
  470. Use the unittest module's ``--buffer`` option instead, or `.ExpectLog`.
  471. """
  472. def run(self, result=None):
  473. logger = logging.getLogger()
  474. if not logger.handlers:
  475. logging.basicConfig()
  476. handler = logger.handlers[0]
  477. if (len(logger.handlers) > 1 or
  478. not isinstance(handler, logging.StreamHandler)):
  479. # Logging has been configured in a way we don't recognize,
  480. # so just leave it alone.
  481. super(LogTrapTestCase, self).run(result)
  482. return
  483. old_stream = handler.stream
  484. try:
  485. handler.stream = StringIO()
  486. gen_log.info("RUNNING TEST: " + str(self))
  487. old_error_count = len(result.failures) + len(result.errors)
  488. super(LogTrapTestCase, self).run(result)
  489. new_error_count = len(result.failures) + len(result.errors)
  490. if new_error_count != old_error_count:
  491. old_stream.write(handler.stream.getvalue())
  492. finally:
  493. handler.stream = old_stream
  494. class ExpectLog(logging.Filter):
  495. """Context manager to capture and suppress expected log output.
  496. Useful to make tests of error conditions less noisy, while still
  497. leaving unexpected log entries visible. *Not thread safe.*
  498. The attribute ``logged_stack`` is set to true if any exception
  499. stack trace was logged.
  500. Usage::
  501. with ExpectLog('tornado.application', "Uncaught exception"):
  502. error_response = self.fetch("/some_page")
  503. .. versionchanged:: 4.3
  504. Added the ``logged_stack`` attribute.
  505. """
  506. def __init__(self, logger, regex, required=True):
  507. """Constructs an ExpectLog context manager.
  508. :param logger: Logger object (or name of logger) to watch. Pass
  509. an empty string to watch the root logger.
  510. :param regex: Regular expression to match. Any log entries on
  511. the specified logger that match this regex will be suppressed.
  512. :param required: If true, an exeption will be raised if the end of
  513. the ``with`` statement is reached without matching any log entries.
  514. """
  515. if isinstance(logger, basestring_type):
  516. logger = logging.getLogger(logger)
  517. self.logger = logger
  518. self.regex = re.compile(regex)
  519. self.required = required
  520. self.matched = False
  521. self.logged_stack = False
  522. def filter(self, record):
  523. if record.exc_info:
  524. self.logged_stack = True
  525. message = record.getMessage()
  526. if self.regex.match(message):
  527. self.matched = True
  528. return False
  529. return True
  530. def __enter__(self):
  531. self.logger.addFilter(self)
  532. return self
  533. def __exit__(self, typ, value, tb):
  534. self.logger.removeFilter(self)
  535. if not typ and self.required and not self.matched:
  536. raise Exception("did not get expected log message")
  537. def main(**kwargs):
  538. """A simple test runner.
  539. This test runner is essentially equivalent to `unittest.main` from
  540. the standard library, but adds support for tornado-style option
  541. parsing and log formatting.
  542. The easiest way to run a test is via the command line::
  543. python -m tornado.testing tornado.test.stack_context_test
  544. See the standard library unittest module for ways in which tests can
  545. be specified.
  546. Projects with many tests may wish to define a test script like
  547. ``tornado/test/runtests.py``. This script should define a method
  548. ``all()`` which returns a test suite and then call
  549. `tornado.testing.main()`. Note that even when a test script is
  550. used, the ``all()`` test suite may be overridden by naming a
  551. single test on the command line::
  552. # Runs all tests
  553. python -m tornado.test.runtests
  554. # Runs one test
  555. python -m tornado.test.runtests tornado.test.stack_context_test
  556. Additional keyword arguments passed through to ``unittest.main()``.
  557. For example, use ``tornado.testing.main(verbosity=2)``
  558. to show many test details as they are run.
  559. See http://docs.python.org/library/unittest.html#unittest.main
  560. for full argument list.
  561. """
  562. from tornado.options import define, options, parse_command_line
  563. define('exception_on_interrupt', type=bool, default=True,
  564. help=("If true (default), ctrl-c raises a KeyboardInterrupt "
  565. "exception. This prints a stack trace but cannot interrupt "
  566. "certain operations. If false, the process is more reliably "
  567. "killed, but does not print a stack trace."))
  568. # support the same options as unittest's command-line interface
  569. define('verbose', type=bool)
  570. define('quiet', type=bool)
  571. define('failfast', type=bool)
  572. define('catch', type=bool)
  573. define('buffer', type=bool)
  574. argv = [sys.argv[0]] + parse_command_line(sys.argv)
  575. if not options.exception_on_interrupt:
  576. signal.signal(signal.SIGINT, signal.SIG_DFL)
  577. if options.verbose is not None:
  578. kwargs['verbosity'] = 2
  579. if options.quiet is not None:
  580. kwargs['verbosity'] = 0
  581. if options.failfast is not None:
  582. kwargs['failfast'] = True
  583. if options.catch is not None:
  584. kwargs['catchbreak'] = True
  585. if options.buffer is not None:
  586. kwargs['buffer'] = True
  587. if __name__ == '__main__' and len(argv) == 1:
  588. print("No tests specified", file=sys.stderr)
  589. sys.exit(1)
  590. try:
  591. # In order to be able to run tests by their fully-qualified name
  592. # on the command line without importing all tests here,
  593. # module must be set to None. Python 3.2's unittest.main ignores
  594. # defaultTest if no module is given (it tries to do its own
  595. # test discovery, which is incompatible with auto2to3), so don't
  596. # set module if we're not asking for a specific test.
  597. if len(argv) > 1:
  598. unittest.main(module=None, argv=argv, **kwargs)
  599. else:
  600. unittest.main(defaultTest="all", argv=argv, **kwargs)
  601. except SystemExit as e:
  602. if e.code == 0:
  603. gen_log.info('PASS')
  604. else:
  605. gen_log.error('FAIL')
  606. raise
  607. if __name__ == '__main__':
  608. main()