blob: af885c51224064eb855b858be4c4e203127b8291 [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
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
Brett Cannonf1a8df02014-09-12 10:39:48 -040015from unittest import mock, skipUnless
16try:
17 from concurrent.futures import ProcessPoolExecutor
18 _have_multiprocessing = True
19except ImportError:
20 _have_multiprocessing = False
21
Berker Peksagce643912015-05-06 06:33:17 +030022from test import support
23from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000024
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040025from .test_py_compile import without_source_date_epoch
26from .test_py_compile import SourceDateEpochTestMeta
27
28
29class CompileallTestsBase:
Brett Cannonbefb14f2009-02-10 02:10:16 +000030
31 def setUp(self):
32 self.directory = tempfile.mkdtemp()
33 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040034 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000035 with open(self.source_path, 'w') as file:
36 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000037 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040038 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000039 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000040 self.subdirectory = os.path.join(self.directory, '_subdir')
41 os.mkdir(self.subdirectory)
42 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
43 shutil.copyfile(self.source_path, self.source_path3)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020044 many_directories = [str(number) for number in range(1, 100)]
45 self.long_path = os.path.join(self.directory,
46 "long",
47 *many_directories)
48 os.makedirs(self.long_path)
49 self.source_path_long = os.path.join(self.long_path, '_test4.py')
50 shutil.copyfile(self.source_path, self.source_path_long)
51 self.bc_path_long = importlib.util.cache_from_source(
52 self.source_path_long
53 )
Brett Cannonbefb14f2009-02-10 02:10:16 +000054
55 def tearDown(self):
56 shutil.rmtree(self.directory)
57
Brett Cannon1e3c3e92015-12-27 13:17:04 -080058 def add_bad_source_file(self):
59 self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
60 with open(self.bad_source_path, 'w') as file:
61 file.write('x (\n')
62
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040063 def timestamp_metadata(self):
Brett Cannonbefb14f2009-02-10 02:10:16 +000064 with open(self.bc_path, 'rb') as file:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080065 data = file.read(12)
Brett Cannonbefb14f2009-02-10 02:10:16 +000066 mtime = int(os.stat(self.source_path).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080067 compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000068 return data, compare
69
70 def recreation_check(self, metadata):
71 """Check that compileall recreates bytecode when the new metadata is
72 used."""
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040073 if os.environ.get('SOURCE_DATE_EPOCH'):
74 raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
Brett Cannonbefb14f2009-02-10 02:10:16 +000075 py_compile.compile(self.source_path)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040076 self.assertEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000077 with open(self.bc_path, 'rb') as file:
78 bc = file.read()[len(metadata):]
79 with open(self.bc_path, 'wb') as file:
80 file.write(metadata)
81 file.write(bc)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040082 self.assertNotEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000083 compileall.compile_dir(self.directory, force=False, quiet=True)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040084 self.assertTrue(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000085
86 def test_mtime(self):
87 # Test a change in mtime leads to a new .pyc.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080088 self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
89 0, 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000090
91 def test_magic_number(self):
92 # Test a change in mtime leads to a new .pyc.
93 self.recreation_check(b'\0\0\0\0')
94
Matthias Klosec33b9022010-03-16 00:36:26 +000095 def test_compile_files(self):
96 # Test compiling a single file, and complete directory
97 for fn in (self.bc_path, self.bc_path2):
98 try:
99 os.unlink(fn)
100 except:
101 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800102 self.assertTrue(compileall.compile_file(self.source_path,
103 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000104 self.assertTrue(os.path.isfile(self.bc_path) and
105 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000106 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800107 self.assertTrue(compileall.compile_dir(self.directory, force=False,
108 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000109 self.assertTrue(os.path.isfile(self.bc_path) and
110 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000111 os.unlink(self.bc_path)
112 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800113 # Test against bad files
114 self.add_bad_source_file()
115 self.assertFalse(compileall.compile_file(self.bad_source_path,
116 force=False, quiet=2))
117 self.assertFalse(compileall.compile_dir(self.directory,
118 force=False, quiet=2))
119
Berker Peksag812a2b62016-10-01 00:54:18 +0300120 def test_compile_file_pathlike(self):
121 self.assertFalse(os.path.isfile(self.bc_path))
122 # we should also test the output
123 with support.captured_stdout() as stdout:
124 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300125 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300126 self.assertTrue(os.path.isfile(self.bc_path))
127
128 def test_compile_file_pathlike_ddir(self):
129 self.assertFalse(os.path.isfile(self.bc_path))
130 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
131 ddir=pathlib.Path('ddir_path'),
132 quiet=2))
133 self.assertTrue(os.path.isfile(self.bc_path))
134
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800135 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300136 with test.test_importlib.util.import_state(path=[self.directory]):
137 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800138
139 with test.test_importlib.util.import_state(path=[self.directory]):
140 self.add_bad_source_file()
141 self.assertFalse(compileall.compile_path(skip_curdir=False,
142 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000143
Barry Warsawc8a99de2010-04-29 18:43:10 +0000144 def test_no_pycache_in_non_package(self):
145 # Bug 8563 reported that __pycache__ directories got created by
146 # compile_file() for non-.py files.
147 data_dir = os.path.join(self.directory, 'data')
148 data_file = os.path.join(data_dir, 'file')
149 os.mkdir(data_dir)
150 # touch data/file
151 with open(data_file, 'w'):
152 pass
153 compileall.compile_file(data_file)
154 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
155
Georg Brandl8334fd92010-12-04 10:26:46 +0000156 def test_optimize(self):
157 # make sure compiling with different optimization settings than the
158 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400159 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000160 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400161 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400162 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400164 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400165 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000166 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400167 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400168 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000169 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000170
Berker Peksag812a2b62016-10-01 00:54:18 +0300171 def test_compile_dir_pathlike(self):
172 self.assertFalse(os.path.isfile(self.bc_path))
173 with support.captured_stdout() as stdout:
174 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300175 line = stdout.getvalue().splitlines()[0]
176 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300177 self.assertTrue(os.path.isfile(self.bc_path))
178
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500179 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400180 def test_compile_pool_called(self, pool_mock):
181 compileall.compile_dir(self.directory, quiet=True, workers=5)
182 self.assertTrue(pool_mock.called)
183
184 def test_compile_workers_non_positive(self):
185 with self.assertRaisesRegex(ValueError,
186 "workers must be greater or equal to 0"):
187 compileall.compile_dir(self.directory, workers=-1)
188
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500189 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400190 def test_compile_workers_cpu_count(self, pool_mock):
191 compileall.compile_dir(self.directory, quiet=True, workers=0)
192 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
193
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500194 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400195 @mock.patch('compileall.compile_file')
196 def test_compile_one_worker(self, compile_file_mock, pool_mock):
197 compileall.compile_dir(self.directory, quiet=True)
198 self.assertFalse(pool_mock.called)
199 self.assertTrue(compile_file_mock.called)
200
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500201 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300202 @mock.patch('compileall.compile_file')
203 def test_compile_missing_multiprocessing(self, compile_file_mock):
204 compileall.compile_dir(self.directory, quiet=True, workers=5)
205 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000206
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200207 def text_compile_dir_maxlevels(self):
208 # Test the actual impact of maxlevels attr
209 compileall.compile_dir(os.path.join(self.directory, "long"),
210 maxlevels=10, quiet=True)
211 self.assertFalse(os.path.isfile(self.bc_path_long))
212 compileall.compile_dir(os.path.join(self.directory, "long"),
213 maxlevels=110, quiet=True)
214 self.assertTrue(os.path.isfile(self.bc_path_long))
215
216 def test_strip_only(self):
217 fullpath = ["test", "build", "real", "path"]
218 path = os.path.join(self.directory, *fullpath)
219 os.makedirs(path)
220 script = script_helper.make_script(path, "test", "1 / 0")
221 bc = importlib.util.cache_from_source(script)
222 stripdir = os.path.join(self.directory, *fullpath[:2])
223 compileall.compile_dir(path, quiet=True, stripdir=stripdir)
224 rc, out, err = script_helper.assert_python_failure(bc)
225 expected_in = os.path.join(*fullpath[2:])
226 self.assertIn(
227 expected_in,
228 str(err, encoding=sys.getdefaultencoding())
229 )
230 self.assertNotIn(
231 stripdir,
232 str(err, encoding=sys.getdefaultencoding())
233 )
234
235 def test_prepend_only(self):
236 fullpath = ["test", "build", "real", "path"]
237 path = os.path.join(self.directory, *fullpath)
238 os.makedirs(path)
239 script = script_helper.make_script(path, "test", "1 / 0")
240 bc = importlib.util.cache_from_source(script)
241 prependdir = "/foo"
242 compileall.compile_dir(path, quiet=True, prependdir=prependdir)
243 rc, out, err = script_helper.assert_python_failure(bc)
244 expected_in = os.path.join(prependdir, self.directory, *fullpath)
245 self.assertIn(
246 expected_in,
247 str(err, encoding=sys.getdefaultencoding())
248 )
249
250 def test_strip_and_prepend(self):
251 fullpath = ["test", "build", "real", "path"]
252 path = os.path.join(self.directory, *fullpath)
253 os.makedirs(path)
254 script = script_helper.make_script(path, "test", "1 / 0")
255 bc = importlib.util.cache_from_source(script)
256 stripdir = os.path.join(self.directory, *fullpath[:2])
257 prependdir = "/foo"
258 compileall.compile_dir(path, quiet=True,
259 stripdir=stripdir, prependdir=prependdir)
260 rc, out, err = script_helper.assert_python_failure(bc)
261 expected_in = os.path.join(prependdir, *fullpath[2:])
262 self.assertIn(
263 expected_in,
264 str(err, encoding=sys.getdefaultencoding())
265 )
266 self.assertNotIn(
267 stripdir,
268 str(err, encoding=sys.getdefaultencoding())
269 )
270
271 def test_strip_prepend_and_ddir(self):
272 fullpath = ["test", "build", "real", "path", "ddir"]
273 path = os.path.join(self.directory, *fullpath)
274 os.makedirs(path)
275 script_helper.make_script(path, "test", "1 / 0")
276 with self.assertRaises(ValueError):
277 compileall.compile_dir(path, quiet=True, ddir="/bar",
278 stripdir="/foo", prependdir="/bar")
279
280 def test_multiple_optimization_levels(self):
281 script = script_helper.make_script(self.directory,
282 "test_optimization",
283 "a = 0")
284 bc = []
285 for opt_level in "", 1, 2, 3:
286 bc.append(importlib.util.cache_from_source(script,
287 optimization=opt_level))
288 test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]]
289 for opt_combination in test_combinations:
290 compileall.compile_file(script, quiet=True,
291 optimize=opt_combination)
292 for opt_level in opt_combination:
293 self.assertTrue(os.path.isfile(bc[opt_level]))
294 try:
295 os.unlink(bc[opt_level])
296 except Exception:
297 pass
298
299 @support.skip_unless_symlink
300 def test_ignore_symlink_destination(self):
301 # Create folders for allowed files, symlinks and prohibited area
302 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
303 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
304 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
305 os.makedirs(allowed_path)
306 os.makedirs(symlinks_path)
307 os.makedirs(prohibited_path)
308
309 # Create scripts and symlinks and remember their byte-compiled versions
310 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
311 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
312 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
313 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
314 os.symlink(allowed_script, allowed_symlink)
315 os.symlink(prohibited_script, prohibited_symlink)
316 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
317 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
318
319 compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path)
320
321 self.assertTrue(os.path.isfile(allowed_bc))
322 self.assertFalse(os.path.isfile(prohibited_bc))
323
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400324
325class CompileallTestsWithSourceEpoch(CompileallTestsBase,
326 unittest.TestCase,
327 metaclass=SourceDateEpochTestMeta,
328 source_date_epoch=True):
329 pass
330
331
332class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
333 unittest.TestCase,
334 metaclass=SourceDateEpochTestMeta,
335 source_date_epoch=False):
336 pass
337
338
Martin v. Löwis4b003072010-03-16 13:19:21 +0000339class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000340 """Issue 6716: compileall should escape source code when printing errors
341 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000342
343 def setUp(self):
344 self.directory = tempfile.mkdtemp()
345 self.source_path = os.path.join(self.directory, '_test.py')
346 with open(self.source_path, 'w', encoding='utf-8') as file:
347 file.write('# -*- coding: utf-8 -*-\n')
348 file.write('print u"\u20ac"\n')
349
350 def tearDown(self):
351 shutil.rmtree(self.directory)
352
353 def test_error(self):
354 try:
355 orig_stdout = sys.stdout
356 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
357 compileall.compile_dir(self.directory)
358 finally:
359 sys.stdout = orig_stdout
360
Barry Warsawc8a99de2010-04-29 18:43:10 +0000361
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400362class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000363 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000364
Brett Cannon65ed7502015-10-09 15:09:43 -0700365 @classmethod
366 def setUpClass(cls):
367 for path in filter(os.path.isdir, sys.path):
368 directory_created = False
369 directory = pathlib.Path(path) / '__pycache__'
370 path = directory / 'test.try'
371 try:
372 if not directory.is_dir():
373 directory.mkdir()
374 directory_created = True
375 with path.open('w') as file:
376 file.write('# for test_compileall')
377 except OSError:
378 sys_path_writable = False
379 break
380 finally:
381 support.unlink(str(path))
382 if directory_created:
383 directory.rmdir()
384 else:
385 sys_path_writable = True
386 cls._sys_path_writable = sys_path_writable
387
388 def _skip_if_sys_path_not_writable(self):
389 if not self._sys_path_writable:
390 raise unittest.SkipTest('not all entries on sys.path are writable')
391
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400392 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100393 return [*support.optim_args_from_interpreter_flags(),
394 '-S', '-m', 'compileall',
395 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400396
R. David Murray5317e9c2010-12-16 19:08:51 +0000397 def assertRunOK(self, *args, **env_vars):
398 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400399 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000400 self.assertEqual(b'', err)
401 return out
402
R. David Murray5317e9c2010-12-16 19:08:51 +0000403 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000404 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400405 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000406 return rc, out, err
407
408 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400409 path = importlib.util.cache_from_source(fn)
410 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000411
412 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400413 path = importlib.util.cache_from_source(fn)
414 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000415
Barry Warsaw28a691b2010-04-17 00:19:56 +0000416 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000417 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700418 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000419 self.pkgdir = os.path.join(self.directory, 'foo')
420 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000421 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
422 # Create the __init__.py and a package module.
423 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
424 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000425
R. David Murray5317e9c2010-12-16 19:08:51 +0000426 def test_no_args_compiles_path(self):
427 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700428 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000429 bazfn = script_helper.make_script(self.directory, 'baz', '')
430 self.assertRunOK(PYTHONPATH=self.directory)
431 self.assertCompiled(bazfn)
432 self.assertNotCompiled(self.initfn)
433 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000434
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400435 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500436 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700437 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500438 bazfn = script_helper.make_script(self.directory, 'baz', '')
439 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500440 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500441 # Set atime/mtime backward to avoid file timestamp resolution issues
442 os.utime(pycpath, (time.time()-60,)*2)
443 mtime = os.stat(pycpath).st_mtime
444 # Without force, no recompilation
445 self.assertRunOK(PYTHONPATH=self.directory)
446 mtime2 = os.stat(pycpath).st_mtime
447 self.assertEqual(mtime, mtime2)
448 # Now force it.
449 self.assertRunOK('-f', PYTHONPATH=self.directory)
450 mtime2 = os.stat(pycpath).st_mtime
451 self.assertNotEqual(mtime, mtime2)
452
453 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700454 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500455 script_helper.make_script(self.directory, 'baz', '')
456 noisy = self.assertRunOK(PYTHONPATH=self.directory)
457 self.assertIn(b'Listing ', noisy)
458 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
459 self.assertNotIn(b'Listing ', quiet)
460
Georg Brandl1463a3f2010-10-14 07:42:27 +0000461 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400462 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000463 for name, ext, switch in [
464 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400465 ('optimize', 'opt-1.pyc', ['-O']),
466 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000467 ]:
468 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000469 script_helper.assert_python_ok(*(switch +
470 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000471 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000472 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400473 expected = sorted(base.format(sys.implementation.cache_tag, ext)
474 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000475 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000476 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000477 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
478 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000479 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000480
481 def test_legacy_paths(self):
482 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400483 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000484 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000485 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000486 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400487 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
488 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000489 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
490
Barry Warsawc04317f2010-04-26 15:59:03 +0000491 def test_multiple_runs(self):
492 # Bug 8527 reported that multiple calls produced empty
493 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000494 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000495 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000496 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
497 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000498 self.assertFalse(os.path.exists(cachecachedir))
499 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000500 self.assertRunOK('-q', self.pkgdir)
501 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000502 self.assertFalse(os.path.exists(cachecachedir))
503
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400504 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000505 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000506 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400507 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000508 # set atime/mtime backward to avoid file timestamp resolution issues
509 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000510 mtime = os.stat(pycpath).st_mtime
511 # without force, no recompilation
512 self.assertRunOK('-q', self.pkgdir)
513 mtime2 = os.stat(pycpath).st_mtime
514 self.assertEqual(mtime, mtime2)
515 # now force it.
516 self.assertRunOK('-q', '-f', self.pkgdir)
517 mtime2 = os.stat(pycpath).st_mtime
518 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000519
R. David Murray95333e32010-12-14 22:32:50 +0000520 def test_recursion_control(self):
521 subpackage = os.path.join(self.pkgdir, 'spam')
522 os.mkdir(subpackage)
523 subinitfn = script_helper.make_script(subpackage, '__init__', '')
524 hamfn = script_helper.make_script(subpackage, 'ham', '')
525 self.assertRunOK('-q', '-l', self.pkgdir)
526 self.assertNotCompiled(subinitfn)
527 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
528 self.assertRunOK('-q', self.pkgdir)
529 self.assertCompiled(subinitfn)
530 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000531
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500532 def test_recursion_limit(self):
533 subpackage = os.path.join(self.pkgdir, 'spam')
534 subpackage2 = os.path.join(subpackage, 'ham')
535 subpackage3 = os.path.join(subpackage2, 'eggs')
536 for pkg in (subpackage, subpackage2, subpackage3):
537 script_helper.make_pkg(pkg)
538
539 subinitfn = os.path.join(subpackage, '__init__.py')
540 hamfn = script_helper.make_script(subpackage, 'ham', '')
541 spamfn = script_helper.make_script(subpackage2, 'spam', '')
542 eggfn = script_helper.make_script(subpackage3, 'egg', '')
543
544 self.assertRunOK('-q', '-r 0', self.pkgdir)
545 self.assertNotCompiled(subinitfn)
546 self.assertFalse(
547 os.path.exists(os.path.join(subpackage, '__pycache__')))
548
549 self.assertRunOK('-q', '-r 1', self.pkgdir)
550 self.assertCompiled(subinitfn)
551 self.assertCompiled(hamfn)
552 self.assertNotCompiled(spamfn)
553
554 self.assertRunOK('-q', '-r 2', self.pkgdir)
555 self.assertCompiled(subinitfn)
556 self.assertCompiled(hamfn)
557 self.assertCompiled(spamfn)
558 self.assertNotCompiled(eggfn)
559
560 self.assertRunOK('-q', '-r 5', self.pkgdir)
561 self.assertCompiled(subinitfn)
562 self.assertCompiled(hamfn)
563 self.assertCompiled(spamfn)
564 self.assertCompiled(eggfn)
565
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200566 @support.skip_unless_symlink
567 def test_symlink_loop(self):
568 # Currently, compileall ignores symlinks to directories.
569 # If that limitation is ever lifted, it should protect against
570 # recursion in symlink loops.
571 pkg = os.path.join(self.pkgdir, 'spam')
572 script_helper.make_pkg(pkg)
573 os.symlink('.', os.path.join(pkg, 'evil'))
574 os.symlink('.', os.path.join(pkg, 'evil2'))
575 self.assertRunOK('-q', self.pkgdir)
576 self.assertCompiled(os.path.join(
577 self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py'
578 ))
579
R. David Murray650f1472010-11-20 21:18:51 +0000580 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000581 noisy = self.assertRunOK(self.pkgdir)
582 quiet = self.assertRunOK('-q', self.pkgdir)
583 self.assertNotEqual(b'', noisy)
584 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000585
Berker Peksag6554b862014-10-15 11:10:57 +0300586 def test_silent(self):
587 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
588 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
589 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
590 self.assertNotEqual(b'', quiet)
591 self.assertEqual(b'', silent)
592
R. David Murray650f1472010-11-20 21:18:51 +0000593 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400594 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000595 self.assertNotCompiled(self.barfn)
596 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000597
R. David Murray95333e32010-12-14 22:32:50 +0000598 def test_multiple_dirs(self):
599 pkgdir2 = os.path.join(self.directory, 'foo2')
600 os.mkdir(pkgdir2)
601 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
602 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
603 self.assertRunOK('-q', self.pkgdir, pkgdir2)
604 self.assertCompiled(self.initfn)
605 self.assertCompiled(self.barfn)
606 self.assertCompiled(init2fn)
607 self.assertCompiled(bar2fn)
608
R. David Murray95333e32010-12-14 22:32:50 +0000609 def test_d_compile_error(self):
610 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
611 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
612 self.assertRegex(out, b'File "dinsdale')
613
614 def test_d_runtime_error(self):
615 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
616 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
617 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400618 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000619 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
620 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200621 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000622 self.assertRegex(err, b'File "dinsdale')
623
624 def test_include_bad_file(self):
625 rc, out, err = self.assertRunNotOK(
626 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
627 self.assertRegex(out, b'rror.*nosuchfile')
628 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400629 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000630 self.pkgdir_cachedir)))
631
632 def test_include_file_with_arg(self):
633 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
634 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
635 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
636 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
637 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
638 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
639 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
640 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
641 self.assertCompiled(f1)
642 self.assertCompiled(f2)
643 self.assertNotCompiled(f3)
644 self.assertCompiled(f4)
645
646 def test_include_file_no_arg(self):
647 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
648 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
649 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
650 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
651 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
652 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
653 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
654 self.assertNotCompiled(f1)
655 self.assertCompiled(f2)
656 self.assertNotCompiled(f3)
657 self.assertNotCompiled(f4)
658
659 def test_include_on_stdin(self):
660 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
661 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
662 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
663 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400664 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000665 p.stdin.write((f3+os.linesep).encode('ascii'))
666 script_helper.kill_python(p)
667 self.assertNotCompiled(f1)
668 self.assertNotCompiled(f2)
669 self.assertCompiled(f3)
670 self.assertNotCompiled(f4)
671
672 def test_compiles_as_much_as_possible(self):
673 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
674 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
675 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000676 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000677 self.assertNotCompiled(bingfn)
678 self.assertCompiled(self.initfn)
679 self.assertCompiled(self.barfn)
680
R. David Murray5317e9c2010-12-16 19:08:51 +0000681 def test_invalid_arg_produces_message(self):
682 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200683 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000684
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800685 def test_pyc_invalidation_mode(self):
686 script_helper.make_script(self.pkgdir, 'f1', '')
687 pyc = importlib.util.cache_from_source(
688 os.path.join(self.pkgdir, 'f1.py'))
689 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
690 with open(pyc, 'rb') as fp:
691 data = fp.read()
692 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
693 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
694 with open(pyc, 'rb') as fp:
695 data = fp.read()
696 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
697
Brett Cannonf1a8df02014-09-12 10:39:48 -0400698 @skipUnless(_have_multiprocessing, "requires multiprocessing")
699 def test_workers(self):
700 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
701 files = []
702 for suffix in range(5):
703 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
704 os.mkdir(pkgdir)
705 fn = script_helper.make_script(pkgdir, '__init__', '')
706 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
707
708 self.assertRunOK(self.directory, '-j', '0')
709 self.assertCompiled(bar2fn)
710 for file in files:
711 self.assertCompiled(file)
712
713 @mock.patch('compileall.compile_dir')
714 def test_workers_available_cores(self, compile_dir):
715 with mock.patch("sys.argv",
716 new=[sys.executable, self.directory, "-j0"]):
717 compileall.main()
718 self.assertTrue(compile_dir.called)
Antoine Pitrou1a2dd822019-05-15 23:45:18 +0200719 self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400720
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200721 def test_strip_and_prepend(self):
722 fullpath = ["test", "build", "real", "path"]
723 path = os.path.join(self.directory, *fullpath)
724 os.makedirs(path)
725 script = script_helper.make_script(path, "test", "1 / 0")
726 bc = importlib.util.cache_from_source(script)
727 stripdir = os.path.join(self.directory, *fullpath[:2])
728 prependdir = "/foo"
729 self.assertRunOK("-s", stripdir, "-p", prependdir, path)
730 rc, out, err = script_helper.assert_python_failure(bc)
731 expected_in = os.path.join(prependdir, *fullpath[2:])
732 self.assertIn(
733 expected_in,
734 str(err, encoding=sys.getdefaultencoding())
735 )
736 self.assertNotIn(
737 stripdir,
738 str(err, encoding=sys.getdefaultencoding())
739 )
740
741 def test_multiple_optimization_levels(self):
742 path = os.path.join(self.directory, "optimizations")
743 os.makedirs(path)
744 script = script_helper.make_script(path,
745 "test_optimization",
746 "a = 0")
747 bc = []
748 for opt_level in "", 1, 2, 3:
749 bc.append(importlib.util.cache_from_source(script,
750 optimization=opt_level))
751 test_combinations = [["0", "1"],
752 ["1", "2"],
753 ["0", "2"],
754 ["0", "1", "2"]]
755 for opt_combination in test_combinations:
756 self.assertRunOK(path, *("-o" + str(n) for n in opt_combination))
757 for opt_level in opt_combination:
758 self.assertTrue(os.path.isfile(bc[int(opt_level)]))
759 try:
760 os.unlink(bc[opt_level])
761 except Exception:
762 pass
763
764 @support.skip_unless_symlink
765 def test_ignore_symlink_destination(self):
766 # Create folders for allowed files, symlinks and prohibited area
767 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
768 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
769 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
770 os.makedirs(allowed_path)
771 os.makedirs(symlinks_path)
772 os.makedirs(prohibited_path)
773
774 # Create scripts and symlinks and remember their byte-compiled versions
775 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
776 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
777 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
778 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
779 os.symlink(allowed_script, allowed_symlink)
780 os.symlink(prohibited_script, prohibited_symlink)
781 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
782 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
783
784 self.assertRunOK(symlinks_path, "-e", allowed_path)
785
786 self.assertTrue(os.path.isfile(allowed_bc))
787 self.assertFalse(os.path.isfile(prohibited_bc))
788
Barry Warsaw28a691b2010-04-17 00:19:56 +0000789
Min ho Kimc4cacc82019-07-31 08:16:13 +1000790class CommandLineTestsWithSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400791 unittest.TestCase,
792 metaclass=SourceDateEpochTestMeta,
793 source_date_epoch=True):
794 pass
795
796
Min ho Kimc4cacc82019-07-31 08:16:13 +1000797class CommandLineTestsNoSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400798 unittest.TestCase,
799 metaclass=SourceDateEpochTestMeta,
800 source_date_epoch=False):
801 pass
802
803
804
Brett Cannonbefb14f2009-02-10 02:10:16 +0000805if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400806 unittest.main()