blob: 4246b2f5da4a7d94ab6932ebfbb909315852043a [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
R. David Murray650f1472010-11-20 21:18:51 +000010import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000011import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000012import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000013
Barry Warsaw28a691b2010-04-17 00:19:56 +000014from test import support
Brett Cannonbefb14f2009-02-10 02:10:16 +000015
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')
Barry Warsaw28a691b2010-04-17 00:19:56 +000021 self.bc_path = imp.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000022 with open(self.source_path, 'w') as file:
23 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000024 self.source_path2 = os.path.join(self.directory, '_test2.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000025 self.bc_path2 = imp.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000026 shutil.copyfile(self.source_path, self.source_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000027
28 def tearDown(self):
29 shutil.rmtree(self.directory)
30
31 def data(self):
32 with open(self.bc_path, 'rb') as file:
33 data = file.read(8)
34 mtime = int(os.stat(self.source_path).st_mtime)
35 compare = struct.pack('<4sl', imp.get_magic(), mtime)
36 return data, compare
37
38 def recreation_check(self, metadata):
39 """Check that compileall recreates bytecode when the new metadata is
40 used."""
41 if not hasattr(os, 'stat'):
42 return
43 py_compile.compile(self.source_path)
44 self.assertEqual(*self.data())
45 with open(self.bc_path, 'rb') as file:
46 bc = file.read()[len(metadata):]
47 with open(self.bc_path, 'wb') as file:
48 file.write(metadata)
49 file.write(bc)
50 self.assertNotEqual(*self.data())
51 compileall.compile_dir(self.directory, force=False, quiet=True)
52 self.assertTrue(*self.data())
53
54 def test_mtime(self):
55 # Test a change in mtime leads to a new .pyc.
56 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
57
58 def test_magic_number(self):
59 # Test a change in mtime leads to a new .pyc.
60 self.recreation_check(b'\0\0\0\0')
61
Matthias Klosec33b9022010-03-16 00:36:26 +000062 def test_compile_files(self):
63 # Test compiling a single file, and complete directory
64 for fn in (self.bc_path, self.bc_path2):
65 try:
66 os.unlink(fn)
67 except:
68 pass
69 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 self.assertTrue(os.path.isfile(self.bc_path) and
71 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000072 os.unlink(self.bc_path)
73 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000074 self.assertTrue(os.path.isfile(self.bc_path) and
75 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000076 os.unlink(self.bc_path)
77 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000078
Barry Warsawc8a99de2010-04-29 18:43:10 +000079 def test_no_pycache_in_non_package(self):
80 # Bug 8563 reported that __pycache__ directories got created by
81 # compile_file() for non-.py files.
82 data_dir = os.path.join(self.directory, 'data')
83 data_file = os.path.join(data_dir, 'file')
84 os.mkdir(data_dir)
85 # touch data/file
86 with open(data_file, 'w'):
87 pass
88 compileall.compile_file(data_file)
89 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
90
Georg Brandl8334fd92010-12-04 10:26:46 +000091 def test_optimize(self):
92 # make sure compiling with different optimization settings than the
93 # interpreter's creates the correct file names
94 optimize = 1 if __debug__ else 0
95 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
96 cached = imp.cache_from_source(self.source_path,
97 debug_override=not optimize)
98 self.assertTrue(os.path.isfile(cached))
99
Barry Warsaw28a691b2010-04-17 00:19:56 +0000100
Martin v. Löwis4b003072010-03-16 13:19:21 +0000101class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000102 """Issue 6716: compileall should escape source code when printing errors
103 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000104
105 def setUp(self):
106 self.directory = tempfile.mkdtemp()
107 self.source_path = os.path.join(self.directory, '_test.py')
108 with open(self.source_path, 'w', encoding='utf-8') as file:
109 file.write('# -*- coding: utf-8 -*-\n')
110 file.write('print u"\u20ac"\n')
111
112 def tearDown(self):
113 shutil.rmtree(self.directory)
114
115 def test_error(self):
116 try:
117 orig_stdout = sys.stdout
118 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
119 compileall.compile_dir(self.directory)
120 finally:
121 sys.stdout = orig_stdout
122
Barry Warsawc8a99de2010-04-29 18:43:10 +0000123
Barry Warsaw28a691b2010-04-17 00:19:56 +0000124class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000125 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000126
127 def setUp(self):
128 self.addCleanup(self._cleanup)
129 self.directory = tempfile.mkdtemp()
130 self.pkgdir = os.path.join(self.directory, 'foo')
131 os.mkdir(self.pkgdir)
132 # Touch the __init__.py and a package module.
133 with open(os.path.join(self.pkgdir, '__init__.py'), 'w'):
134 pass
135 with open(os.path.join(self.pkgdir, 'bar.py'), 'w'):
136 pass
137 sys.path.insert(0, self.directory)
138
139 def _cleanup(self):
140 support.rmtree(self.directory)
141 assert sys.path[0] == self.directory, 'Missing path'
142 del sys.path[0]
143
Georg Brandl1463a3f2010-10-14 07:42:27 +0000144 # Ensure that the default behavior of compileall's CLI is to create
145 # PEP 3147 pyc/pyo files.
146 for name, ext, switch in [
147 ('normal', 'pyc', []),
148 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000149 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000150 ]:
151 def f(self, ext=ext, switch=switch):
152 retcode = subprocess.call(
153 [sys.executable] + switch +
154 ['-m', 'compileall', '-q', self.pkgdir])
155 self.assertEqual(retcode, 0)
156 # Verify the __pycache__ directory contents.
157 cachedir = os.path.join(self.pkgdir, '__pycache__')
158 self.assertTrue(os.path.exists(cachedir))
159 expected = sorted(base.format(imp.get_tag(), ext) for base in
160 ('__init__.{}.{}', 'bar.{}.{}'))
161 self.assertEqual(sorted(os.listdir(cachedir)), expected)
162 # Make sure there are no .pyc files in the source directory.
163 self.assertFalse([pyc_file for pyc_file in os.listdir(self.pkgdir)
164 if pyc_file.endswith(ext)])
165 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000166
167 def test_legacy_paths(self):
168 # Ensure that with the proper switch, compileall leaves legacy
169 # pyc/pyo files, and no __pycache__ directory.
170 retcode = subprocess.call(
171 (sys.executable, '-m', 'compileall', '-b', '-q', self.pkgdir))
172 self.assertEqual(retcode, 0)
173 # Verify the __pycache__ directory contents.
174 cachedir = os.path.join(self.pkgdir, '__pycache__')
175 self.assertFalse(os.path.exists(cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000176 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000177 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
178
Barry Warsawc04317f2010-04-26 15:59:03 +0000179 def test_multiple_runs(self):
180 # Bug 8527 reported that multiple calls produced empty
181 # __pycache__/__pycache__ directories.
182 retcode = subprocess.call(
183 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
184 self.assertEqual(retcode, 0)
185 # Verify the __pycache__ directory contents.
186 cachedir = os.path.join(self.pkgdir, '__pycache__')
187 self.assertTrue(os.path.exists(cachedir))
188 cachecachedir = os.path.join(cachedir, '__pycache__')
189 self.assertFalse(os.path.exists(cachecachedir))
190 # Call compileall again.
191 retcode = subprocess.call(
192 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
193 self.assertEqual(retcode, 0)
194 self.assertTrue(os.path.exists(cachedir))
195 self.assertFalse(os.path.exists(cachecachedir))
196
R. David Murray650f1472010-11-20 21:18:51 +0000197 def test_force(self):
198 retcode = subprocess.call(
199 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
200 self.assertEqual(retcode, 0)
201 pycpath = imp.cache_from_source(os.path.join(self.pkgdir, 'bar.py'))
202 # set atime/mtime backward to avoid file timestamp resolution issues
203 os.utime(pycpath, (time.time()-60,)*2)
204 access = os.stat(pycpath).st_mtime
205 retcode = subprocess.call(
206 (sys.executable, '-m', 'compileall', '-q', '-f', self.pkgdir))
207 self.assertEqual(retcode, 0)
208 access2 = os.stat(pycpath).st_mtime
209 self.assertNotEqual(access, access2)
210
211 def test_legacy(self):
Éric Araujo31717e82010-11-26 00:39:59 +0000212 # create a new module XXX could rewrite using self.pkgdir
R. David Murray650f1472010-11-20 21:18:51 +0000213 newpackage = os.path.join(self.pkgdir, 'spam')
214 os.mkdir(newpackage)
215 with open(os.path.join(newpackage, '__init__.py'), 'w'):
216 pass
217 with open(os.path.join(newpackage, 'ham.py'), 'w'):
218 pass
219 sourcefile = os.path.join(newpackage, 'ham.py')
220
221 retcode = subprocess.call(
222 (sys.executable, '-m', 'compileall', '-q', '-l', self.pkgdir))
223 self.assertEqual(retcode, 0)
224 self.assertFalse(os.path.exists(imp.cache_from_source(sourcefile)))
225
226 retcode = subprocess.call(
227 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
228 self.assertEqual(retcode, 0)
229 self.assertTrue(os.path.exists(imp.cache_from_source(sourcefile)))
230
231 def test_quiet(self):
Éric Araujo31717e82010-11-26 00:39:59 +0000232 noise = subprocess.check_output(
233 [sys.executable, '-m', 'compileall', self.pkgdir],
234 stderr=subprocess.STDOUT)
235 quiet = subprocess.check_output(
236 [sys.executable, '-m', 'compileall', '-f', '-q', self.pkgdir],
237 stderr=subprocess.STDOUT)
Éric Araujoa491ced2010-11-21 02:19:09 +0000238 self.assertGreater(len(noise), len(quiet))
R. David Murray650f1472010-11-20 21:18:51 +0000239
240 def test_regexp(self):
241 retcode = subprocess.call(
242 (sys.executable, '-m', 'compileall', '-q', '-x', 'bar.*', self.pkgdir))
243 self.assertEqual(retcode, 0)
244
245 sourcefile = os.path.join(self.pkgdir, 'bar.py')
246 self.assertFalse(os.path.exists(imp.cache_from_source(sourcefile)))
247 sourcefile = os.path.join(self.pkgdir, '__init__.py')
248 self.assertTrue(os.path.exists(imp.cache_from_source(sourcefile)))
249
Barry Warsaw28a691b2010-04-17 00:19:56 +0000250
Brett Cannonbefb14f2009-02-10 02:10:16 +0000251def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000252 support.run_unittest(
253 CommandLineTests,
254 CompileallTests,
255 EncodingTest,
256 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000257
258
259if __name__ == "__main__":
260 test_main()