The silencing of DeprecationWarning was not taking -3 into consideration. Since
[python.git] / Lib / test / test_compileall.py
blob219d85f8982304c691f6c21bfadcfa5fd099e9b3
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 test_support
11 import unittest
14 class CompileallTests(unittest.TestCase):
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')
23 def tearDown(self):
24 shutil.rmtree(self.directory)
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
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())
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))
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')
58 def test_main():
59 test_support.run_unittest(CompileallTests)
62 if __name__ == "__main__":
63 test_main()