blob: 8b345873906cac187b66de2c68fa8d331794037d [file] [log] [blame]
Martin v. Löwis4b003072010-03-16 13:19:21 +00001import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +00002import compileall
3import imp
4import os
5import py_compile
6import shutil
7import struct
Barry Warsaw28a691b2010-04-17 00:19:56 +00008import subprocess
Brett Cannonbefb14f2009-02-10 02:10:16 +00009import tempfile
Brett Cannonbefb14f2009-02-10 02:10:16 +000010import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000011import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000012
Barry Warsaw28a691b2010-04-17 00:19:56 +000013from test import support
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
15class CompileallTests(unittest.TestCase):
16
17 def setUp(self):
18 self.directory = tempfile.mkdtemp()
19 self.source_path = os.path.join(self.directory, '_test.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000020 self.bc_path = imp.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000021 with open(self.source_path, 'w') as file:
22 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000023 self.source_path2 = os.path.join(self.directory, '_test2.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000024 self.bc_path2 = imp.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000025 shutil.copyfile(self.source_path, self.source_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000026
27 def tearDown(self):
28 shutil.rmtree(self.directory)
29
30 def data(self):
31 with open(self.bc_path, 'rb') as file:
32 data = file.read(8)
33 mtime = int(os.stat(self.source_path).st_mtime)
34 compare = struct.pack('<4sl', imp.get_magic(), mtime)
35 return data, compare
36
37 def recreation_check(self, metadata):
38 """Check that compileall recreates bytecode when the new metadata is
39 used."""
40 if not hasattr(os, 'stat'):
41 return
42 py_compile.compile(self.source_path)
43 self.assertEqual(*self.data())
44 with open(self.bc_path, 'rb') as file:
45 bc = file.read()[len(metadata):]
46 with open(self.bc_path, 'wb') as file:
47 file.write(metadata)
48 file.write(bc)
49 self.assertNotEqual(*self.data())
50 compileall.compile_dir(self.directory, force=False, quiet=True)
51 self.assertTrue(*self.data())
52
53 def test_mtime(self):
54 # Test a change in mtime leads to a new .pyc.
55 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
56
57 def test_magic_number(self):
58 # Test a change in mtime leads to a new .pyc.
59 self.recreation_check(b'\0\0\0\0')
60
Matthias Klosec33b9022010-03-16 00:36:26 +000061 def test_compile_files(self):
62 # Test compiling a single file, and complete directory
63 for fn in (self.bc_path, self.bc_path2):
64 try:
65 os.unlink(fn)
66 except:
67 pass
68 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000069 self.assertTrue(os.path.isfile(self.bc_path) and
70 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000071 os.unlink(self.bc_path)
72 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000073 self.assertTrue(os.path.isfile(self.bc_path) and
74 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000075 os.unlink(self.bc_path)
76 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000077
Barry Warsaw28a691b2010-04-17 00:19:56 +000078
Martin v. Löwis4b003072010-03-16 13:19:21 +000079class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +000080 """Issue 6716: compileall should escape source code when printing errors
81 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +000082
83 def setUp(self):
84 self.directory = tempfile.mkdtemp()
85 self.source_path = os.path.join(self.directory, '_test.py')
86 with open(self.source_path, 'w', encoding='utf-8') as file:
87 file.write('# -*- coding: utf-8 -*-\n')
88 file.write('print u"\u20ac"\n')
89
90 def tearDown(self):
91 shutil.rmtree(self.directory)
92
93 def test_error(self):
94 try:
95 orig_stdout = sys.stdout
96 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
97 compileall.compile_dir(self.directory)
98 finally:
99 sys.stdout = orig_stdout
100
Barry Warsaw28a691b2010-04-17 00:19:56 +0000101class CommandLineTests(unittest.TestCase):
102 """Test some aspects of compileall's CLI."""
103
104 def setUp(self):
105 self.addCleanup(self._cleanup)
106 self.directory = tempfile.mkdtemp()
107 self.pkgdir = os.path.join(self.directory, 'foo')
108 os.mkdir(self.pkgdir)
109 # Touch the __init__.py and a package module.
110 with open(os.path.join(self.pkgdir, '__init__.py'), 'w'):
111 pass
112 with open(os.path.join(self.pkgdir, 'bar.py'), 'w'):
113 pass
114 sys.path.insert(0, self.directory)
115
116 def _cleanup(self):
117 support.rmtree(self.directory)
118 assert sys.path[0] == self.directory, 'Missing path'
119 del sys.path[0]
120
121 def test_pep3147_paths(self):
122 # Ensure that the default behavior of compileall's CLI is to create
123 # PEP 3147 pyc/pyo files.
124 retcode = subprocess.call(
125 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
126 self.assertEqual(retcode, 0)
127 # Verify the __pycache__ directory contents.
128 cachedir = os.path.join(self.pkgdir, '__pycache__')
129 self.assertTrue(os.path.exists(cachedir))
130 ext = ('pyc' if __debug__ else 'pyo')
131 expected = sorted(base.format(imp.get_tag(), ext) for base in
132 ('__init__.{}.{}', 'bar.{}.{}'))
133 self.assertEqual(sorted(os.listdir(cachedir)), expected)
134 # Make sure there are no .pyc files in the source directory.
135 self.assertFalse([pyc_file for pyc_file in os.listdir(self.pkgdir)
136 if pyc_file.endswith(ext)])
137
138 def test_legacy_paths(self):
139 # Ensure that with the proper switch, compileall leaves legacy
140 # pyc/pyo files, and no __pycache__ directory.
141 retcode = subprocess.call(
142 (sys.executable, '-m', 'compileall', '-b', '-q', self.pkgdir))
143 self.assertEqual(retcode, 0)
144 # Verify the __pycache__ directory contents.
145 cachedir = os.path.join(self.pkgdir, '__pycache__')
146 self.assertFalse(os.path.exists(cachedir))
147 ext = ('pyc' if __debug__ else 'pyo')
148 expected = [base.format(ext) for base in ('__init__.{}', 'bar.{}')]
149 expected.extend(['__init__.py', 'bar.py'])
150 expected.sort()
151 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
152
153
Brett Cannonbefb14f2009-02-10 02:10:16 +0000154def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000155 support.run_unittest(
156 CommandLineTests,
157 CompileallTests,
158 EncodingTest,
159 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000160
161
162if __name__ == "__main__":
163 test_main()