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