blob: 2ebcb424095d8b14680c400ada8086178a2c54ba [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 Cannon1e3c3e92015-12-27 13:17:04 -08004import test.test_importlib.util
Brett Cannonbefb14f2009-02-10 02:10:16 +00005import os
Brett Cannon65ed7502015-10-09 15:09:43 -07006import pathlib
Brett Cannonbefb14f2009-02-10 02:10:16 +00007import py_compile
8import shutil
9import struct
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
Petr Viktorin4267c982019-09-26 11:53:51 +020014import errno
Brett Cannonbefb14f2009-02-10 02:10:16 +000015
Brett Cannonf1a8df02014-09-12 10:39:48 -040016from unittest import mock, skipUnless
17try:
18 from concurrent.futures import ProcessPoolExecutor
19 _have_multiprocessing = True
20except ImportError:
21 _have_multiprocessing = False
22
Berker Peksagce643912015-05-06 06:33:17 +030023from test import support
24from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000025
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040026from .test_py_compile import without_source_date_epoch
27from .test_py_compile import SourceDateEpochTestMeta
28
29
30class CompileallTestsBase:
Brett Cannonbefb14f2009-02-10 02:10:16 +000031
32 def setUp(self):
33 self.directory = tempfile.mkdtemp()
34 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040035 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000036 with open(self.source_path, 'w') as file:
37 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000038 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040039 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000040 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000041 self.subdirectory = os.path.join(self.directory, '_subdir')
42 os.mkdir(self.subdirectory)
43 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
44 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000045
46 def tearDown(self):
47 shutil.rmtree(self.directory)
48
Brett Cannon1e3c3e92015-12-27 13:17:04 -080049 def add_bad_source_file(self):
50 self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
51 with open(self.bad_source_path, 'w') as file:
52 file.write('x (\n')
53
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040054 def timestamp_metadata(self):
Brett Cannonbefb14f2009-02-10 02:10:16 +000055 with open(self.bc_path, 'rb') as file:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080056 data = file.read(12)
Brett Cannonbefb14f2009-02-10 02:10:16 +000057 mtime = int(os.stat(self.source_path).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080058 compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000059 return data, compare
60
61 def recreation_check(self, metadata):
62 """Check that compileall recreates bytecode when the new metadata is
63 used."""
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040064 if os.environ.get('SOURCE_DATE_EPOCH'):
65 raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
Brett Cannonbefb14f2009-02-10 02:10:16 +000066 py_compile.compile(self.source_path)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040067 self.assertEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000068 with open(self.bc_path, 'rb') as file:
69 bc = file.read()[len(metadata):]
70 with open(self.bc_path, 'wb') as file:
71 file.write(metadata)
72 file.write(bc)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040073 self.assertNotEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000074 compileall.compile_dir(self.directory, force=False, quiet=True)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040075 self.assertTrue(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000076
77 def test_mtime(self):
78 # Test a change in mtime leads to a new .pyc.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080079 self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
80 0, 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000081
82 def test_magic_number(self):
83 # Test a change in mtime leads to a new .pyc.
84 self.recreation_check(b'\0\0\0\0')
85
Matthias Klosec33b9022010-03-16 00:36:26 +000086 def test_compile_files(self):
87 # Test compiling a single file, and complete directory
88 for fn in (self.bc_path, self.bc_path2):
89 try:
90 os.unlink(fn)
91 except:
92 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -080093 self.assertTrue(compileall.compile_file(self.source_path,
94 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +000095 self.assertTrue(os.path.isfile(self.bc_path) and
96 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000097 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080098 self.assertTrue(compileall.compile_dir(self.directory, force=False,
99 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000100 self.assertTrue(os.path.isfile(self.bc_path) and
101 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000102 os.unlink(self.bc_path)
103 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800104 # Test against bad files
105 self.add_bad_source_file()
106 self.assertFalse(compileall.compile_file(self.bad_source_path,
107 force=False, quiet=2))
108 self.assertFalse(compileall.compile_dir(self.directory,
109 force=False, quiet=2))
110
Berker Peksag812a2b62016-10-01 00:54:18 +0300111 def test_compile_file_pathlike(self):
112 self.assertFalse(os.path.isfile(self.bc_path))
113 # we should also test the output
114 with support.captured_stdout() as stdout:
115 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300116 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300117 self.assertTrue(os.path.isfile(self.bc_path))
118
119 def test_compile_file_pathlike_ddir(self):
120 self.assertFalse(os.path.isfile(self.bc_path))
121 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
122 ddir=pathlib.Path('ddir_path'),
123 quiet=2))
124 self.assertTrue(os.path.isfile(self.bc_path))
125
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800126 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300127 with test.test_importlib.util.import_state(path=[self.directory]):
128 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800129
130 with test.test_importlib.util.import_state(path=[self.directory]):
131 self.add_bad_source_file()
132 self.assertFalse(compileall.compile_path(skip_curdir=False,
133 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000134
Barry Warsawc8a99de2010-04-29 18:43:10 +0000135 def test_no_pycache_in_non_package(self):
136 # Bug 8563 reported that __pycache__ directories got created by
137 # compile_file() for non-.py files.
138 data_dir = os.path.join(self.directory, 'data')
139 data_file = os.path.join(data_dir, 'file')
140 os.mkdir(data_dir)
141 # touch data/file
142 with open(data_file, 'w'):
143 pass
144 compileall.compile_file(data_file)
145 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
146
Georg Brandl8334fd92010-12-04 10:26:46 +0000147 def test_optimize(self):
148 # make sure compiling with different optimization settings than the
149 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400150 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000151 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400152 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400153 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000154 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400155 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400156 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000157 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400158 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400159 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000160 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000161
Berker Peksag812a2b62016-10-01 00:54:18 +0300162 def test_compile_dir_pathlike(self):
163 self.assertFalse(os.path.isfile(self.bc_path))
164 with support.captured_stdout() as stdout:
165 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300166 line = stdout.getvalue().splitlines()[0]
167 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300168 self.assertTrue(os.path.isfile(self.bc_path))
169
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500170 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400171 def test_compile_pool_called(self, pool_mock):
172 compileall.compile_dir(self.directory, quiet=True, workers=5)
173 self.assertTrue(pool_mock.called)
174
175 def test_compile_workers_non_positive(self):
176 with self.assertRaisesRegex(ValueError,
177 "workers must be greater or equal to 0"):
178 compileall.compile_dir(self.directory, workers=-1)
179
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500180 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400181 def test_compile_workers_cpu_count(self, pool_mock):
182 compileall.compile_dir(self.directory, quiet=True, workers=0)
183 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
184
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500185 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400186 @mock.patch('compileall.compile_file')
187 def test_compile_one_worker(self, compile_file_mock, pool_mock):
188 compileall.compile_dir(self.directory, quiet=True)
189 self.assertFalse(pool_mock.called)
190 self.assertTrue(compile_file_mock.called)
191
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500192 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300193 @mock.patch('compileall.compile_file')
194 def test_compile_missing_multiprocessing(self, compile_file_mock):
195 compileall.compile_dir(self.directory, quiet=True, workers=5)
196 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000197
Petr Viktorin4267c982019-09-26 11:53:51 +0200198 def test_compile_dir_maxlevels(self):
Victor Stinnereb1dda22019-10-15 11:26:13 +0200199 # Test the actual impact of maxlevels parameter
200 depth = 3
201 path = self.directory
202 for i in range(1, depth + 1):
203 path = os.path.join(path, f"dir_{i}")
204 source = os.path.join(path, 'script.py')
205 os.mkdir(path)
206 shutil.copyfile(self.source_path, source)
207 pyc_filename = importlib.util.cache_from_source(source)
208
209 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth - 1)
210 self.assertFalse(os.path.isfile(pyc_filename))
211
212 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth)
213 self.assertTrue(os.path.isfile(pyc_filename))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200214
215 def test_strip_only(self):
216 fullpath = ["test", "build", "real", "path"]
217 path = os.path.join(self.directory, *fullpath)
218 os.makedirs(path)
219 script = script_helper.make_script(path, "test", "1 / 0")
220 bc = importlib.util.cache_from_source(script)
221 stripdir = os.path.join(self.directory, *fullpath[:2])
222 compileall.compile_dir(path, quiet=True, stripdir=stripdir)
223 rc, out, err = script_helper.assert_python_failure(bc)
224 expected_in = os.path.join(*fullpath[2:])
225 self.assertIn(
226 expected_in,
227 str(err, encoding=sys.getdefaultencoding())
228 )
229 self.assertNotIn(
230 stripdir,
231 str(err, encoding=sys.getdefaultencoding())
232 )
233
234 def test_prepend_only(self):
235 fullpath = ["test", "build", "real", "path"]
236 path = os.path.join(self.directory, *fullpath)
237 os.makedirs(path)
238 script = script_helper.make_script(path, "test", "1 / 0")
239 bc = importlib.util.cache_from_source(script)
240 prependdir = "/foo"
241 compileall.compile_dir(path, quiet=True, prependdir=prependdir)
242 rc, out, err = script_helper.assert_python_failure(bc)
243 expected_in = os.path.join(prependdir, self.directory, *fullpath)
244 self.assertIn(
245 expected_in,
246 str(err, encoding=sys.getdefaultencoding())
247 )
248
249 def test_strip_and_prepend(self):
250 fullpath = ["test", "build", "real", "path"]
251 path = os.path.join(self.directory, *fullpath)
252 os.makedirs(path)
253 script = script_helper.make_script(path, "test", "1 / 0")
254 bc = importlib.util.cache_from_source(script)
255 stripdir = os.path.join(self.directory, *fullpath[:2])
256 prependdir = "/foo"
257 compileall.compile_dir(path, quiet=True,
258 stripdir=stripdir, prependdir=prependdir)
259 rc, out, err = script_helper.assert_python_failure(bc)
260 expected_in = os.path.join(prependdir, *fullpath[2:])
261 self.assertIn(
262 expected_in,
263 str(err, encoding=sys.getdefaultencoding())
264 )
265 self.assertNotIn(
266 stripdir,
267 str(err, encoding=sys.getdefaultencoding())
268 )
269
270 def test_strip_prepend_and_ddir(self):
271 fullpath = ["test", "build", "real", "path", "ddir"]
272 path = os.path.join(self.directory, *fullpath)
273 os.makedirs(path)
274 script_helper.make_script(path, "test", "1 / 0")
275 with self.assertRaises(ValueError):
276 compileall.compile_dir(path, quiet=True, ddir="/bar",
277 stripdir="/foo", prependdir="/bar")
278
279 def test_multiple_optimization_levels(self):
280 script = script_helper.make_script(self.directory,
281 "test_optimization",
282 "a = 0")
283 bc = []
284 for opt_level in "", 1, 2, 3:
285 bc.append(importlib.util.cache_from_source(script,
286 optimization=opt_level))
287 test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]]
288 for opt_combination in test_combinations:
289 compileall.compile_file(script, quiet=True,
290 optimize=opt_combination)
291 for opt_level in opt_combination:
292 self.assertTrue(os.path.isfile(bc[opt_level]))
293 try:
294 os.unlink(bc[opt_level])
295 except Exception:
296 pass
297
298 @support.skip_unless_symlink
299 def test_ignore_symlink_destination(self):
300 # Create folders for allowed files, symlinks and prohibited area
301 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
302 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
303 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
304 os.makedirs(allowed_path)
305 os.makedirs(symlinks_path)
306 os.makedirs(prohibited_path)
307
308 # Create scripts and symlinks and remember their byte-compiled versions
309 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
310 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
311 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
312 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
313 os.symlink(allowed_script, allowed_symlink)
314 os.symlink(prohibited_script, prohibited_symlink)
315 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
316 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
317
318 compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path)
319
320 self.assertTrue(os.path.isfile(allowed_bc))
321 self.assertFalse(os.path.isfile(prohibited_bc))
322
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400323
324class CompileallTestsWithSourceEpoch(CompileallTestsBase,
325 unittest.TestCase,
326 metaclass=SourceDateEpochTestMeta,
327 source_date_epoch=True):
328 pass
329
330
331class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
332 unittest.TestCase,
333 metaclass=SourceDateEpochTestMeta,
334 source_date_epoch=False):
335 pass
336
337
Martin v. Löwis4b003072010-03-16 13:19:21 +0000338class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000339 """Issue 6716: compileall should escape source code when printing errors
340 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000341
342 def setUp(self):
343 self.directory = tempfile.mkdtemp()
344 self.source_path = os.path.join(self.directory, '_test.py')
345 with open(self.source_path, 'w', encoding='utf-8') as file:
346 file.write('# -*- coding: utf-8 -*-\n')
347 file.write('print u"\u20ac"\n')
348
349 def tearDown(self):
350 shutil.rmtree(self.directory)
351
352 def test_error(self):
353 try:
354 orig_stdout = sys.stdout
355 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
356 compileall.compile_dir(self.directory)
357 finally:
358 sys.stdout = orig_stdout
359
Barry Warsawc8a99de2010-04-29 18:43:10 +0000360
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400361class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000362 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000363
Brett Cannon65ed7502015-10-09 15:09:43 -0700364 @classmethod
365 def setUpClass(cls):
366 for path in filter(os.path.isdir, sys.path):
367 directory_created = False
368 directory = pathlib.Path(path) / '__pycache__'
369 path = directory / 'test.try'
370 try:
371 if not directory.is_dir():
372 directory.mkdir()
373 directory_created = True
374 with path.open('w') as file:
375 file.write('# for test_compileall')
376 except OSError:
377 sys_path_writable = False
378 break
379 finally:
380 support.unlink(str(path))
381 if directory_created:
382 directory.rmdir()
383 else:
384 sys_path_writable = True
385 cls._sys_path_writable = sys_path_writable
386
387 def _skip_if_sys_path_not_writable(self):
388 if not self._sys_path_writable:
389 raise unittest.SkipTest('not all entries on sys.path are writable')
390
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400391 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100392 return [*support.optim_args_from_interpreter_flags(),
393 '-S', '-m', 'compileall',
394 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400395
R. David Murray5317e9c2010-12-16 19:08:51 +0000396 def assertRunOK(self, *args, **env_vars):
397 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400398 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000399 self.assertEqual(b'', err)
400 return out
401
R. David Murray5317e9c2010-12-16 19:08:51 +0000402 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000403 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400404 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000405 return rc, out, err
406
407 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400408 path = importlib.util.cache_from_source(fn)
409 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000410
411 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400412 path = importlib.util.cache_from_source(fn)
413 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000414
Barry Warsaw28a691b2010-04-17 00:19:56 +0000415 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000416 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700417 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000418 self.pkgdir = os.path.join(self.directory, 'foo')
419 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000420 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
421 # Create the __init__.py and a package module.
422 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
423 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000424
R. David Murray5317e9c2010-12-16 19:08:51 +0000425 def test_no_args_compiles_path(self):
426 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700427 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000428 bazfn = script_helper.make_script(self.directory, 'baz', '')
429 self.assertRunOK(PYTHONPATH=self.directory)
430 self.assertCompiled(bazfn)
431 self.assertNotCompiled(self.initfn)
432 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000433
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400434 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500435 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700436 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500437 bazfn = script_helper.make_script(self.directory, 'baz', '')
438 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500439 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500440 # Set atime/mtime backward to avoid file timestamp resolution issues
441 os.utime(pycpath, (time.time()-60,)*2)
442 mtime = os.stat(pycpath).st_mtime
443 # Without force, no recompilation
444 self.assertRunOK(PYTHONPATH=self.directory)
445 mtime2 = os.stat(pycpath).st_mtime
446 self.assertEqual(mtime, mtime2)
447 # Now force it.
448 self.assertRunOK('-f', PYTHONPATH=self.directory)
449 mtime2 = os.stat(pycpath).st_mtime
450 self.assertNotEqual(mtime, mtime2)
451
452 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700453 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500454 script_helper.make_script(self.directory, 'baz', '')
455 noisy = self.assertRunOK(PYTHONPATH=self.directory)
456 self.assertIn(b'Listing ', noisy)
457 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
458 self.assertNotIn(b'Listing ', quiet)
459
Georg Brandl1463a3f2010-10-14 07:42:27 +0000460 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400461 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000462 for name, ext, switch in [
463 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400464 ('optimize', 'opt-1.pyc', ['-O']),
465 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000466 ]:
467 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000468 script_helper.assert_python_ok(*(switch +
469 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000470 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000471 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400472 expected = sorted(base.format(sys.implementation.cache_tag, ext)
473 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000474 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000475 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000476 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
477 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000478 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000479
480 def test_legacy_paths(self):
481 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400482 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000483 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000484 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000485 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400486 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
487 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000488 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
489
Barry Warsawc04317f2010-04-26 15:59:03 +0000490 def test_multiple_runs(self):
491 # Bug 8527 reported that multiple calls produced empty
492 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000493 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000494 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000495 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
496 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000497 self.assertFalse(os.path.exists(cachecachedir))
498 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000499 self.assertRunOK('-q', self.pkgdir)
500 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000501 self.assertFalse(os.path.exists(cachecachedir))
502
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400503 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000504 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000505 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400506 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000507 # set atime/mtime backward to avoid file timestamp resolution issues
508 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000509 mtime = os.stat(pycpath).st_mtime
510 # without force, no recompilation
511 self.assertRunOK('-q', self.pkgdir)
512 mtime2 = os.stat(pycpath).st_mtime
513 self.assertEqual(mtime, mtime2)
514 # now force it.
515 self.assertRunOK('-q', '-f', self.pkgdir)
516 mtime2 = os.stat(pycpath).st_mtime
517 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000518
R. David Murray95333e32010-12-14 22:32:50 +0000519 def test_recursion_control(self):
520 subpackage = os.path.join(self.pkgdir, 'spam')
521 os.mkdir(subpackage)
522 subinitfn = script_helper.make_script(subpackage, '__init__', '')
523 hamfn = script_helper.make_script(subpackage, 'ham', '')
524 self.assertRunOK('-q', '-l', self.pkgdir)
525 self.assertNotCompiled(subinitfn)
526 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
527 self.assertRunOK('-q', self.pkgdir)
528 self.assertCompiled(subinitfn)
529 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000530
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500531 def test_recursion_limit(self):
532 subpackage = os.path.join(self.pkgdir, 'spam')
533 subpackage2 = os.path.join(subpackage, 'ham')
534 subpackage3 = os.path.join(subpackage2, 'eggs')
535 for pkg in (subpackage, subpackage2, subpackage3):
536 script_helper.make_pkg(pkg)
537
538 subinitfn = os.path.join(subpackage, '__init__.py')
539 hamfn = script_helper.make_script(subpackage, 'ham', '')
540 spamfn = script_helper.make_script(subpackage2, 'spam', '')
541 eggfn = script_helper.make_script(subpackage3, 'egg', '')
542
543 self.assertRunOK('-q', '-r 0', self.pkgdir)
544 self.assertNotCompiled(subinitfn)
545 self.assertFalse(
546 os.path.exists(os.path.join(subpackage, '__pycache__')))
547
548 self.assertRunOK('-q', '-r 1', self.pkgdir)
549 self.assertCompiled(subinitfn)
550 self.assertCompiled(hamfn)
551 self.assertNotCompiled(spamfn)
552
553 self.assertRunOK('-q', '-r 2', self.pkgdir)
554 self.assertCompiled(subinitfn)
555 self.assertCompiled(hamfn)
556 self.assertCompiled(spamfn)
557 self.assertNotCompiled(eggfn)
558
559 self.assertRunOK('-q', '-r 5', self.pkgdir)
560 self.assertCompiled(subinitfn)
561 self.assertCompiled(hamfn)
562 self.assertCompiled(spamfn)
563 self.assertCompiled(eggfn)
564
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200565 @support.skip_unless_symlink
566 def test_symlink_loop(self):
567 # Currently, compileall ignores symlinks to directories.
568 # If that limitation is ever lifted, it should protect against
569 # recursion in symlink loops.
570 pkg = os.path.join(self.pkgdir, 'spam')
571 script_helper.make_pkg(pkg)
572 os.symlink('.', os.path.join(pkg, 'evil'))
573 os.symlink('.', os.path.join(pkg, 'evil2'))
574 self.assertRunOK('-q', self.pkgdir)
575 self.assertCompiled(os.path.join(
576 self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py'
577 ))
578
R. David Murray650f1472010-11-20 21:18:51 +0000579 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000580 noisy = self.assertRunOK(self.pkgdir)
581 quiet = self.assertRunOK('-q', self.pkgdir)
582 self.assertNotEqual(b'', noisy)
583 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000584
Berker Peksag6554b862014-10-15 11:10:57 +0300585 def test_silent(self):
586 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
587 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
588 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
589 self.assertNotEqual(b'', quiet)
590 self.assertEqual(b'', silent)
591
R. David Murray650f1472010-11-20 21:18:51 +0000592 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400593 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000594 self.assertNotCompiled(self.barfn)
595 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000596
R. David Murray95333e32010-12-14 22:32:50 +0000597 def test_multiple_dirs(self):
598 pkgdir2 = os.path.join(self.directory, 'foo2')
599 os.mkdir(pkgdir2)
600 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
601 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
602 self.assertRunOK('-q', self.pkgdir, pkgdir2)
603 self.assertCompiled(self.initfn)
604 self.assertCompiled(self.barfn)
605 self.assertCompiled(init2fn)
606 self.assertCompiled(bar2fn)
607
R. David Murray95333e32010-12-14 22:32:50 +0000608 def test_d_compile_error(self):
609 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
610 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
611 self.assertRegex(out, b'File "dinsdale')
612
613 def test_d_runtime_error(self):
614 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
615 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
616 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400617 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000618 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
619 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200620 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000621 self.assertRegex(err, b'File "dinsdale')
622
623 def test_include_bad_file(self):
624 rc, out, err = self.assertRunNotOK(
625 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
626 self.assertRegex(out, b'rror.*nosuchfile')
627 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400628 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000629 self.pkgdir_cachedir)))
630
631 def test_include_file_with_arg(self):
632 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
633 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
634 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
635 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
636 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
637 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
638 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
639 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
640 self.assertCompiled(f1)
641 self.assertCompiled(f2)
642 self.assertNotCompiled(f3)
643 self.assertCompiled(f4)
644
645 def test_include_file_no_arg(self):
646 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
647 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
648 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
649 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
650 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
651 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
652 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
653 self.assertNotCompiled(f1)
654 self.assertCompiled(f2)
655 self.assertNotCompiled(f3)
656 self.assertNotCompiled(f4)
657
658 def test_include_on_stdin(self):
659 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
660 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
661 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
662 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400663 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000664 p.stdin.write((f3+os.linesep).encode('ascii'))
665 script_helper.kill_python(p)
666 self.assertNotCompiled(f1)
667 self.assertNotCompiled(f2)
668 self.assertCompiled(f3)
669 self.assertNotCompiled(f4)
670
671 def test_compiles_as_much_as_possible(self):
672 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
673 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
674 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000675 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000676 self.assertNotCompiled(bingfn)
677 self.assertCompiled(self.initfn)
678 self.assertCompiled(self.barfn)
679
R. David Murray5317e9c2010-12-16 19:08:51 +0000680 def test_invalid_arg_produces_message(self):
681 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200682 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000683
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800684 def test_pyc_invalidation_mode(self):
685 script_helper.make_script(self.pkgdir, 'f1', '')
686 pyc = importlib.util.cache_from_source(
687 os.path.join(self.pkgdir, 'f1.py'))
688 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
689 with open(pyc, 'rb') as fp:
690 data = fp.read()
691 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
692 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
693 with open(pyc, 'rb') as fp:
694 data = fp.read()
695 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
696
Brett Cannonf1a8df02014-09-12 10:39:48 -0400697 @skipUnless(_have_multiprocessing, "requires multiprocessing")
698 def test_workers(self):
699 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
700 files = []
701 for suffix in range(5):
702 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
703 os.mkdir(pkgdir)
704 fn = script_helper.make_script(pkgdir, '__init__', '')
705 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
706
707 self.assertRunOK(self.directory, '-j', '0')
708 self.assertCompiled(bar2fn)
709 for file in files:
710 self.assertCompiled(file)
711
712 @mock.patch('compileall.compile_dir')
713 def test_workers_available_cores(self, compile_dir):
714 with mock.patch("sys.argv",
715 new=[sys.executable, self.directory, "-j0"]):
716 compileall.main()
717 self.assertTrue(compile_dir.called)
Antoine Pitrou1a2dd822019-05-15 23:45:18 +0200718 self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400719
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200720 def test_strip_and_prepend(self):
721 fullpath = ["test", "build", "real", "path"]
722 path = os.path.join(self.directory, *fullpath)
723 os.makedirs(path)
724 script = script_helper.make_script(path, "test", "1 / 0")
725 bc = importlib.util.cache_from_source(script)
726 stripdir = os.path.join(self.directory, *fullpath[:2])
727 prependdir = "/foo"
728 self.assertRunOK("-s", stripdir, "-p", prependdir, path)
729 rc, out, err = script_helper.assert_python_failure(bc)
730 expected_in = os.path.join(prependdir, *fullpath[2:])
731 self.assertIn(
732 expected_in,
733 str(err, encoding=sys.getdefaultencoding())
734 )
735 self.assertNotIn(
736 stripdir,
737 str(err, encoding=sys.getdefaultencoding())
738 )
739
740 def test_multiple_optimization_levels(self):
741 path = os.path.join(self.directory, "optimizations")
742 os.makedirs(path)
743 script = script_helper.make_script(path,
744 "test_optimization",
745 "a = 0")
746 bc = []
747 for opt_level in "", 1, 2, 3:
748 bc.append(importlib.util.cache_from_source(script,
749 optimization=opt_level))
750 test_combinations = [["0", "1"],
751 ["1", "2"],
752 ["0", "2"],
753 ["0", "1", "2"]]
754 for opt_combination in test_combinations:
755 self.assertRunOK(path, *("-o" + str(n) for n in opt_combination))
756 for opt_level in opt_combination:
757 self.assertTrue(os.path.isfile(bc[int(opt_level)]))
758 try:
759 os.unlink(bc[opt_level])
760 except Exception:
761 pass
762
763 @support.skip_unless_symlink
764 def test_ignore_symlink_destination(self):
765 # Create folders for allowed files, symlinks and prohibited area
766 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
767 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
768 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
769 os.makedirs(allowed_path)
770 os.makedirs(symlinks_path)
771 os.makedirs(prohibited_path)
772
773 # Create scripts and symlinks and remember their byte-compiled versions
774 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
775 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
776 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
777 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
778 os.symlink(allowed_script, allowed_symlink)
779 os.symlink(prohibited_script, prohibited_symlink)
780 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
781 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
782
783 self.assertRunOK(symlinks_path, "-e", allowed_path)
784
785 self.assertTrue(os.path.isfile(allowed_bc))
786 self.assertFalse(os.path.isfile(prohibited_bc))
787
Barry Warsaw28a691b2010-04-17 00:19:56 +0000788
Min ho Kimc4cacc82019-07-31 08:16:13 +1000789class CommandLineTestsWithSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400790 unittest.TestCase,
791 metaclass=SourceDateEpochTestMeta,
792 source_date_epoch=True):
793 pass
794
795
Min ho Kimc4cacc82019-07-31 08:16:13 +1000796class CommandLineTestsNoSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400797 unittest.TestCase,
798 metaclass=SourceDateEpochTestMeta,
799 source_date_epoch=False):
800 pass
801
802
803
Brett Cannonbefb14f2009-02-10 02:10:16 +0000804if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400805 unittest.main()