PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/tornado-2.2.1/tornado/testing.py

#
Python | 381 lines | 284 code | 10 blank | 87 comment | 6 complexity | fcbe203d03d5587f92302891689b865c MD5 | raw file
  1. """Support classes for automated testing.
  2. This module contains three parts:
  3. * `AsyncTestCase`/`AsyncHTTPTestCase`: Subclasses of unittest.TestCase
  4. with additional support for testing asynchronous (IOLoop-based) code.
  5. * `LogTrapTestCase`: Subclass of unittest.TestCase that discards log output
  6. from tests that pass and only produces output for failing tests.
  7. * `main()`: A simple test runner (wrapper around unittest.main()) with support
  8. for the tornado.autoreload module to rerun the tests when code changes.
  9. These components may be used together or independently. In particular,
  10. it is safe to combine AsyncTestCase and LogTrapTestCase via multiple
  11. inheritance. See the docstrings for each class/function below for more
  12. information.
  13. """
  14. from __future__ import with_statement
  15. from cStringIO import StringIO
  16. try:
  17. from tornado.httpclient import AsyncHTTPClient
  18. from tornado.httpserver import HTTPServer
  19. from tornado.ioloop import IOLoop
  20. except ImportError:
  21. # These modules are not importable on app engine. Parts of this module
  22. # won't work, but e.g. LogTrapTestCase and main() will.
  23. AsyncHTTPClient = None
  24. HTTPServer = None
  25. IOLoop = None
  26. from tornado.stack_context import StackContext, NullContext
  27. import contextlib
  28. import logging
  29. import signal
  30. import sys
  31. import time
  32. import unittest
  33. _next_port = 10000
  34. def get_unused_port():
  35. """Returns a (hopefully) unused port number."""
  36. global _next_port
  37. port = _next_port
  38. _next_port = _next_port + 1
  39. return port
  40. class AsyncTestCase(unittest.TestCase):
  41. """TestCase subclass for testing IOLoop-based asynchronous code.
  42. The unittest framework is synchronous, so the test must be complete
  43. by the time the test method returns. This method provides the stop()
  44. and wait() methods for this purpose. The test method itself must call
  45. self.wait(), and asynchronous callbacks should call self.stop() to signal
  46. completion.
  47. By default, a new IOLoop is constructed for each test and is available
  48. as self.io_loop. This IOLoop should be used in the construction of
  49. HTTP clients/servers, etc. If the code being tested requires a
  50. global IOLoop, subclasses should override get_new_ioloop to return it.
  51. The IOLoop's start and stop methods should not be called directly.
  52. Instead, use self.stop self.wait. Arguments passed to self.stop are
  53. returned from self.wait. It is possible to have multiple
  54. wait/stop cycles in the same test.
  55. Example::
  56. # This test uses an asynchronous style similar to most async
  57. # application code.
  58. class MyTestCase(AsyncTestCase):
  59. def test_http_fetch(self):
  60. client = AsyncHTTPClient(self.io_loop)
  61. client.fetch("http://www.tornadoweb.org/", self.handle_fetch)
  62. self.wait()
  63. def handle_fetch(self, response):
  64. # Test contents of response (failures and exceptions here
  65. # will cause self.wait() to throw an exception and end the
  66. # test).
  67. # Exceptions thrown here are magically propagated to
  68. # self.wait() in test_http_fetch() via stack_context.
  69. self.assertIn("FriendFeed", response.body)
  70. self.stop()
  71. # This test uses the argument passing between self.stop and self.wait
  72. # for a simpler, more synchronous style.
  73. # This style is recommended over the preceding example because it
  74. # keeps the assertions in the test method itself, and is therefore
  75. # less sensitive to the subtleties of stack_context.
  76. class MyTestCase2(AsyncTestCase):
  77. def test_http_fetch(self):
  78. client = AsyncHTTPClient(self.io_loop)
  79. client.fetch("http://www.tornadoweb.org/", self.stop)
  80. response = self.wait()
  81. # Test contents of response
  82. self.assertIn("FriendFeed", response.body)
  83. """
  84. def __init__(self, *args, **kwargs):
  85. super(AsyncTestCase, self).__init__(*args, **kwargs)
  86. self.__stopped = False
  87. self.__running = False
  88. self.__failure = None
  89. self.__stop_args = None
  90. def setUp(self):
  91. super(AsyncTestCase, self).setUp()
  92. self.io_loop = self.get_new_ioloop()
  93. def tearDown(self):
  94. if (not IOLoop.initialized() or
  95. self.io_loop is not IOLoop.instance()):
  96. # Try to clean up any file descriptors left open in the ioloop.
  97. # This avoids leaks, especially when tests are run repeatedly
  98. # in the same process with autoreload (because curl does not
  99. # set FD_CLOEXEC on its file descriptors)
  100. self.io_loop.close(all_fds=True)
  101. super(AsyncTestCase, self).tearDown()
  102. def get_new_ioloop(self):
  103. '''Creates a new IOLoop for this test. May be overridden in
  104. subclasses for tests that require a specific IOLoop (usually
  105. the singleton).
  106. '''
  107. return IOLoop()
  108. @contextlib.contextmanager
  109. def _stack_context(self):
  110. try:
  111. yield
  112. except Exception:
  113. self.__failure = sys.exc_info()
  114. self.stop()
  115. def run(self, result=None):
  116. with StackContext(self._stack_context):
  117. super(AsyncTestCase, self).run(result)
  118. def stop(self, _arg=None, **kwargs):
  119. '''Stops the ioloop, causing one pending (or future) call to wait()
  120. to return.
  121. Keyword arguments or a single positional argument passed to stop() are
  122. saved and will be returned by wait().
  123. '''
  124. assert _arg is None or not kwargs
  125. self.__stop_args = kwargs or _arg
  126. if self.__running:
  127. self.io_loop.stop()
  128. self.__running = False
  129. self.__stopped = True
  130. def wait(self, condition=None, timeout=5):
  131. """Runs the IOLoop until stop is called or timeout has passed.
  132. In the event of a timeout, an exception will be thrown.
  133. If condition is not None, the IOLoop will be restarted after stop()
  134. until condition() returns true.
  135. """
  136. if not self.__stopped:
  137. if timeout:
  138. def timeout_func():
  139. try:
  140. raise self.failureException(
  141. 'Async operation timed out after %d seconds' %
  142. timeout)
  143. except Exception:
  144. self.__failure = sys.exc_info()
  145. self.stop()
  146. self.io_loop.add_timeout(time.time() + timeout, timeout_func)
  147. while True:
  148. self.__running = True
  149. with NullContext():
  150. # Wipe out the StackContext that was established in
  151. # self.run() so that all callbacks executed inside the
  152. # IOLoop will re-run it.
  153. self.io_loop.start()
  154. if (self.__failure is not None or
  155. condition is None or condition()):
  156. break
  157. assert self.__stopped
  158. self.__stopped = False
  159. if self.__failure is not None:
  160. # 2to3 isn't smart enough to convert three-argument raise
  161. # statements correctly in some cases.
  162. if isinstance(self.__failure[1], self.__failure[0]):
  163. raise self.__failure[1], None, self.__failure[2]
  164. else:
  165. raise self.__failure[0], self.__failure[1], self.__failure[2]
  166. result = self.__stop_args
  167. self.__stop_args = None
  168. return result
  169. class AsyncHTTPTestCase(AsyncTestCase):
  170. '''A test case that starts up an HTTP server.
  171. Subclasses must override get_app(), which returns the
  172. tornado.web.Application (or other HTTPServer callback) to be tested.
  173. Tests will typically use the provided self.http_client to fetch
  174. URLs from this server.
  175. Example::
  176. class MyHTTPTest(AsyncHTTPTestCase):
  177. def get_app(self):
  178. return Application([('/', MyHandler)...])
  179. def test_homepage(self):
  180. # The following two lines are equivalent to
  181. # response = self.fetch('/')
  182. # but are shown in full here to demonstrate explicit use
  183. # of self.stop and self.wait.
  184. self.http_client.fetch(self.get_url('/'), self.stop)
  185. response = self.wait()
  186. # test contents of response
  187. '''
  188. def setUp(self):
  189. super(AsyncHTTPTestCase, self).setUp()
  190. self.__port = None
  191. self.http_client = AsyncHTTPClient(io_loop=self.io_loop)
  192. self._app = self.get_app()
  193. self.http_server = HTTPServer(self._app, io_loop=self.io_loop,
  194. **self.get_httpserver_options())
  195. self.http_server.listen(self.get_http_port(), address="127.0.0.1")
  196. def get_app(self):
  197. """Should be overridden by subclasses to return a
  198. tornado.web.Application or other HTTPServer callback.
  199. """
  200. raise NotImplementedError()
  201. def fetch(self, path, **kwargs):
  202. """Convenience method to synchronously fetch a url.
  203. The given path will be appended to the local server's host and port.
  204. Any additional kwargs will be passed directly to
  205. AsyncHTTPClient.fetch (and so could be used to pass method="POST",
  206. body="...", etc).
  207. """
  208. self.http_client.fetch(self.get_url(path), self.stop, **kwargs)
  209. return self.wait()
  210. def get_httpserver_options(self):
  211. """May be overridden by subclasses to return additional
  212. keyword arguments for HTTPServer.
  213. """
  214. return {}
  215. def get_http_port(self):
  216. """Returns the port used by the HTTPServer.
  217. A new port is chosen for each test.
  218. """
  219. if self.__port is None:
  220. self.__port = get_unused_port()
  221. return self.__port
  222. def get_url(self, path):
  223. """Returns an absolute url for the given path on the test server."""
  224. return 'http://localhost:%s%s' % (self.get_http_port(), path)
  225. def tearDown(self):
  226. self.http_server.stop()
  227. self.http_client.close()
  228. super(AsyncHTTPTestCase, self).tearDown()
  229. class LogTrapTestCase(unittest.TestCase):
  230. """A test case that captures and discards all logging output
  231. if the test passes.
  232. Some libraries can produce a lot of logging output even when
  233. the test succeeds, so this class can be useful to minimize the noise.
  234. Simply use it as a base class for your test case. It is safe to combine
  235. with AsyncTestCase via multiple inheritance
  236. ("class MyTestCase(AsyncHTTPTestCase, LogTrapTestCase):")
  237. This class assumes that only one log handler is configured and that
  238. it is a StreamHandler. This is true for both logging.basicConfig
  239. and the "pretty logging" configured by tornado.options.
  240. """
  241. def run(self, result=None):
  242. logger = logging.getLogger()
  243. if len(logger.handlers) > 1:
  244. # Multiple handlers have been defined. It gets messy to handle
  245. # this, especially since the handlers may have different
  246. # formatters. Just leave the logging alone in this case.
  247. super(LogTrapTestCase, self).run(result)
  248. return
  249. if not logger.handlers:
  250. logging.basicConfig()
  251. self.assertEqual(len(logger.handlers), 1)
  252. handler = logger.handlers[0]
  253. assert isinstance(handler, logging.StreamHandler)
  254. old_stream = handler.stream
  255. try:
  256. handler.stream = StringIO()
  257. logging.info("RUNNING TEST: " + str(self))
  258. old_error_count = len(result.failures) + len(result.errors)
  259. super(LogTrapTestCase, self).run(result)
  260. new_error_count = len(result.failures) + len(result.errors)
  261. if new_error_count != old_error_count:
  262. old_stream.write(handler.stream.getvalue())
  263. finally:
  264. handler.stream = old_stream
  265. def main():
  266. """A simple test runner.
  267. This test runner is essentially equivalent to `unittest.main` from
  268. the standard library, but adds support for tornado-style option
  269. parsing and log formatting.
  270. The easiest way to run a test is via the command line::
  271. python -m tornado.testing tornado.test.stack_context_test
  272. See the standard library unittest module for ways in which tests can
  273. be specified.
  274. Projects with many tests may wish to define a test script like
  275. tornado/test/runtests.py. This script should define a method all()
  276. which returns a test suite and then call tornado.testing.main().
  277. Note that even when a test script is used, the all() test suite may
  278. be overridden by naming a single test on the command line::
  279. # Runs all tests
  280. tornado/test/runtests.py
  281. # Runs one test
  282. tornado/test/runtests.py tornado.test.stack_context_test
  283. """
  284. from tornado.options import define, options, parse_command_line
  285. define('autoreload', type=bool, default=False,
  286. help="DEPRECATED: use tornado.autoreload.main instead")
  287. define('httpclient', type=str, default=None)
  288. define('exception_on_interrupt', type=bool, default=True,
  289. help=("If true (default), ctrl-c raises a KeyboardInterrupt "
  290. "exception. This prints a stack trace but cannot interrupt "
  291. "certain operations. If false, the process is more reliably "
  292. "killed, but does not print a stack trace."))
  293. argv = [sys.argv[0]] + parse_command_line(sys.argv)
  294. if options.httpclient:
  295. from tornado.httpclient import AsyncHTTPClient
  296. AsyncHTTPClient.configure(options.httpclient)
  297. if not options.exception_on_interrupt:
  298. signal.signal(signal.SIGINT, signal.SIG_DFL)
  299. if __name__ == '__main__' and len(argv) == 1:
  300. print >> sys.stderr, "No tests specified"
  301. sys.exit(1)
  302. try:
  303. # In order to be able to run tests by their fully-qualified name
  304. # on the command line without importing all tests here,
  305. # module must be set to None. Python 3.2's unittest.main ignores
  306. # defaultTest if no module is given (it tries to do its own
  307. # test discovery, which is incompatible with auto2to3), so don't
  308. # set module if we're not asking for a specific test.
  309. if len(argv) > 1:
  310. unittest.main(module=None, argv=argv)
  311. else:
  312. unittest.main(defaultTest="all", argv=argv)
  313. except SystemExit, e:
  314. if e.code == 0:
  315. logging.info('PASS')
  316. else:
  317. logging.error('FAIL')
  318. if not options.autoreload:
  319. raise
  320. if options.autoreload:
  321. import tornado.autoreload
  322. tornado.autoreload.wait()
  323. if __name__ == '__main__':
  324. main()