test_compileall.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import compileall
  2. import imp
  3. import os
  4. import py_compile
  5. import shutil
  6. import struct
  7. import tempfile
  8. from test import test_support
  9. import unittest
  10. class CompileallTests(unittest.TestCase):
  11. def setUp(self):
  12. self.directory = tempfile.mkdtemp()
  13. self.source_path = os.path.join(self.directory, '_test.py')
  14. self.bc_path = self.source_path + ('c' if __debug__ else 'o')
  15. with open(self.source_path, 'w') as file:
  16. file.write('x = 123\n')
  17. self.source_path2 = os.path.join(self.directory, '_test2.py')
  18. self.bc_path2 = self.source_path2 + ('c' if __debug__ else 'o')
  19. shutil.copyfile(self.source_path, self.source_path2)
  20. def tearDown(self):
  21. shutil.rmtree(self.directory)
  22. def data(self):
  23. with open(self.bc_path, 'rb') as file:
  24. data = file.read(8)
  25. mtime = int(os.stat(self.source_path).st_mtime)
  26. compare = struct.pack('<4sl', imp.get_magic(), mtime)
  27. return data, compare
  28. @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
  29. def recreation_check(self, metadata):
  30. """Check that compileall recreates bytecode when the new metadata is
  31. used."""
  32. py_compile.compile(self.source_path)
  33. self.assertEqual(*self.data())
  34. with open(self.bc_path, 'rb') as file:
  35. bc = file.read()[len(metadata):]
  36. with open(self.bc_path, 'wb') as file:
  37. file.write(metadata)
  38. file.write(bc)
  39. self.assertNotEqual(*self.data())
  40. compileall.compile_dir(self.directory, force=False, quiet=True)
  41. self.assertTrue(*self.data())
  42. def test_mtime(self):
  43. # Test a change in mtime leads to a new .pyc.
  44. self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
  45. def test_magic_number(self):
  46. # Test a change in mtime leads to a new .pyc.
  47. self.recreation_check(b'\0\0\0\0')
  48. def test_compile_files(self):
  49. # Test compiling a single file, and complete directory
  50. for fn in (self.bc_path, self.bc_path2):
  51. try:
  52. os.unlink(fn)
  53. except:
  54. pass
  55. compileall.compile_file(self.source_path, force=False, quiet=True)
  56. self.assertTrue(os.path.isfile(self.bc_path) \
  57. and not os.path.isfile(self.bc_path2))
  58. os.unlink(self.bc_path)
  59. compileall.compile_dir(self.directory, force=False, quiet=True)
  60. self.assertTrue(os.path.isfile(self.bc_path) \
  61. and os.path.isfile(self.bc_path2))
  62. os.unlink(self.bc_path)
  63. os.unlink(self.bc_path2)
  64. def test_main():
  65. test_support.run_unittest(CompileallTests)
  66. if __name__ == "__main__":
  67. test_main()