blob: fe1dcf7a723dc91aaaac14a1bd7548ddd9171f44 [file] [log] [blame]
Martin v. Löwise96ac3a2010-03-21 22:02:42 +00001import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +00002import compileall
3import imp
4import os
5import py_compile
6import shutil
7import struct
8import sys
9import tempfile
10import time
11from test import support
12import unittest
Martin v. Löwise96ac3a2010-03-21 22:02:42 +000013import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
15
16class CompileallTests(unittest.TestCase):
17
18 def setUp(self):
19 self.directory = tempfile.mkdtemp()
20 self.source_path = os.path.join(self.directory, '_test.py')
21 self.bc_path = self.source_path + ('c' if __debug__ else 'o')
22 with open(self.source_path, 'w') as file:
23 file.write('x = 123\n')
24
25 def tearDown(self):
26 shutil.rmtree(self.directory)
27
28 def data(self):
29 with open(self.bc_path, 'rb') as file:
30 data = file.read(8)
31 mtime = int(os.stat(self.source_path).st_mtime)
32 compare = struct.pack('<4sl', imp.get_magic(), mtime)
33 return data, compare
34
35 def recreation_check(self, metadata):
36 """Check that compileall recreates bytecode when the new metadata is
37 used."""
38 if not hasattr(os, 'stat'):
39 return
40 py_compile.compile(self.source_path)
41 self.assertEqual(*self.data())
42 with open(self.bc_path, 'rb') as file:
43 bc = file.read()[len(metadata):]
44 with open(self.bc_path, 'wb') as file:
45 file.write(metadata)
46 file.write(bc)
47 self.assertNotEqual(*self.data())
48 compileall.compile_dir(self.directory, force=False, quiet=True)
49 self.assertTrue(*self.data())
50
51 def test_mtime(self):
52 # Test a change in mtime leads to a new .pyc.
53 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
54
55 def test_magic_number(self):
56 # Test a change in mtime leads to a new .pyc.
57 self.recreation_check(b'\0\0\0\0')
58
59
Martin v. Löwise96ac3a2010-03-21 22:02:42 +000060class EncodingTest(unittest.TestCase):
61 'Issue 6716: compileall should escape source code when printing errors to stdout.'
62
63 def setUp(self):
64 self.directory = tempfile.mkdtemp()
65 self.source_path = os.path.join(self.directory, '_test.py')
66 with open(self.source_path, 'w', encoding='utf-8') as file:
67 file.write('# -*- coding: utf-8 -*-\n')
68 file.write('print u"\u20ac"\n')
69
70 def tearDown(self):
71 shutil.rmtree(self.directory)
72
73 def test_error(self):
74 try:
75 orig_stdout = sys.stdout
76 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
77 compileall.compile_dir(self.directory)
78 finally:
79 sys.stdout = orig_stdout
80
Brett Cannonbefb14f2009-02-10 02:10:16 +000081def test_main():
Martin v. Löwise96ac3a2010-03-21 22:02:42 +000082 support.run_unittest(CompileallTests,
83 EncodingTest)
Brett Cannonbefb14f2009-02-10 02:10:16 +000084
85
86if __name__ == "__main__":
87 test_main()