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