blob: cf58ca6fa71d72b999c0c38ab818c9eac9d34444 [file] [log] [blame]
Martin v. Löwis4b003072010-03-16 13:19:21 +00001import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +00002import compileall
Brett Cannon7822e122013-06-14 23:04:02 -04003import importlib.util
Brett Cannonbefb14f2009-02-10 02:10:16 +00004import os
5import py_compile
6import shutil
7import struct
Barry Warsaw28a691b2010-04-17 00:19:56 +00008import subprocess
Brett Cannon7822e122013-06-14 23:04:02 -04009import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +000010import tempfile
R. David Murray650f1472010-11-20 21:18:51 +000011import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000012import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000013import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
R. David Murray95333e32010-12-14 22:32:50 +000015from test import support, script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000016
17class CompileallTests(unittest.TestCase):
18
19 def setUp(self):
20 self.directory = tempfile.mkdtemp()
21 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040022 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000023 with open(self.source_path, 'w') as file:
24 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000025 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040026 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000027 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000028 self.subdirectory = os.path.join(self.directory, '_subdir')
29 os.mkdir(self.subdirectory)
30 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
31 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000032
33 def tearDown(self):
34 shutil.rmtree(self.directory)
35
36 def data(self):
37 with open(self.bc_path, 'rb') as file:
38 data = file.read(8)
39 mtime = int(os.stat(self.source_path).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -040040 compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000041 return data, compare
42
43 def recreation_check(self, metadata):
44 """Check that compileall recreates bytecode when the new metadata is
45 used."""
46 if not hasattr(os, 'stat'):
47 return
48 py_compile.compile(self.source_path)
49 self.assertEqual(*self.data())
50 with open(self.bc_path, 'rb') as file:
51 bc = file.read()[len(metadata):]
52 with open(self.bc_path, 'wb') as file:
53 file.write(metadata)
54 file.write(bc)
55 self.assertNotEqual(*self.data())
56 compileall.compile_dir(self.directory, force=False, quiet=True)
57 self.assertTrue(*self.data())
58
59 def test_mtime(self):
60 # Test a change in mtime leads to a new .pyc.
Brett Cannon7822e122013-06-14 23:04:02 -040061 self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
62 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000063
64 def test_magic_number(self):
65 # Test a change in mtime leads to a new .pyc.
66 self.recreation_check(b'\0\0\0\0')
67
Matthias Klosec33b9022010-03-16 00:36:26 +000068 def test_compile_files(self):
69 # Test compiling a single file, and complete directory
70 for fn in (self.bc_path, self.bc_path2):
71 try:
72 os.unlink(fn)
73 except:
74 pass
75 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000076 self.assertTrue(os.path.isfile(self.bc_path) and
77 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000078 os.unlink(self.bc_path)
79 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000080 self.assertTrue(os.path.isfile(self.bc_path) and
81 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000082 os.unlink(self.bc_path)
83 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000084
Barry Warsawc8a99de2010-04-29 18:43:10 +000085 def test_no_pycache_in_non_package(self):
86 # Bug 8563 reported that __pycache__ directories got created by
87 # compile_file() for non-.py files.
88 data_dir = os.path.join(self.directory, 'data')
89 data_file = os.path.join(data_dir, 'file')
90 os.mkdir(data_dir)
91 # touch data/file
92 with open(data_file, 'w'):
93 pass
94 compileall.compile_file(data_file)
95 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
96
Georg Brandl8334fd92010-12-04 10:26:46 +000097 def test_optimize(self):
98 # make sure compiling with different optimization settings than the
99 # interpreter's creates the correct file names
100 optimize = 1 if __debug__ else 0
101 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400102 cached = importlib.util.cache_from_source(self.source_path,
103 debug_override=not optimize)
Georg Brandl8334fd92010-12-04 10:26:46 +0000104 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400105 cached2 = importlib.util.cache_from_source(self.source_path2,
106 debug_override=not optimize)
Georg Brandl45438462011-02-07 12:36:54 +0000107 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400108 cached3 = importlib.util.cache_from_source(self.source_path3,
109 debug_override=not optimize)
Georg Brandl45438462011-02-07 12:36:54 +0000110 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000111
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112
Martin v. Löwis4b003072010-03-16 13:19:21 +0000113class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114 """Issue 6716: compileall should escape source code when printing errors
115 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000116
117 def setUp(self):
118 self.directory = tempfile.mkdtemp()
119 self.source_path = os.path.join(self.directory, '_test.py')
120 with open(self.source_path, 'w', encoding='utf-8') as file:
121 file.write('# -*- coding: utf-8 -*-\n')
122 file.write('print u"\u20ac"\n')
123
124 def tearDown(self):
125 shutil.rmtree(self.directory)
126
127 def test_error(self):
128 try:
129 orig_stdout = sys.stdout
130 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
131 compileall.compile_dir(self.directory)
132 finally:
133 sys.stdout = orig_stdout
134
Barry Warsawc8a99de2010-04-29 18:43:10 +0000135
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000137 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000138
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400139 def _get_run_args(self, args):
140 interp_args = ['-S']
141 if sys.flags.optimize:
142 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
143 return interp_args + ['-m', 'compileall'] + list(args)
144
R. David Murray5317e9c2010-12-16 19:08:51 +0000145 def assertRunOK(self, *args, **env_vars):
146 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400147 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000148 self.assertEqual(b'', err)
149 return out
150
R. David Murray5317e9c2010-12-16 19:08:51 +0000151 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000152 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400153 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000154 return rc, out, err
155
156 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400157 path = importlib.util.cache_from_source(fn)
158 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000159
160 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400161 path = importlib.util.cache_from_source(fn)
162 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000163
Barry Warsaw28a691b2010-04-17 00:19:56 +0000164 def setUp(self):
165 self.addCleanup(self._cleanup)
166 self.directory = tempfile.mkdtemp()
167 self.pkgdir = os.path.join(self.directory, 'foo')
168 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000169 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
170 # Create the __init__.py and a package module.
171 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
172 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000173
174 def _cleanup(self):
175 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000176
177 def test_no_args_compiles_path(self):
178 # Note that -l is implied for the no args case.
179 bazfn = script_helper.make_script(self.directory, 'baz', '')
180 self.assertRunOK(PYTHONPATH=self.directory)
181 self.assertCompiled(bazfn)
182 self.assertNotCompiled(self.initfn)
183 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000184
Georg Brandl1463a3f2010-10-14 07:42:27 +0000185 # Ensure that the default behavior of compileall's CLI is to create
186 # PEP 3147 pyc/pyo files.
187 for name, ext, switch in [
188 ('normal', 'pyc', []),
189 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000190 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000191 ]:
192 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000193 script_helper.assert_python_ok(*(switch +
194 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000195 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000196 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400197 expected = sorted(base.format(sys.implementation.cache_tag, ext)
198 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000199 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000200 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000201 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
202 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000203 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000204
205 def test_legacy_paths(self):
206 # Ensure that with the proper switch, compileall leaves legacy
207 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000208 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000209 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000210 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400211 opt = 'c' if __debug__ else 'o'
212 expected = sorted(['__init__.py', '__init__.py' + opt, 'bar.py',
213 'bar.py' + opt])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000214 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
215
Barry Warsawc04317f2010-04-26 15:59:03 +0000216 def test_multiple_runs(self):
217 # Bug 8527 reported that multiple calls produced empty
218 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000219 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000220 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000221 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
222 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000223 self.assertFalse(os.path.exists(cachecachedir))
224 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000225 self.assertRunOK('-q', self.pkgdir)
226 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000227 self.assertFalse(os.path.exists(cachecachedir))
228
R. David Murray650f1472010-11-20 21:18:51 +0000229 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000230 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400231 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000232 # set atime/mtime backward to avoid file timestamp resolution issues
233 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000234 mtime = os.stat(pycpath).st_mtime
235 # without force, no recompilation
236 self.assertRunOK('-q', self.pkgdir)
237 mtime2 = os.stat(pycpath).st_mtime
238 self.assertEqual(mtime, mtime2)
239 # now force it.
240 self.assertRunOK('-q', '-f', self.pkgdir)
241 mtime2 = os.stat(pycpath).st_mtime
242 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000243
R. David Murray95333e32010-12-14 22:32:50 +0000244 def test_recursion_control(self):
245 subpackage = os.path.join(self.pkgdir, 'spam')
246 os.mkdir(subpackage)
247 subinitfn = script_helper.make_script(subpackage, '__init__', '')
248 hamfn = script_helper.make_script(subpackage, 'ham', '')
249 self.assertRunOK('-q', '-l', self.pkgdir)
250 self.assertNotCompiled(subinitfn)
251 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
252 self.assertRunOK('-q', self.pkgdir)
253 self.assertCompiled(subinitfn)
254 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000255
256 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000257 noisy = self.assertRunOK(self.pkgdir)
258 quiet = self.assertRunOK('-q', self.pkgdir)
259 self.assertNotEqual(b'', noisy)
260 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000261
262 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400263 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000264 self.assertNotCompiled(self.barfn)
265 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000266
R. David Murray95333e32010-12-14 22:32:50 +0000267 def test_multiple_dirs(self):
268 pkgdir2 = os.path.join(self.directory, 'foo2')
269 os.mkdir(pkgdir2)
270 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
271 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
272 self.assertRunOK('-q', self.pkgdir, pkgdir2)
273 self.assertCompiled(self.initfn)
274 self.assertCompiled(self.barfn)
275 self.assertCompiled(init2fn)
276 self.assertCompiled(bar2fn)
277
278 def test_d_takes_exactly_one_dir(self):
279 rc, out, err = self.assertRunNotOK('-d', 'foo')
280 self.assertEqual(out, b'')
281 self.assertRegex(err, b'-d')
282 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
283 self.assertEqual(out, b'')
284 self.assertRegex(err, b'-d')
285
286 def test_d_compile_error(self):
287 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
288 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
289 self.assertRegex(out, b'File "dinsdale')
290
291 def test_d_runtime_error(self):
292 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
293 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
294 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400295 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000296 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
297 os.remove(bazfn)
298 rc, out, err = script_helper.assert_python_failure(fn)
299 self.assertRegex(err, b'File "dinsdale')
300
301 def test_include_bad_file(self):
302 rc, out, err = self.assertRunNotOK(
303 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
304 self.assertRegex(out, b'rror.*nosuchfile')
305 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400306 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000307 self.pkgdir_cachedir)))
308
309 def test_include_file_with_arg(self):
310 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
311 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
312 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
313 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
314 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
315 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
316 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
317 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
318 self.assertCompiled(f1)
319 self.assertCompiled(f2)
320 self.assertNotCompiled(f3)
321 self.assertCompiled(f4)
322
323 def test_include_file_no_arg(self):
324 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
325 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
326 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
327 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
328 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
329 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
330 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
331 self.assertNotCompiled(f1)
332 self.assertCompiled(f2)
333 self.assertNotCompiled(f3)
334 self.assertNotCompiled(f4)
335
336 def test_include_on_stdin(self):
337 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
338 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
339 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
340 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400341 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000342 p.stdin.write((f3+os.linesep).encode('ascii'))
343 script_helper.kill_python(p)
344 self.assertNotCompiled(f1)
345 self.assertNotCompiled(f2)
346 self.assertCompiled(f3)
347 self.assertNotCompiled(f4)
348
349 def test_compiles_as_much_as_possible(self):
350 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
351 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
352 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000353 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000354 self.assertNotCompiled(bingfn)
355 self.assertCompiled(self.initfn)
356 self.assertCompiled(self.barfn)
357
R. David Murray5317e9c2010-12-16 19:08:51 +0000358 def test_invalid_arg_produces_message(self):
359 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200360 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000361
Barry Warsaw28a691b2010-04-17 00:19:56 +0000362
Brett Cannonbefb14f2009-02-10 02:10:16 +0000363if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400364 unittest.main()