blob: 19890b5c6edab6ca65911757f3cd519c4a6d91a3 [file] [log] [blame]
Brett Cannon28d10882009-02-10 02:07:38 +00001import compileall
2import imp
3import os
4import py_compile
5import shutil
6import struct
Brett Cannon28d10882009-02-10 02:07:38 +00007import tempfile
Brett Cannon28d10882009-02-10 02:07:38 +00008from test import test_support
9import unittest
10
11
12class 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
56def test_main():
57 test_support.run_unittest(CompileallTests)
58
59
60if __name__ == "__main__":
61 test_main()