import_test.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # flake8: noqa
  2. import subprocess
  3. import sys
  4. import unittest
  5. _import_everything = b"""
  6. # The event loop is not fork-safe, and it's easy to initialize an asyncio.Future
  7. # at startup, which in turn creates the default event loop and prevents forking.
  8. # Explicitly disallow the default event loop so that an error will be raised
  9. # if something tries to touch it.
  10. import asyncio
  11. import warnings
  12. with warnings.catch_warnings():
  13. warnings.simplefilter("ignore", DeprecationWarning)
  14. asyncio.set_event_loop(None)
  15. import importlib
  16. import tornado
  17. for mod in tornado.__all__:
  18. if mod == "curl_httpclient":
  19. # This module has extra dependencies; skip it if they're not installed.
  20. try:
  21. import pycurl
  22. except ImportError:
  23. continue
  24. importlib.import_module(f"tornado.{mod}")
  25. """
  26. _import_lazy = b"""
  27. import sys
  28. import tornado
  29. if "tornado.web" in sys.modules:
  30. raise Exception("unexpected eager import")
  31. # Trigger a lazy import by referring to something in a submodule.
  32. tornado.web.RequestHandler
  33. if "tornado.web" not in sys.modules:
  34. raise Exception("lazy import did not update sys.modules")
  35. """
  36. class ImportTest(unittest.TestCase):
  37. def test_import_everything(self):
  38. # Test that all Tornado modules can be imported without side effects,
  39. # specifically without initializing the default asyncio event loop.
  40. # Since we can't tell which modules may have already beein imported
  41. # in our process, do it in a subprocess for a clean slate.
  42. proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)
  43. proc.communicate(_import_everything)
  44. self.assertEqual(proc.returncode, 0)
  45. def test_lazy_import(self):
  46. # Test that submodules can be referenced lazily after "import tornado"
  47. proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)
  48. proc.communicate(_import_lazy)
  49. self.assertEqual(proc.returncode, 0)
  50. def test_import_aliases(self):
  51. # Ensure we don't delete formerly-documented aliases accidentally.
  52. import tornado
  53. import asyncio
  54. self.assertIs(tornado.ioloop.TimeoutError, tornado.util.TimeoutError)
  55. self.assertIs(tornado.gen.TimeoutError, tornado.util.TimeoutError)
  56. self.assertIs(tornado.util.TimeoutError, asyncio.TimeoutError)