test_frozen.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Basic test of the frozen module (source is in Python/frozen.c)."""
  2. # The Python/frozen.c source code contains a marshalled Python module
  3. # and therefore depends on the marshal format as well as the bytecode
  4. # format. If those formats have been changed then frozen.c needs to be
  5. # updated.
  6. #
  7. # The test_importlib also tests this module but because those tests
  8. # are much more complicated, it might be unclear why they are failing.
  9. # Invalid marshalled data in frozen.c could case the interpreter to
  10. # crash when __hello__ is imported.
  11. import importlib.machinery
  12. import sys
  13. import unittest
  14. from test.support import captured_stdout, import_helper
  15. class TestFrozen(unittest.TestCase):
  16. def test_frozen(self):
  17. name = '__hello__'
  18. if name in sys.modules:
  19. del sys.modules[name]
  20. with import_helper.frozen_modules():
  21. import __hello__
  22. with captured_stdout() as out:
  23. __hello__.main()
  24. self.assertEqual(out.getvalue(), 'Hello world!\n')
  25. def test_frozen_submodule_in_unfrozen_package(self):
  26. with import_helper.CleanImport('__phello__', '__phello__.spam'):
  27. with import_helper.frozen_modules(enabled=False):
  28. import __phello__
  29. with import_helper.frozen_modules(enabled=True):
  30. import __phello__.spam as spam
  31. self.assertIs(spam, __phello__.spam)
  32. self.assertIsNot(__phello__.__spec__.loader,
  33. importlib.machinery.FrozenImporter)
  34. self.assertIs(spam.__spec__.loader,
  35. importlib.machinery.FrozenImporter)
  36. def test_unfrozen_submodule_in_frozen_package(self):
  37. with import_helper.CleanImport('__phello__', '__phello__.spam'):
  38. with import_helper.frozen_modules(enabled=True):
  39. import __phello__
  40. with import_helper.frozen_modules(enabled=False):
  41. import __phello__.spam as spam
  42. self.assertIs(spam, __phello__.spam)
  43. self.assertIs(__phello__.__spec__.loader,
  44. importlib.machinery.FrozenImporter)
  45. self.assertIsNot(spam.__spec__.loader,
  46. importlib.machinery.FrozenImporter)
  47. if __name__ == '__main__':
  48. unittest.main()