testing_test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. from tornado import gen, ioloop
  2. from tornado.httpserver import HTTPServer
  3. from tornado.locks import Event
  4. from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, bind_unused_port, gen_test
  5. from tornado.web import Application
  6. import asyncio
  7. import contextlib
  8. import gc
  9. import os
  10. import platform
  11. import sys
  12. import traceback
  13. import unittest
  14. import warnings
  15. @contextlib.contextmanager
  16. def set_environ(name, value):
  17. old_value = os.environ.get(name)
  18. os.environ[name] = value
  19. try:
  20. yield
  21. finally:
  22. if old_value is None:
  23. del os.environ[name]
  24. else:
  25. os.environ[name] = old_value
  26. class AsyncTestCaseTest(AsyncTestCase):
  27. def test_wait_timeout(self):
  28. time = self.io_loop.time
  29. # Accept default 5-second timeout, no error
  30. self.io_loop.add_timeout(time() + 0.01, self.stop)
  31. self.wait()
  32. # Timeout passed to wait()
  33. self.io_loop.add_timeout(time() + 1, self.stop)
  34. with self.assertRaises(self.failureException):
  35. self.wait(timeout=0.01)
  36. # Timeout set with environment variable
  37. self.io_loop.add_timeout(time() + 1, self.stop)
  38. with set_environ("ASYNC_TEST_TIMEOUT", "0.01"):
  39. with self.assertRaises(self.failureException):
  40. self.wait()
  41. def test_subsequent_wait_calls(self):
  42. """
  43. This test makes sure that a second call to wait()
  44. clears the first timeout.
  45. """
  46. # The first wait ends with time left on the clock
  47. self.io_loop.add_timeout(self.io_loop.time() + 0.00, self.stop)
  48. self.wait(timeout=0.1)
  49. # The second wait has enough time for itself but would fail if the
  50. # first wait's deadline were still in effect.
  51. self.io_loop.add_timeout(self.io_loop.time() + 0.2, self.stop)
  52. self.wait(timeout=0.4)
  53. class LeakTest(AsyncTestCase):
  54. def tearDown(self):
  55. super().tearDown()
  56. # Trigger a gc to make warnings more deterministic.
  57. gc.collect()
  58. def test_leaked_coroutine(self):
  59. # This test verifies that "leaked" coroutines are shut down
  60. # without triggering warnings like "task was destroyed but it
  61. # is pending". If this test were to fail, it would fail
  62. # because runtests.py detected unexpected output to stderr.
  63. event = Event()
  64. async def callback():
  65. try:
  66. await event.wait()
  67. except asyncio.CancelledError:
  68. pass
  69. self.io_loop.add_callback(callback)
  70. self.io_loop.add_callback(self.stop)
  71. self.wait()
  72. class AsyncHTTPTestCaseTest(AsyncHTTPTestCase):
  73. def setUp(self):
  74. super().setUp()
  75. # Bind a second port.
  76. sock, port = bind_unused_port()
  77. app = Application()
  78. server = HTTPServer(app, **self.get_httpserver_options())
  79. server.add_socket(sock)
  80. self.second_port = port
  81. self.second_server = server
  82. def get_app(self):
  83. return Application()
  84. def test_fetch_segment(self):
  85. path = "/path"
  86. response = self.fetch(path)
  87. self.assertEqual(response.request.url, self.get_url(path))
  88. def test_fetch_full_http_url(self):
  89. # Ensure that self.fetch() recognizes absolute urls and does
  90. # not transform them into references to our main test server.
  91. path = "http://127.0.0.1:%d/path" % self.second_port
  92. response = self.fetch(path)
  93. self.assertEqual(response.request.url, path)
  94. def tearDown(self):
  95. self.second_server.stop()
  96. super().tearDown()
  97. class AsyncTestCaseReturnAssertionsTest(unittest.TestCase):
  98. # These tests verify that tests that return non-None values (without being decorated with
  99. # @gen_test) raise errors instead of incorrectly succeeding. These tests should be removed or
  100. # updated when the _callTestMethod method is removed from AsyncTestCase (the same checks will
  101. # still happen, but they'll be performed in the stdlib as DeprecationWarnings)
  102. def test_undecorated_generator(self):
  103. class Test(AsyncTestCase):
  104. def test_gen(self):
  105. yield
  106. test = Test("test_gen")
  107. result = unittest.TestResult()
  108. test.run(result)
  109. self.assertEqual(len(result.errors), 1)
  110. self.assertIn("should be decorated", result.errors[0][1])
  111. @unittest.skipIf(
  112. platform.python_implementation() == "PyPy",
  113. "pypy destructor warnings cannot be silenced",
  114. )
  115. @unittest.skipIf(
  116. # This check actually exists in 3.11 but it changed in 3.12 in a way that breaks
  117. # this test.
  118. sys.version_info >= (3, 12),
  119. "py312 has its own check for test case returns",
  120. )
  121. def test_undecorated_coroutine(self):
  122. class Test(AsyncTestCase):
  123. async def test_coro(self):
  124. pass
  125. test = Test("test_coro")
  126. result = unittest.TestResult()
  127. # Silence "RuntimeWarning: coroutine 'test_coro' was never awaited".
  128. with warnings.catch_warnings():
  129. warnings.simplefilter("ignore")
  130. test.run(result)
  131. self.assertEqual(len(result.errors), 1)
  132. self.assertIn("should be decorated", result.errors[0][1])
  133. def test_undecorated_generator_with_skip(self):
  134. class Test(AsyncTestCase):
  135. @unittest.skip("don't run this")
  136. def test_gen(self):
  137. yield
  138. test = Test("test_gen")
  139. result = unittest.TestResult()
  140. test.run(result)
  141. self.assertEqual(len(result.errors), 0)
  142. self.assertEqual(len(result.skipped), 1)
  143. def test_other_return(self):
  144. class Test(AsyncTestCase):
  145. def test_other_return(self):
  146. return 42
  147. test = Test("test_other_return")
  148. result = unittest.TestResult()
  149. test.run(result)
  150. self.assertEqual(len(result.errors), 1)
  151. self.assertIn("Return value from test method ignored", result.errors[0][1])
  152. class SetUpTearDownTest(unittest.TestCase):
  153. def test_set_up_tear_down(self):
  154. """
  155. This test makes sure that AsyncTestCase calls super methods for
  156. setUp and tearDown.
  157. InheritBoth is a subclass of both AsyncTestCase and
  158. SetUpTearDown, with the ordering so that the super of
  159. AsyncTestCase will be SetUpTearDown.
  160. """
  161. events = []
  162. result = unittest.TestResult()
  163. class SetUpTearDown(unittest.TestCase):
  164. def setUp(self):
  165. events.append("setUp")
  166. def tearDown(self):
  167. events.append("tearDown")
  168. class InheritBoth(AsyncTestCase, SetUpTearDown):
  169. def test(self):
  170. events.append("test")
  171. InheritBoth("test").run(result)
  172. expected = ["setUp", "test", "tearDown"]
  173. self.assertEqual(expected, events)
  174. class AsyncHTTPTestCaseSetUpTearDownTest(unittest.TestCase):
  175. def test_tear_down_releases_app_and_http_server(self):
  176. result = unittest.TestResult()
  177. class SetUpTearDown(AsyncHTTPTestCase):
  178. def get_app(self):
  179. return Application()
  180. def test(self):
  181. self.assertTrue(hasattr(self, "_app"))
  182. self.assertTrue(hasattr(self, "http_server"))
  183. test = SetUpTearDown("test")
  184. test.run(result)
  185. self.assertFalse(hasattr(test, "_app"))
  186. self.assertFalse(hasattr(test, "http_server"))
  187. class GenTest(AsyncTestCase):
  188. def setUp(self):
  189. super().setUp()
  190. self.finished = False
  191. def tearDown(self):
  192. self.assertTrue(self.finished)
  193. super().tearDown()
  194. @gen_test
  195. def test_sync(self):
  196. self.finished = True
  197. @gen_test
  198. def test_async(self):
  199. yield gen.moment
  200. self.finished = True
  201. def test_timeout(self):
  202. # Set a short timeout and exceed it.
  203. @gen_test(timeout=0.1)
  204. def test(self):
  205. yield gen.sleep(1)
  206. # This can't use assertRaises because we need to inspect the
  207. # exc_info triple (and not just the exception object)
  208. try:
  209. test(self)
  210. self.fail("did not get expected exception")
  211. except ioloop.TimeoutError:
  212. # The stack trace should blame the add_timeout line, not just
  213. # unrelated IOLoop/testing internals.
  214. self.assertIn("gen.sleep(1)", traceback.format_exc())
  215. self.finished = True
  216. def test_no_timeout(self):
  217. # A test that does not exceed its timeout should succeed.
  218. @gen_test(timeout=1)
  219. def test(self):
  220. yield gen.sleep(0.1)
  221. test(self)
  222. self.finished = True
  223. def test_timeout_environment_variable(self):
  224. @gen_test(timeout=0.5)
  225. def test_long_timeout(self):
  226. yield gen.sleep(0.25)
  227. # Uses provided timeout of 0.5 seconds, doesn't time out.
  228. with set_environ("ASYNC_TEST_TIMEOUT", "0.1"):
  229. test_long_timeout(self)
  230. self.finished = True
  231. def test_no_timeout_environment_variable(self):
  232. @gen_test(timeout=0.01)
  233. def test_short_timeout(self):
  234. yield gen.sleep(1)
  235. # Uses environment-variable timeout of 0.1, times out.
  236. with set_environ("ASYNC_TEST_TIMEOUT", "0.1"):
  237. with self.assertRaises(ioloop.TimeoutError):
  238. test_short_timeout(self)
  239. self.finished = True
  240. def test_with_method_args(self):
  241. @gen_test
  242. def test_with_args(self, *args):
  243. self.assertEqual(args, ("test",))
  244. yield gen.moment
  245. test_with_args(self, "test")
  246. self.finished = True
  247. def test_with_method_kwargs(self):
  248. @gen_test
  249. def test_with_kwargs(self, **kwargs):
  250. self.assertDictEqual(kwargs, {"test": "test"})
  251. yield gen.moment
  252. test_with_kwargs(self, test="test")
  253. self.finished = True
  254. def test_native_coroutine(self):
  255. @gen_test
  256. async def test(self):
  257. self.finished = True
  258. test(self)
  259. def test_native_coroutine_timeout(self):
  260. # Set a short timeout and exceed it.
  261. @gen_test(timeout=0.1)
  262. async def test(self):
  263. await gen.sleep(1)
  264. try:
  265. test(self)
  266. self.fail("did not get expected exception")
  267. except ioloop.TimeoutError:
  268. self.finished = True
  269. if __name__ == "__main__":
  270. unittest.main()