blob: 49b644876c1f091efab543b7208fe83e5dd2aca3 [file] [log] [blame]
Brett Cannonbefb14f2009-02-10 02:10:16 +00001import compileall
2import imp
3import os
4import py_compile
5import shutil
6import struct
7import sys
8import tempfile
9import time
10from test import support
11import unittest
12
13
14class 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
58def test_main():
59 support.run_unittest(CompileallTests)
60
61
62if __name__ == "__main__":
63 test_main()