blob: cc51b8c06a0637b0d466d3b8ddaa903d210a21e7 [file] [log] [blame]
Brett Cannonbefb14f2009-02-10 02:10:16 +00001import compileall
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +02002import contextlib
3import filecmp
Brett Cannon7822e122013-06-14 23:04:02 -04004import importlib.util
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +02005import io
6import itertools
Brett Cannonbefb14f2009-02-10 02:10:16 +00007import os
Brett Cannon65ed7502015-10-09 15:09:43 -07008import pathlib
Brett Cannonbefb14f2009-02-10 02:10:16 +00009import py_compile
10import shutil
11import struct
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020012import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +000013import tempfile
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020014import test.test_importlib.util
R. David Murray650f1472010-11-20 21:18:51 +000015import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000016import unittest
17
Brett Cannonf1a8df02014-09-12 10:39:48 -040018from unittest import mock, skipUnless
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -080019from concurrent.futures import ProcessPoolExecutor
Brett Cannonf1a8df02014-09-12 10:39:48 -040020try:
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -080021 # compileall relies on ProcessPoolExecutor if ProcessPoolExecutor exists
22 # and it can function.
23 from concurrent.futures.process import _check_system_limits
24 _check_system_limits()
Brett Cannonf1a8df02014-09-12 10:39:48 -040025 _have_multiprocessing = True
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -080026except NotImplementedError:
Brett Cannonf1a8df02014-09-12 10:39:48 -040027 _have_multiprocessing = False
28
Berker Peksagce643912015-05-06 06:33:17 +030029from test import support
Hai Shi883bc632020-07-06 17:12:49 +080030from test.support import os_helper
Berker Peksagce643912015-05-06 06:33:17 +030031from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000032
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040033from .test_py_compile import without_source_date_epoch
34from .test_py_compile import SourceDateEpochTestMeta
35
36
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020037def get_pyc(script, opt):
38 if not opt:
39 # Replace None and 0 with ''
40 opt = ''
41 return importlib.util.cache_from_source(script, optimization=opt)
42
43
44def get_pycs(script):
45 return [get_pyc(script, opt) for opt in (0, 1, 2)]
46
47
48def is_hardlink(filename1, filename2):
49 """Returns True if two files have the same inode (hardlink)"""
50 inode1 = os.stat(filename1).st_ino
51 inode2 = os.stat(filename2).st_ino
52 return inode1 == inode2
53
54
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040055class CompileallTestsBase:
Brett Cannonbefb14f2009-02-10 02:10:16 +000056
57 def setUp(self):
58 self.directory = tempfile.mkdtemp()
59 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040060 self.bc_path = importlib.util.cache_from_source(self.source_path)
Inada Naoki80017752021-04-02 09:01:57 +090061 with open(self.source_path, 'w', encoding="utf-8") as file:
Brett Cannonbefb14f2009-02-10 02:10:16 +000062 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000063 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040064 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000065 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000066 self.subdirectory = os.path.join(self.directory, '_subdir')
67 os.mkdir(self.subdirectory)
68 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
69 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000070
71 def tearDown(self):
72 shutil.rmtree(self.directory)
73
Brett Cannon1e3c3e92015-12-27 13:17:04 -080074 def add_bad_source_file(self):
75 self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
Inada Naoki80017752021-04-02 09:01:57 +090076 with open(self.bad_source_path, 'w', encoding="utf-8") as file:
Brett Cannon1e3c3e92015-12-27 13:17:04 -080077 file.write('x (\n')
78
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040079 def timestamp_metadata(self):
Brett Cannonbefb14f2009-02-10 02:10:16 +000080 with open(self.bc_path, 'rb') as file:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080081 data = file.read(12)
Brett Cannonbefb14f2009-02-10 02:10:16 +000082 mtime = int(os.stat(self.source_path).st_mtime)
Miss Islington (bot)0af681b2021-08-24 08:09:14 -070083 compare = struct.pack('<4sLL', importlib.util.MAGIC_NUMBER, 0,
84 mtime & 0xFFFF_FFFF)
Brett Cannonbefb14f2009-02-10 02:10:16 +000085 return data, compare
86
Miss Islington (bot)0af681b2021-08-24 08:09:14 -070087 def test_year_2038_mtime_compilation(self):
88 # Test to make sure we can handle mtimes larger than what a 32-bit
89 # signed number can hold as part of bpo-34990
90 try:
91 os.utime(self.source_path, (2**32 - 1, 2**32 - 1))
92 except (OverflowError, OSError):
93 self.skipTest("filesystem doesn't support timestamps near 2**32")
94 self.assertTrue(compileall.compile_file(self.source_path))
95
96 def test_larger_than_32_bit_times(self):
97 # This is similar to the test above but we skip it if the OS doesn't
98 # support modification times larger than 32-bits.
99 try:
100 os.utime(self.source_path, (2**35, 2**35))
101 except (OverflowError, OSError):
102 self.skipTest("filesystem doesn't support large timestamps")
103 self.assertTrue(compileall.compile_file(self.source_path))
104
Brett Cannonbefb14f2009-02-10 02:10:16 +0000105 def recreation_check(self, metadata):
106 """Check that compileall recreates bytecode when the new metadata is
107 used."""
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400108 if os.environ.get('SOURCE_DATE_EPOCH'):
109 raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
Brett Cannonbefb14f2009-02-10 02:10:16 +0000110 py_compile.compile(self.source_path)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400111 self.assertEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +0000112 with open(self.bc_path, 'rb') as file:
113 bc = file.read()[len(metadata):]
114 with open(self.bc_path, 'wb') as file:
115 file.write(metadata)
116 file.write(bc)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400117 self.assertNotEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +0000118 compileall.compile_dir(self.directory, force=False, quiet=True)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400119 self.assertTrue(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +0000120
121 def test_mtime(self):
122 # Test a change in mtime leads to a new .pyc.
Miss Islington (bot)0af681b2021-08-24 08:09:14 -0700123 self.recreation_check(struct.pack('<4sLL', importlib.util.MAGIC_NUMBER,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800124 0, 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000125
126 def test_magic_number(self):
127 # Test a change in mtime leads to a new .pyc.
128 self.recreation_check(b'\0\0\0\0')
129
Matthias Klosec33b9022010-03-16 00:36:26 +0000130 def test_compile_files(self):
131 # Test compiling a single file, and complete directory
132 for fn in (self.bc_path, self.bc_path2):
133 try:
134 os.unlink(fn)
135 except:
136 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800137 self.assertTrue(compileall.compile_file(self.source_path,
138 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000139 self.assertTrue(os.path.isfile(self.bc_path) and
140 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000141 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800142 self.assertTrue(compileall.compile_dir(self.directory, force=False,
143 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000144 self.assertTrue(os.path.isfile(self.bc_path) and
145 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000146 os.unlink(self.bc_path)
147 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800148 # Test against bad files
149 self.add_bad_source_file()
150 self.assertFalse(compileall.compile_file(self.bad_source_path,
151 force=False, quiet=2))
152 self.assertFalse(compileall.compile_dir(self.directory,
153 force=False, quiet=2))
154
Berker Peksag812a2b62016-10-01 00:54:18 +0300155 def test_compile_file_pathlike(self):
156 self.assertFalse(os.path.isfile(self.bc_path))
157 # we should also test the output
158 with support.captured_stdout() as stdout:
159 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300160 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300161 self.assertTrue(os.path.isfile(self.bc_path))
162
163 def test_compile_file_pathlike_ddir(self):
164 self.assertFalse(os.path.isfile(self.bc_path))
165 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
166 ddir=pathlib.Path('ddir_path'),
167 quiet=2))
168 self.assertTrue(os.path.isfile(self.bc_path))
169
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800170 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300171 with test.test_importlib.util.import_state(path=[self.directory]):
172 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800173
174 with test.test_importlib.util.import_state(path=[self.directory]):
175 self.add_bad_source_file()
176 self.assertFalse(compileall.compile_path(skip_curdir=False,
177 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000178
Barry Warsawc8a99de2010-04-29 18:43:10 +0000179 def test_no_pycache_in_non_package(self):
180 # Bug 8563 reported that __pycache__ directories got created by
181 # compile_file() for non-.py files.
182 data_dir = os.path.join(self.directory, 'data')
183 data_file = os.path.join(data_dir, 'file')
184 os.mkdir(data_dir)
185 # touch data/file
Inada Naoki80017752021-04-02 09:01:57 +0900186 with open(data_file, 'wb'):
Barry Warsawc8a99de2010-04-29 18:43:10 +0000187 pass
188 compileall.compile_file(data_file)
189 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
190
Miss Islington (bot)0db6c142021-07-30 10:12:05 -0700191
192 def test_compile_file_encoding_fallback(self):
193 # Bug 44666 reported that compile_file failed when sys.stdout.encoding is None
194 self.add_bad_source_file()
195 with contextlib.redirect_stdout(io.StringIO()):
196 self.assertFalse(compileall.compile_file(self.bad_source_path))
197
198
Georg Brandl8334fd92010-12-04 10:26:46 +0000199 def test_optimize(self):
200 # make sure compiling with different optimization settings than the
201 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400202 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000203 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400204 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400205 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000206 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400207 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400208 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000209 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400210 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400211 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000212 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000213
Berker Peksag812a2b62016-10-01 00:54:18 +0300214 def test_compile_dir_pathlike(self):
215 self.assertFalse(os.path.isfile(self.bc_path))
216 with support.captured_stdout() as stdout:
217 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300218 line = stdout.getvalue().splitlines()[0]
219 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300220 self.assertTrue(os.path.isfile(self.bc_path))
221
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800222 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500223 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400224 def test_compile_pool_called(self, pool_mock):
225 compileall.compile_dir(self.directory, quiet=True, workers=5)
226 self.assertTrue(pool_mock.called)
227
228 def test_compile_workers_non_positive(self):
229 with self.assertRaisesRegex(ValueError,
230 "workers must be greater or equal to 0"):
231 compileall.compile_dir(self.directory, workers=-1)
232
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800233 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500234 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400235 def test_compile_workers_cpu_count(self, pool_mock):
236 compileall.compile_dir(self.directory, quiet=True, workers=0)
237 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
238
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800239 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500240 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400241 @mock.patch('compileall.compile_file')
242 def test_compile_one_worker(self, compile_file_mock, pool_mock):
243 compileall.compile_dir(self.directory, quiet=True)
244 self.assertFalse(pool_mock.called)
245 self.assertTrue(compile_file_mock.called)
246
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500247 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300248 @mock.patch('compileall.compile_file')
249 def test_compile_missing_multiprocessing(self, compile_file_mock):
250 compileall.compile_dir(self.directory, quiet=True, workers=5)
251 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000252
Petr Viktorin4267c982019-09-26 11:53:51 +0200253 def test_compile_dir_maxlevels(self):
Victor Stinnereb1dda22019-10-15 11:26:13 +0200254 # Test the actual impact of maxlevels parameter
255 depth = 3
256 path = self.directory
257 for i in range(1, depth + 1):
258 path = os.path.join(path, f"dir_{i}")
259 source = os.path.join(path, 'script.py')
260 os.mkdir(path)
261 shutil.copyfile(self.source_path, source)
262 pyc_filename = importlib.util.cache_from_source(source)
263
264 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth - 1)
265 self.assertFalse(os.path.isfile(pyc_filename))
266
267 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth)
268 self.assertTrue(os.path.isfile(pyc_filename))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200269
Gregory P. Smith02673352020-02-28 17:28:37 -0800270 def _test_ddir_only(self, *, ddir, parallel=True):
271 """Recursive compile_dir ddir must contain package paths; bpo39769."""
272 fullpath = ["test", "foo"]
273 path = self.directory
274 mods = []
275 for subdir in fullpath:
276 path = os.path.join(path, subdir)
277 os.mkdir(path)
278 script_helper.make_script(path, "__init__", "")
279 mods.append(script_helper.make_script(path, "mod",
280 "def fn(): 1/0\nfn()\n"))
281 compileall.compile_dir(
282 self.directory, quiet=True, ddir=ddir,
283 workers=2 if parallel else 1)
284 self.assertTrue(mods)
285 for mod in mods:
286 self.assertTrue(mod.startswith(self.directory), mod)
287 modcode = importlib.util.cache_from_source(mod)
288 modpath = mod[len(self.directory+os.sep):]
289 _, _, err = script_helper.assert_python_failure(modcode)
290 expected_in = os.path.join(ddir, modpath)
291 mod_code_obj = test.test_importlib.util.get_code_from_pyc(modcode)
292 self.assertEqual(mod_code_obj.co_filename, expected_in)
293 self.assertIn(f'"{expected_in}"', os.fsdecode(err))
294
295 def test_ddir_only_one_worker(self):
296 """Recursive compile_dir ddir= contains package paths; bpo39769."""
297 return self._test_ddir_only(ddir="<a prefix>", parallel=False)
298
299 def test_ddir_multiple_workers(self):
300 """Recursive compile_dir ddir= contains package paths; bpo39769."""
301 return self._test_ddir_only(ddir="<a prefix>", parallel=True)
302
303 def test_ddir_empty_only_one_worker(self):
304 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
305 return self._test_ddir_only(ddir="", parallel=False)
306
307 def test_ddir_empty_multiple_workers(self):
308 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
309 return self._test_ddir_only(ddir="", parallel=True)
310
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200311 def test_strip_only(self):
312 fullpath = ["test", "build", "real", "path"]
313 path = os.path.join(self.directory, *fullpath)
314 os.makedirs(path)
315 script = script_helper.make_script(path, "test", "1 / 0")
316 bc = importlib.util.cache_from_source(script)
317 stripdir = os.path.join(self.directory, *fullpath[:2])
318 compileall.compile_dir(path, quiet=True, stripdir=stripdir)
319 rc, out, err = script_helper.assert_python_failure(bc)
320 expected_in = os.path.join(*fullpath[2:])
321 self.assertIn(
322 expected_in,
323 str(err, encoding=sys.getdefaultencoding())
324 )
325 self.assertNotIn(
326 stripdir,
327 str(err, encoding=sys.getdefaultencoding())
328 )
329
330 def test_prepend_only(self):
331 fullpath = ["test", "build", "real", "path"]
332 path = os.path.join(self.directory, *fullpath)
333 os.makedirs(path)
334 script = script_helper.make_script(path, "test", "1 / 0")
335 bc = importlib.util.cache_from_source(script)
336 prependdir = "/foo"
337 compileall.compile_dir(path, quiet=True, prependdir=prependdir)
338 rc, out, err = script_helper.assert_python_failure(bc)
339 expected_in = os.path.join(prependdir, self.directory, *fullpath)
340 self.assertIn(
341 expected_in,
342 str(err, encoding=sys.getdefaultencoding())
343 )
344
345 def test_strip_and_prepend(self):
346 fullpath = ["test", "build", "real", "path"]
347 path = os.path.join(self.directory, *fullpath)
348 os.makedirs(path)
349 script = script_helper.make_script(path, "test", "1 / 0")
350 bc = importlib.util.cache_from_source(script)
351 stripdir = os.path.join(self.directory, *fullpath[:2])
352 prependdir = "/foo"
353 compileall.compile_dir(path, quiet=True,
354 stripdir=stripdir, prependdir=prependdir)
355 rc, out, err = script_helper.assert_python_failure(bc)
356 expected_in = os.path.join(prependdir, *fullpath[2:])
357 self.assertIn(
358 expected_in,
359 str(err, encoding=sys.getdefaultencoding())
360 )
361 self.assertNotIn(
362 stripdir,
363 str(err, encoding=sys.getdefaultencoding())
364 )
365
366 def test_strip_prepend_and_ddir(self):
367 fullpath = ["test", "build", "real", "path", "ddir"]
368 path = os.path.join(self.directory, *fullpath)
369 os.makedirs(path)
370 script_helper.make_script(path, "test", "1 / 0")
371 with self.assertRaises(ValueError):
372 compileall.compile_dir(path, quiet=True, ddir="/bar",
373 stripdir="/foo", prependdir="/bar")
374
375 def test_multiple_optimization_levels(self):
376 script = script_helper.make_script(self.directory,
377 "test_optimization",
378 "a = 0")
379 bc = []
380 for opt_level in "", 1, 2, 3:
381 bc.append(importlib.util.cache_from_source(script,
382 optimization=opt_level))
383 test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]]
384 for opt_combination in test_combinations:
385 compileall.compile_file(script, quiet=True,
386 optimize=opt_combination)
387 for opt_level in opt_combination:
388 self.assertTrue(os.path.isfile(bc[opt_level]))
389 try:
390 os.unlink(bc[opt_level])
391 except Exception:
392 pass
393
Hai Shi883bc632020-07-06 17:12:49 +0800394 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200395 def test_ignore_symlink_destination(self):
396 # Create folders for allowed files, symlinks and prohibited area
397 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
398 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
399 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
400 os.makedirs(allowed_path)
401 os.makedirs(symlinks_path)
402 os.makedirs(prohibited_path)
403
404 # Create scripts and symlinks and remember their byte-compiled versions
405 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
406 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
407 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
408 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
409 os.symlink(allowed_script, allowed_symlink)
410 os.symlink(prohibited_script, prohibited_symlink)
411 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
412 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
413
414 compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path)
415
416 self.assertTrue(os.path.isfile(allowed_bc))
417 self.assertFalse(os.path.isfile(prohibited_bc))
418
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400419
420class CompileallTestsWithSourceEpoch(CompileallTestsBase,
421 unittest.TestCase,
422 metaclass=SourceDateEpochTestMeta,
423 source_date_epoch=True):
424 pass
425
426
427class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
428 unittest.TestCase,
429 metaclass=SourceDateEpochTestMeta,
430 source_date_epoch=False):
431 pass
432
433
Martin v. Löwis4b003072010-03-16 13:19:21 +0000434class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000435 """Issue 6716: compileall should escape source code when printing errors
436 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000437
438 def setUp(self):
439 self.directory = tempfile.mkdtemp()
440 self.source_path = os.path.join(self.directory, '_test.py')
441 with open(self.source_path, 'w', encoding='utf-8') as file:
442 file.write('# -*- coding: utf-8 -*-\n')
443 file.write('print u"\u20ac"\n')
444
445 def tearDown(self):
446 shutil.rmtree(self.directory)
447
448 def test_error(self):
449 try:
450 orig_stdout = sys.stdout
451 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
452 compileall.compile_dir(self.directory)
453 finally:
454 sys.stdout = orig_stdout
455
Barry Warsawc8a99de2010-04-29 18:43:10 +0000456
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400457class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000458 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000459
Brett Cannon65ed7502015-10-09 15:09:43 -0700460 @classmethod
461 def setUpClass(cls):
462 for path in filter(os.path.isdir, sys.path):
463 directory_created = False
464 directory = pathlib.Path(path) / '__pycache__'
465 path = directory / 'test.try'
466 try:
467 if not directory.is_dir():
468 directory.mkdir()
469 directory_created = True
Inada Naoki80017752021-04-02 09:01:57 +0900470 path.write_text('# for test_compileall', encoding="utf-8")
Brett Cannon65ed7502015-10-09 15:09:43 -0700471 except OSError:
472 sys_path_writable = False
473 break
474 finally:
Hai Shi883bc632020-07-06 17:12:49 +0800475 os_helper.unlink(str(path))
Brett Cannon65ed7502015-10-09 15:09:43 -0700476 if directory_created:
477 directory.rmdir()
478 else:
479 sys_path_writable = True
480 cls._sys_path_writable = sys_path_writable
481
482 def _skip_if_sys_path_not_writable(self):
483 if not self._sys_path_writable:
484 raise unittest.SkipTest('not all entries on sys.path are writable')
485
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400486 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100487 return [*support.optim_args_from_interpreter_flags(),
488 '-S', '-m', 'compileall',
489 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400490
R. David Murray5317e9c2010-12-16 19:08:51 +0000491 def assertRunOK(self, *args, **env_vars):
492 rc, out, err = script_helper.assert_python_ok(
Serhiy Storchaka700cfa82020-06-25 17:56:31 +0300493 *self._get_run_args(args), **env_vars,
494 PYTHONIOENCODING='utf-8')
R. David Murray95333e32010-12-14 22:32:50 +0000495 self.assertEqual(b'', err)
496 return out
497
R. David Murray5317e9c2010-12-16 19:08:51 +0000498 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000499 rc, out, err = script_helper.assert_python_failure(
Serhiy Storchaka700cfa82020-06-25 17:56:31 +0300500 *self._get_run_args(args), **env_vars,
501 PYTHONIOENCODING='utf-8')
R. David Murray95333e32010-12-14 22:32:50 +0000502 return rc, out, err
503
504 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400505 path = importlib.util.cache_from_source(fn)
506 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000507
508 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400509 path = importlib.util.cache_from_source(fn)
510 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000511
Barry Warsaw28a691b2010-04-17 00:19:56 +0000512 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000513 self.directory = tempfile.mkdtemp()
Hai Shi883bc632020-07-06 17:12:49 +0800514 self.addCleanup(os_helper.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000515 self.pkgdir = os.path.join(self.directory, 'foo')
516 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000517 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
518 # Create the __init__.py and a package module.
519 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
520 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000521
R. David Murray5317e9c2010-12-16 19:08:51 +0000522 def test_no_args_compiles_path(self):
523 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700524 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000525 bazfn = script_helper.make_script(self.directory, 'baz', '')
526 self.assertRunOK(PYTHONPATH=self.directory)
527 self.assertCompiled(bazfn)
528 self.assertNotCompiled(self.initfn)
529 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000530
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400531 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500532 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700533 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500534 bazfn = script_helper.make_script(self.directory, 'baz', '')
535 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500536 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500537 # Set atime/mtime backward to avoid file timestamp resolution issues
538 os.utime(pycpath, (time.time()-60,)*2)
539 mtime = os.stat(pycpath).st_mtime
540 # Without force, no recompilation
541 self.assertRunOK(PYTHONPATH=self.directory)
542 mtime2 = os.stat(pycpath).st_mtime
543 self.assertEqual(mtime, mtime2)
544 # Now force it.
545 self.assertRunOK('-f', PYTHONPATH=self.directory)
546 mtime2 = os.stat(pycpath).st_mtime
547 self.assertNotEqual(mtime, mtime2)
548
549 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700550 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500551 script_helper.make_script(self.directory, 'baz', '')
552 noisy = self.assertRunOK(PYTHONPATH=self.directory)
553 self.assertIn(b'Listing ', noisy)
554 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
555 self.assertNotIn(b'Listing ', quiet)
556
Georg Brandl1463a3f2010-10-14 07:42:27 +0000557 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400558 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000559 for name, ext, switch in [
560 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400561 ('optimize', 'opt-1.pyc', ['-O']),
562 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000563 ]:
564 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000565 script_helper.assert_python_ok(*(switch +
566 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000567 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000568 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400569 expected = sorted(base.format(sys.implementation.cache_tag, ext)
570 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000571 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000572 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000573 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
574 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000575 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000576
577 def test_legacy_paths(self):
578 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400579 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000580 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000581 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000582 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400583 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
584 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000585 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
586
Barry Warsawc04317f2010-04-26 15:59:03 +0000587 def test_multiple_runs(self):
588 # Bug 8527 reported that multiple calls produced empty
589 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000590 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000591 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000592 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
593 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000594 self.assertFalse(os.path.exists(cachecachedir))
595 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000596 self.assertRunOK('-q', self.pkgdir)
597 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000598 self.assertFalse(os.path.exists(cachecachedir))
599
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400600 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000601 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000602 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400603 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000604 # set atime/mtime backward to avoid file timestamp resolution issues
605 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000606 mtime = os.stat(pycpath).st_mtime
607 # without force, no recompilation
608 self.assertRunOK('-q', self.pkgdir)
609 mtime2 = os.stat(pycpath).st_mtime
610 self.assertEqual(mtime, mtime2)
611 # now force it.
612 self.assertRunOK('-q', '-f', self.pkgdir)
613 mtime2 = os.stat(pycpath).st_mtime
614 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000615
R. David Murray95333e32010-12-14 22:32:50 +0000616 def test_recursion_control(self):
617 subpackage = os.path.join(self.pkgdir, 'spam')
618 os.mkdir(subpackage)
619 subinitfn = script_helper.make_script(subpackage, '__init__', '')
620 hamfn = script_helper.make_script(subpackage, 'ham', '')
621 self.assertRunOK('-q', '-l', self.pkgdir)
622 self.assertNotCompiled(subinitfn)
623 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
624 self.assertRunOK('-q', self.pkgdir)
625 self.assertCompiled(subinitfn)
626 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000627
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500628 def test_recursion_limit(self):
629 subpackage = os.path.join(self.pkgdir, 'spam')
630 subpackage2 = os.path.join(subpackage, 'ham')
631 subpackage3 = os.path.join(subpackage2, 'eggs')
632 for pkg in (subpackage, subpackage2, subpackage3):
633 script_helper.make_pkg(pkg)
634
635 subinitfn = os.path.join(subpackage, '__init__.py')
636 hamfn = script_helper.make_script(subpackage, 'ham', '')
637 spamfn = script_helper.make_script(subpackage2, 'spam', '')
638 eggfn = script_helper.make_script(subpackage3, 'egg', '')
639
640 self.assertRunOK('-q', '-r 0', self.pkgdir)
641 self.assertNotCompiled(subinitfn)
642 self.assertFalse(
643 os.path.exists(os.path.join(subpackage, '__pycache__')))
644
645 self.assertRunOK('-q', '-r 1', self.pkgdir)
646 self.assertCompiled(subinitfn)
647 self.assertCompiled(hamfn)
648 self.assertNotCompiled(spamfn)
649
650 self.assertRunOK('-q', '-r 2', self.pkgdir)
651 self.assertCompiled(subinitfn)
652 self.assertCompiled(hamfn)
653 self.assertCompiled(spamfn)
654 self.assertNotCompiled(eggfn)
655
656 self.assertRunOK('-q', '-r 5', self.pkgdir)
657 self.assertCompiled(subinitfn)
658 self.assertCompiled(hamfn)
659 self.assertCompiled(spamfn)
660 self.assertCompiled(eggfn)
661
Hai Shi883bc632020-07-06 17:12:49 +0800662 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200663 def test_symlink_loop(self):
664 # Currently, compileall ignores symlinks to directories.
665 # If that limitation is ever lifted, it should protect against
666 # recursion in symlink loops.
667 pkg = os.path.join(self.pkgdir, 'spam')
668 script_helper.make_pkg(pkg)
669 os.symlink('.', os.path.join(pkg, 'evil'))
670 os.symlink('.', os.path.join(pkg, 'evil2'))
671 self.assertRunOK('-q', self.pkgdir)
672 self.assertCompiled(os.path.join(
673 self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py'
674 ))
675
R. David Murray650f1472010-11-20 21:18:51 +0000676 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000677 noisy = self.assertRunOK(self.pkgdir)
678 quiet = self.assertRunOK('-q', self.pkgdir)
679 self.assertNotEqual(b'', noisy)
680 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000681
Berker Peksag6554b862014-10-15 11:10:57 +0300682 def test_silent(self):
683 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
684 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
685 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
686 self.assertNotEqual(b'', quiet)
687 self.assertEqual(b'', silent)
688
R. David Murray650f1472010-11-20 21:18:51 +0000689 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400690 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000691 self.assertNotCompiled(self.barfn)
692 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000693
R. David Murray95333e32010-12-14 22:32:50 +0000694 def test_multiple_dirs(self):
695 pkgdir2 = os.path.join(self.directory, 'foo2')
696 os.mkdir(pkgdir2)
697 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
698 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
699 self.assertRunOK('-q', self.pkgdir, pkgdir2)
700 self.assertCompiled(self.initfn)
701 self.assertCompiled(self.barfn)
702 self.assertCompiled(init2fn)
703 self.assertCompiled(bar2fn)
704
R. David Murray95333e32010-12-14 22:32:50 +0000705 def test_d_compile_error(self):
706 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
707 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
708 self.assertRegex(out, b'File "dinsdale')
709
710 def test_d_runtime_error(self):
711 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
712 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
713 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400714 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000715 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
716 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200717 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000718 self.assertRegex(err, b'File "dinsdale')
719
720 def test_include_bad_file(self):
721 rc, out, err = self.assertRunNotOK(
722 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
723 self.assertRegex(out, b'rror.*nosuchfile')
724 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400725 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000726 self.pkgdir_cachedir)))
727
728 def test_include_file_with_arg(self):
729 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
730 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
731 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
732 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Inada Naoki80017752021-04-02 09:01:57 +0900733 with open(os.path.join(self.directory, 'l1'), 'w', encoding="utf-8") as l1:
R. David Murray95333e32010-12-14 22:32:50 +0000734 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
735 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
736 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
737 self.assertCompiled(f1)
738 self.assertCompiled(f2)
739 self.assertNotCompiled(f3)
740 self.assertCompiled(f4)
741
742 def test_include_file_no_arg(self):
743 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
744 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
745 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
746 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Inada Naoki80017752021-04-02 09:01:57 +0900747 with open(os.path.join(self.directory, 'l1'), 'w', encoding="utf-8") as l1:
R. David Murray95333e32010-12-14 22:32:50 +0000748 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
749 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
750 self.assertNotCompiled(f1)
751 self.assertCompiled(f2)
752 self.assertNotCompiled(f3)
753 self.assertNotCompiled(f4)
754
755 def test_include_on_stdin(self):
756 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
757 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
758 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
759 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400760 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000761 p.stdin.write((f3+os.linesep).encode('ascii'))
762 script_helper.kill_python(p)
763 self.assertNotCompiled(f1)
764 self.assertNotCompiled(f2)
765 self.assertCompiled(f3)
766 self.assertNotCompiled(f4)
767
768 def test_compiles_as_much_as_possible(self):
769 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
770 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
771 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000772 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000773 self.assertNotCompiled(bingfn)
774 self.assertCompiled(self.initfn)
775 self.assertCompiled(self.barfn)
776
R. David Murray5317e9c2010-12-16 19:08:51 +0000777 def test_invalid_arg_produces_message(self):
778 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200779 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000780
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800781 def test_pyc_invalidation_mode(self):
782 script_helper.make_script(self.pkgdir, 'f1', '')
783 pyc = importlib.util.cache_from_source(
784 os.path.join(self.pkgdir, 'f1.py'))
785 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
786 with open(pyc, 'rb') as fp:
787 data = fp.read()
788 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
789 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
790 with open(pyc, 'rb') as fp:
791 data = fp.read()
792 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
793
Brett Cannonf1a8df02014-09-12 10:39:48 -0400794 @skipUnless(_have_multiprocessing, "requires multiprocessing")
795 def test_workers(self):
796 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
797 files = []
798 for suffix in range(5):
799 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
800 os.mkdir(pkgdir)
801 fn = script_helper.make_script(pkgdir, '__init__', '')
802 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
803
804 self.assertRunOK(self.directory, '-j', '0')
805 self.assertCompiled(bar2fn)
806 for file in files:
807 self.assertCompiled(file)
808
809 @mock.patch('compileall.compile_dir')
810 def test_workers_available_cores(self, compile_dir):
811 with mock.patch("sys.argv",
812 new=[sys.executable, self.directory, "-j0"]):
813 compileall.main()
814 self.assertTrue(compile_dir.called)
Antoine Pitrou1a2dd822019-05-15 23:45:18 +0200815 self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400816
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200817 def test_strip_and_prepend(self):
818 fullpath = ["test", "build", "real", "path"]
819 path = os.path.join(self.directory, *fullpath)
820 os.makedirs(path)
821 script = script_helper.make_script(path, "test", "1 / 0")
822 bc = importlib.util.cache_from_source(script)
823 stripdir = os.path.join(self.directory, *fullpath[:2])
824 prependdir = "/foo"
825 self.assertRunOK("-s", stripdir, "-p", prependdir, path)
826 rc, out, err = script_helper.assert_python_failure(bc)
827 expected_in = os.path.join(prependdir, *fullpath[2:])
828 self.assertIn(
829 expected_in,
830 str(err, encoding=sys.getdefaultencoding())
831 )
832 self.assertNotIn(
833 stripdir,
834 str(err, encoding=sys.getdefaultencoding())
835 )
836
837 def test_multiple_optimization_levels(self):
838 path = os.path.join(self.directory, "optimizations")
839 os.makedirs(path)
840 script = script_helper.make_script(path,
841 "test_optimization",
842 "a = 0")
843 bc = []
844 for opt_level in "", 1, 2, 3:
845 bc.append(importlib.util.cache_from_source(script,
846 optimization=opt_level))
847 test_combinations = [["0", "1"],
848 ["1", "2"],
849 ["0", "2"],
850 ["0", "1", "2"]]
851 for opt_combination in test_combinations:
852 self.assertRunOK(path, *("-o" + str(n) for n in opt_combination))
853 for opt_level in opt_combination:
854 self.assertTrue(os.path.isfile(bc[int(opt_level)]))
855 try:
856 os.unlink(bc[opt_level])
857 except Exception:
858 pass
859
Hai Shi883bc632020-07-06 17:12:49 +0800860 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200861 def test_ignore_symlink_destination(self):
862 # Create folders for allowed files, symlinks and prohibited area
863 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
864 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
865 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
866 os.makedirs(allowed_path)
867 os.makedirs(symlinks_path)
868 os.makedirs(prohibited_path)
869
870 # Create scripts and symlinks and remember their byte-compiled versions
871 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
872 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
873 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
874 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
875 os.symlink(allowed_script, allowed_symlink)
876 os.symlink(prohibited_script, prohibited_symlink)
877 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
878 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
879
880 self.assertRunOK(symlinks_path, "-e", allowed_path)
881
882 self.assertTrue(os.path.isfile(allowed_bc))
883 self.assertFalse(os.path.isfile(prohibited_bc))
884
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200885 def test_hardlink_bad_args(self):
886 # Bad arguments combination, hardlink deduplication make sense
887 # only for more than one optimization level
888 self.assertRunNotOK(self.directory, "-o 1", "--hardlink-dupes")
889
890 def test_hardlink(self):
891 # 'a = 0' code produces the same bytecode for the 3 optimization
892 # levels. All three .pyc files must have the same inode (hardlinks).
893 #
894 # If deduplication is disabled, all pyc files must have different
895 # inodes.
896 for dedup in (True, False):
897 with tempfile.TemporaryDirectory() as path:
898 with self.subTest(dedup=dedup):
899 script = script_helper.make_script(path, "script", "a = 0")
900 pycs = get_pycs(script)
901
902 args = ["-q", "-o 0", "-o 1", "-o 2"]
903 if dedup:
904 args.append("--hardlink-dupes")
905 self.assertRunOK(path, *args)
906
907 self.assertEqual(is_hardlink(pycs[0], pycs[1]), dedup)
908 self.assertEqual(is_hardlink(pycs[1], pycs[2]), dedup)
909 self.assertEqual(is_hardlink(pycs[0], pycs[2]), dedup)
910
Barry Warsaw28a691b2010-04-17 00:19:56 +0000911
Min ho Kimc4cacc82019-07-31 08:16:13 +1000912class CommandLineTestsWithSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400913 unittest.TestCase,
914 metaclass=SourceDateEpochTestMeta,
915 source_date_epoch=True):
916 pass
917
918
Min ho Kimc4cacc82019-07-31 08:16:13 +1000919class CommandLineTestsNoSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400920 unittest.TestCase,
921 metaclass=SourceDateEpochTestMeta,
922 source_date_epoch=False):
923 pass
924
925
926
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200927class HardlinkDedupTestsBase:
928 # Test hardlink_dupes parameter of compileall.compile_dir()
929
930 def setUp(self):
931 self.path = None
932
933 @contextlib.contextmanager
934 def temporary_directory(self):
935 with tempfile.TemporaryDirectory() as path:
936 self.path = path
937 yield path
938 self.path = None
939
940 def make_script(self, code, name="script"):
941 return script_helper.make_script(self.path, name, code)
942
943 def compile_dir(self, *, dedup=True, optimize=(0, 1, 2), force=False):
944 compileall.compile_dir(self.path, quiet=True, optimize=optimize,
945 hardlink_dupes=dedup, force=force)
946
947 def test_bad_args(self):
948 # Bad arguments combination, hardlink deduplication make sense
949 # only for more than one optimization level
950 with self.temporary_directory():
951 self.make_script("pass")
952 with self.assertRaises(ValueError):
953 compileall.compile_dir(self.path, quiet=True, optimize=0,
954 hardlink_dupes=True)
955 with self.assertRaises(ValueError):
956 # same optimization level specified twice:
957 # compile_dir() removes duplicates
958 compileall.compile_dir(self.path, quiet=True, optimize=[0, 0],
959 hardlink_dupes=True)
960
961 def create_code(self, docstring=False, assertion=False):
962 lines = []
963 if docstring:
964 lines.append("'module docstring'")
965 lines.append('x = 1')
966 if assertion:
967 lines.append("assert x == 1")
968 return '\n'.join(lines)
969
970 def iter_codes(self):
971 for docstring in (False, True):
972 for assertion in (False, True):
973 code = self.create_code(docstring=docstring, assertion=assertion)
974 yield (code, docstring, assertion)
975
976 def test_disabled(self):
977 # Deduplication disabled, no hardlinks
978 for code, docstring, assertion in self.iter_codes():
979 with self.subTest(docstring=docstring, assertion=assertion):
980 with self.temporary_directory():
981 script = self.make_script(code)
982 pycs = get_pycs(script)
983 self.compile_dir(dedup=False)
984 self.assertFalse(is_hardlink(pycs[0], pycs[1]))
985 self.assertFalse(is_hardlink(pycs[0], pycs[2]))
986 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
987
988 def check_hardlinks(self, script, docstring=False, assertion=False):
989 pycs = get_pycs(script)
990 self.assertEqual(is_hardlink(pycs[0], pycs[1]),
991 not assertion)
992 self.assertEqual(is_hardlink(pycs[0], pycs[2]),
993 not assertion and not docstring)
994 self.assertEqual(is_hardlink(pycs[1], pycs[2]),
995 not docstring)
996
997 def test_hardlink(self):
998 # Test deduplication on all combinations
999 for code, docstring, assertion in self.iter_codes():
1000 with self.subTest(docstring=docstring, assertion=assertion):
1001 with self.temporary_directory():
1002 script = self.make_script(code)
1003 self.compile_dir()
1004 self.check_hardlinks(script, docstring, assertion)
1005
1006 def test_only_two_levels(self):
1007 # Don't build the 3 optimization levels, but only 2
1008 for opts in ((0, 1), (1, 2), (0, 2)):
1009 with self.subTest(opts=opts):
1010 with self.temporary_directory():
1011 # code with no dostring and no assertion:
1012 # same bytecode for all optimization levels
1013 script = self.make_script(self.create_code())
1014 self.compile_dir(optimize=opts)
1015 pyc1 = get_pyc(script, opts[0])
1016 pyc2 = get_pyc(script, opts[1])
1017 self.assertTrue(is_hardlink(pyc1, pyc2))
1018
1019 def test_duplicated_levels(self):
1020 # compile_dir() must not fail if optimize contains duplicated
1021 # optimization levels and/or if optimization levels are not sorted.
1022 with self.temporary_directory():
1023 # code with no dostring and no assertion:
1024 # same bytecode for all optimization levels
1025 script = self.make_script(self.create_code())
1026 self.compile_dir(optimize=[1, 0, 1, 0])
1027 pyc1 = get_pyc(script, 0)
1028 pyc2 = get_pyc(script, 1)
1029 self.assertTrue(is_hardlink(pyc1, pyc2))
1030
1031 def test_recompilation(self):
1032 # Test compile_dir() when pyc files already exists and the script
1033 # content changed
1034 with self.temporary_directory():
1035 script = self.make_script("a = 0")
1036 self.compile_dir()
1037 # All three levels have the same inode
1038 self.check_hardlinks(script)
1039
1040 pycs = get_pycs(script)
1041 inode = os.stat(pycs[0]).st_ino
1042
1043 # Change of the module content
1044 script = self.make_script("print(0)")
1045
1046 # Recompilation without -o 1
1047 self.compile_dir(optimize=[0, 2], force=True)
1048
1049 # opt-1.pyc should have the same inode as before and others should not
1050 self.assertEqual(inode, os.stat(pycs[1]).st_ino)
1051 self.assertTrue(is_hardlink(pycs[0], pycs[2]))
1052 self.assertNotEqual(inode, os.stat(pycs[2]).st_ino)
1053 # opt-1.pyc and opt-2.pyc have different content
1054 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1055
1056 def test_import(self):
1057 # Test that import updates a single pyc file when pyc files already
1058 # exists and the script content changed
1059 with self.temporary_directory():
1060 script = self.make_script(self.create_code(), name="module")
1061 self.compile_dir()
1062 # All three levels have the same inode
1063 self.check_hardlinks(script)
1064
1065 pycs = get_pycs(script)
1066 inode = os.stat(pycs[0]).st_ino
1067
1068 # Change of the module content
1069 script = self.make_script("print(0)", name="module")
1070
1071 # Import the module in Python with -O (optimization level 1)
1072 script_helper.assert_python_ok(
1073 "-O", "-c", "import module", __isolated=False, PYTHONPATH=self.path
1074 )
1075
1076 # Only opt-1.pyc is changed
1077 self.assertEqual(inode, os.stat(pycs[0]).st_ino)
1078 self.assertEqual(inode, os.stat(pycs[2]).st_ino)
1079 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
1080 # opt-1.pyc and opt-2.pyc have different content
1081 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1082
1083
1084class HardlinkDedupTestsWithSourceEpoch(HardlinkDedupTestsBase,
1085 unittest.TestCase,
1086 metaclass=SourceDateEpochTestMeta,
1087 source_date_epoch=True):
1088 pass
1089
1090
1091class HardlinkDedupTestsNoSourceEpoch(HardlinkDedupTestsBase,
1092 unittest.TestCase,
1093 metaclass=SourceDateEpochTestMeta,
1094 source_date_epoch=False):
1095 pass
1096
1097
Brett Cannonbefb14f2009-02-10 02:10:16 +00001098if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -04001099 unittest.main()