testing.py 27 KB

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