blob: 4612953cf8df39e258edb19e45c30cee7139e7e1 [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)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080083 compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000084 return data, compare
85
86 def recreation_check(self, metadata):
87 """Check that compileall recreates bytecode when the new metadata is
88 used."""
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040089 if os.environ.get('SOURCE_DATE_EPOCH'):
90 raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
Brett Cannonbefb14f2009-02-10 02:10:16 +000091 py_compile.compile(self.source_path)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040092 self.assertEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000093 with open(self.bc_path, 'rb') as file:
94 bc = file.read()[len(metadata):]
95 with open(self.bc_path, 'wb') as file:
96 file.write(metadata)
97 file.write(bc)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040098 self.assertNotEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000099 compileall.compile_dir(self.directory, force=False, quiet=True)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400100 self.assertTrue(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +0000101
102 def test_mtime(self):
103 # Test a change in mtime leads to a new .pyc.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800104 self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
105 0, 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000106
107 def test_magic_number(self):
108 # Test a change in mtime leads to a new .pyc.
109 self.recreation_check(b'\0\0\0\0')
110
Matthias Klosec33b9022010-03-16 00:36:26 +0000111 def test_compile_files(self):
112 # Test compiling a single file, and complete directory
113 for fn in (self.bc_path, self.bc_path2):
114 try:
115 os.unlink(fn)
116 except:
117 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800118 self.assertTrue(compileall.compile_file(self.source_path,
119 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000120 self.assertTrue(os.path.isfile(self.bc_path) and
121 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000122 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800123 self.assertTrue(compileall.compile_dir(self.directory, force=False,
124 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000125 self.assertTrue(os.path.isfile(self.bc_path) and
126 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000127 os.unlink(self.bc_path)
128 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800129 # Test against bad files
130 self.add_bad_source_file()
131 self.assertFalse(compileall.compile_file(self.bad_source_path,
132 force=False, quiet=2))
133 self.assertFalse(compileall.compile_dir(self.directory,
134 force=False, quiet=2))
135
Berker Peksag812a2b62016-10-01 00:54:18 +0300136 def test_compile_file_pathlike(self):
137 self.assertFalse(os.path.isfile(self.bc_path))
138 # we should also test the output
139 with support.captured_stdout() as stdout:
140 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300141 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300142 self.assertTrue(os.path.isfile(self.bc_path))
143
144 def test_compile_file_pathlike_ddir(self):
145 self.assertFalse(os.path.isfile(self.bc_path))
146 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
147 ddir=pathlib.Path('ddir_path'),
148 quiet=2))
149 self.assertTrue(os.path.isfile(self.bc_path))
150
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800151 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300152 with test.test_importlib.util.import_state(path=[self.directory]):
153 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800154
155 with test.test_importlib.util.import_state(path=[self.directory]):
156 self.add_bad_source_file()
157 self.assertFalse(compileall.compile_path(skip_curdir=False,
158 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000159
Barry Warsawc8a99de2010-04-29 18:43:10 +0000160 def test_no_pycache_in_non_package(self):
161 # Bug 8563 reported that __pycache__ directories got created by
162 # compile_file() for non-.py files.
163 data_dir = os.path.join(self.directory, 'data')
164 data_file = os.path.join(data_dir, 'file')
165 os.mkdir(data_dir)
166 # touch data/file
Inada Naoki80017752021-04-02 09:01:57 +0900167 with open(data_file, 'wb'):
Barry Warsawc8a99de2010-04-29 18:43:10 +0000168 pass
169 compileall.compile_file(data_file)
170 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
171
Miss Islington (bot)0db6c142021-07-30 10:12:05 -0700172
173 def test_compile_file_encoding_fallback(self):
174 # Bug 44666 reported that compile_file failed when sys.stdout.encoding is None
175 self.add_bad_source_file()
176 with contextlib.redirect_stdout(io.StringIO()):
177 self.assertFalse(compileall.compile_file(self.bad_source_path))
178
179
Georg Brandl8334fd92010-12-04 10:26:46 +0000180 def test_optimize(self):
181 # make sure compiling with different optimization settings than the
182 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400183 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000184 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400185 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400186 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000187 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400188 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400189 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000190 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400191 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400192 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000193 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000194
Berker Peksag812a2b62016-10-01 00:54:18 +0300195 def test_compile_dir_pathlike(self):
196 self.assertFalse(os.path.isfile(self.bc_path))
197 with support.captured_stdout() as stdout:
198 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300199 line = stdout.getvalue().splitlines()[0]
200 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300201 self.assertTrue(os.path.isfile(self.bc_path))
202
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800203 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500204 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400205 def test_compile_pool_called(self, pool_mock):
206 compileall.compile_dir(self.directory, quiet=True, workers=5)
207 self.assertTrue(pool_mock.called)
208
209 def test_compile_workers_non_positive(self):
210 with self.assertRaisesRegex(ValueError,
211 "workers must be greater or equal to 0"):
212 compileall.compile_dir(self.directory, workers=-1)
213
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800214 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500215 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400216 def test_compile_workers_cpu_count(self, pool_mock):
217 compileall.compile_dir(self.directory, quiet=True, workers=0)
218 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
219
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800220 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500221 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400222 @mock.patch('compileall.compile_file')
223 def test_compile_one_worker(self, compile_file_mock, pool_mock):
224 compileall.compile_dir(self.directory, quiet=True)
225 self.assertFalse(pool_mock.called)
226 self.assertTrue(compile_file_mock.called)
227
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500228 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300229 @mock.patch('compileall.compile_file')
230 def test_compile_missing_multiprocessing(self, compile_file_mock):
231 compileall.compile_dir(self.directory, quiet=True, workers=5)
232 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000233
Petr Viktorin4267c982019-09-26 11:53:51 +0200234 def test_compile_dir_maxlevels(self):
Victor Stinnereb1dda22019-10-15 11:26:13 +0200235 # Test the actual impact of maxlevels parameter
236 depth = 3
237 path = self.directory
238 for i in range(1, depth + 1):
239 path = os.path.join(path, f"dir_{i}")
240 source = os.path.join(path, 'script.py')
241 os.mkdir(path)
242 shutil.copyfile(self.source_path, source)
243 pyc_filename = importlib.util.cache_from_source(source)
244
245 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth - 1)
246 self.assertFalse(os.path.isfile(pyc_filename))
247
248 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth)
249 self.assertTrue(os.path.isfile(pyc_filename))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200250
Gregory P. Smith02673352020-02-28 17:28:37 -0800251 def _test_ddir_only(self, *, ddir, parallel=True):
252 """Recursive compile_dir ddir must contain package paths; bpo39769."""
253 fullpath = ["test", "foo"]
254 path = self.directory
255 mods = []
256 for subdir in fullpath:
257 path = os.path.join(path, subdir)
258 os.mkdir(path)
259 script_helper.make_script(path, "__init__", "")
260 mods.append(script_helper.make_script(path, "mod",
261 "def fn(): 1/0\nfn()\n"))
262 compileall.compile_dir(
263 self.directory, quiet=True, ddir=ddir,
264 workers=2 if parallel else 1)
265 self.assertTrue(mods)
266 for mod in mods:
267 self.assertTrue(mod.startswith(self.directory), mod)
268 modcode = importlib.util.cache_from_source(mod)
269 modpath = mod[len(self.directory+os.sep):]
270 _, _, err = script_helper.assert_python_failure(modcode)
271 expected_in = os.path.join(ddir, modpath)
272 mod_code_obj = test.test_importlib.util.get_code_from_pyc(modcode)
273 self.assertEqual(mod_code_obj.co_filename, expected_in)
274 self.assertIn(f'"{expected_in}"', os.fsdecode(err))
275
276 def test_ddir_only_one_worker(self):
277 """Recursive compile_dir ddir= contains package paths; bpo39769."""
278 return self._test_ddir_only(ddir="<a prefix>", parallel=False)
279
280 def test_ddir_multiple_workers(self):
281 """Recursive compile_dir ddir= contains package paths; bpo39769."""
282 return self._test_ddir_only(ddir="<a prefix>", parallel=True)
283
284 def test_ddir_empty_only_one_worker(self):
285 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
286 return self._test_ddir_only(ddir="", parallel=False)
287
288 def test_ddir_empty_multiple_workers(self):
289 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
290 return self._test_ddir_only(ddir="", parallel=True)
291
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200292 def test_strip_only(self):
293 fullpath = ["test", "build", "real", "path"]
294 path = os.path.join(self.directory, *fullpath)
295 os.makedirs(path)
296 script = script_helper.make_script(path, "test", "1 / 0")
297 bc = importlib.util.cache_from_source(script)
298 stripdir = os.path.join(self.directory, *fullpath[:2])
299 compileall.compile_dir(path, quiet=True, stripdir=stripdir)
300 rc, out, err = script_helper.assert_python_failure(bc)
301 expected_in = os.path.join(*fullpath[2:])
302 self.assertIn(
303 expected_in,
304 str(err, encoding=sys.getdefaultencoding())
305 )
306 self.assertNotIn(
307 stripdir,
308 str(err, encoding=sys.getdefaultencoding())
309 )
310
311 def test_prepend_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 prependdir = "/foo"
318 compileall.compile_dir(path, quiet=True, prependdir=prependdir)
319 rc, out, err = script_helper.assert_python_failure(bc)
320 expected_in = os.path.join(prependdir, self.directory, *fullpath)
321 self.assertIn(
322 expected_in,
323 str(err, encoding=sys.getdefaultencoding())
324 )
325
326 def test_strip_and_prepend(self):
327 fullpath = ["test", "build", "real", "path"]
328 path = os.path.join(self.directory, *fullpath)
329 os.makedirs(path)
330 script = script_helper.make_script(path, "test", "1 / 0")
331 bc = importlib.util.cache_from_source(script)
332 stripdir = os.path.join(self.directory, *fullpath[:2])
333 prependdir = "/foo"
334 compileall.compile_dir(path, quiet=True,
335 stripdir=stripdir, prependdir=prependdir)
336 rc, out, err = script_helper.assert_python_failure(bc)
337 expected_in = os.path.join(prependdir, *fullpath[2:])
338 self.assertIn(
339 expected_in,
340 str(err, encoding=sys.getdefaultencoding())
341 )
342 self.assertNotIn(
343 stripdir,
344 str(err, encoding=sys.getdefaultencoding())
345 )
346
347 def test_strip_prepend_and_ddir(self):
348 fullpath = ["test", "build", "real", "path", "ddir"]
349 path = os.path.join(self.directory, *fullpath)
350 os.makedirs(path)
351 script_helper.make_script(path, "test", "1 / 0")
352 with self.assertRaises(ValueError):
353 compileall.compile_dir(path, quiet=True, ddir="/bar",
354 stripdir="/foo", prependdir="/bar")
355
356 def test_multiple_optimization_levels(self):
357 script = script_helper.make_script(self.directory,
358 "test_optimization",
359 "a = 0")
360 bc = []
361 for opt_level in "", 1, 2, 3:
362 bc.append(importlib.util.cache_from_source(script,
363 optimization=opt_level))
364 test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]]
365 for opt_combination in test_combinations:
366 compileall.compile_file(script, quiet=True,
367 optimize=opt_combination)
368 for opt_level in opt_combination:
369 self.assertTrue(os.path.isfile(bc[opt_level]))
370 try:
371 os.unlink(bc[opt_level])
372 except Exception:
373 pass
374
Hai Shi883bc632020-07-06 17:12:49 +0800375 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200376 def test_ignore_symlink_destination(self):
377 # Create folders for allowed files, symlinks and prohibited area
378 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
379 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
380 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
381 os.makedirs(allowed_path)
382 os.makedirs(symlinks_path)
383 os.makedirs(prohibited_path)
384
385 # Create scripts and symlinks and remember their byte-compiled versions
386 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
387 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
388 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
389 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
390 os.symlink(allowed_script, allowed_symlink)
391 os.symlink(prohibited_script, prohibited_symlink)
392 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
393 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
394
395 compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path)
396
397 self.assertTrue(os.path.isfile(allowed_bc))
398 self.assertFalse(os.path.isfile(prohibited_bc))
399
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400400
401class CompileallTestsWithSourceEpoch(CompileallTestsBase,
402 unittest.TestCase,
403 metaclass=SourceDateEpochTestMeta,
404 source_date_epoch=True):
405 pass
406
407
408class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
409 unittest.TestCase,
410 metaclass=SourceDateEpochTestMeta,
411 source_date_epoch=False):
412 pass
413
414
Martin v. Löwis4b003072010-03-16 13:19:21 +0000415class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000416 """Issue 6716: compileall should escape source code when printing errors
417 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000418
419 def setUp(self):
420 self.directory = tempfile.mkdtemp()
421 self.source_path = os.path.join(self.directory, '_test.py')
422 with open(self.source_path, 'w', encoding='utf-8') as file:
423 file.write('# -*- coding: utf-8 -*-\n')
424 file.write('print u"\u20ac"\n')
425
426 def tearDown(self):
427 shutil.rmtree(self.directory)
428
429 def test_error(self):
430 try:
431 orig_stdout = sys.stdout
432 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
433 compileall.compile_dir(self.directory)
434 finally:
435 sys.stdout = orig_stdout
436
Barry Warsawc8a99de2010-04-29 18:43:10 +0000437
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400438class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000439 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000440
Brett Cannon65ed7502015-10-09 15:09:43 -0700441 @classmethod
442 def setUpClass(cls):
443 for path in filter(os.path.isdir, sys.path):
444 directory_created = False
445 directory = pathlib.Path(path) / '__pycache__'
446 path = directory / 'test.try'
447 try:
448 if not directory.is_dir():
449 directory.mkdir()
450 directory_created = True
Inada Naoki80017752021-04-02 09:01:57 +0900451 path.write_text('# for test_compileall', encoding="utf-8")
Brett Cannon65ed7502015-10-09 15:09:43 -0700452 except OSError:
453 sys_path_writable = False
454 break
455 finally:
Hai Shi883bc632020-07-06 17:12:49 +0800456 os_helper.unlink(str(path))
Brett Cannon65ed7502015-10-09 15:09:43 -0700457 if directory_created:
458 directory.rmdir()
459 else:
460 sys_path_writable = True
461 cls._sys_path_writable = sys_path_writable
462
463 def _skip_if_sys_path_not_writable(self):
464 if not self._sys_path_writable:
465 raise unittest.SkipTest('not all entries on sys.path are writable')
466
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400467 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100468 return [*support.optim_args_from_interpreter_flags(),
469 '-S', '-m', 'compileall',
470 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400471
R. David Murray5317e9c2010-12-16 19:08:51 +0000472 def assertRunOK(self, *args, **env_vars):
473 rc, out, err = script_helper.assert_python_ok(
Serhiy Storchaka700cfa82020-06-25 17:56:31 +0300474 *self._get_run_args(args), **env_vars,
475 PYTHONIOENCODING='utf-8')
R. David Murray95333e32010-12-14 22:32:50 +0000476 self.assertEqual(b'', err)
477 return out
478
R. David Murray5317e9c2010-12-16 19:08:51 +0000479 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000480 rc, out, err = script_helper.assert_python_failure(
Serhiy Storchaka700cfa82020-06-25 17:56:31 +0300481 *self._get_run_args(args), **env_vars,
482 PYTHONIOENCODING='utf-8')
R. David Murray95333e32010-12-14 22:32:50 +0000483 return rc, out, err
484
485 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400486 path = importlib.util.cache_from_source(fn)
487 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000488
489 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400490 path = importlib.util.cache_from_source(fn)
491 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000492
Barry Warsaw28a691b2010-04-17 00:19:56 +0000493 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000494 self.directory = tempfile.mkdtemp()
Hai Shi883bc632020-07-06 17:12:49 +0800495 self.addCleanup(os_helper.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000496 self.pkgdir = os.path.join(self.directory, 'foo')
497 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000498 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
499 # Create the __init__.py and a package module.
500 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
501 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000502
R. David Murray5317e9c2010-12-16 19:08:51 +0000503 def test_no_args_compiles_path(self):
504 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700505 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000506 bazfn = script_helper.make_script(self.directory, 'baz', '')
507 self.assertRunOK(PYTHONPATH=self.directory)
508 self.assertCompiled(bazfn)
509 self.assertNotCompiled(self.initfn)
510 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000511
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400512 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500513 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700514 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500515 bazfn = script_helper.make_script(self.directory, 'baz', '')
516 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500517 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500518 # Set atime/mtime backward to avoid file timestamp resolution issues
519 os.utime(pycpath, (time.time()-60,)*2)
520 mtime = os.stat(pycpath).st_mtime
521 # Without force, no recompilation
522 self.assertRunOK(PYTHONPATH=self.directory)
523 mtime2 = os.stat(pycpath).st_mtime
524 self.assertEqual(mtime, mtime2)
525 # Now force it.
526 self.assertRunOK('-f', PYTHONPATH=self.directory)
527 mtime2 = os.stat(pycpath).st_mtime
528 self.assertNotEqual(mtime, mtime2)
529
530 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700531 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500532 script_helper.make_script(self.directory, 'baz', '')
533 noisy = self.assertRunOK(PYTHONPATH=self.directory)
534 self.assertIn(b'Listing ', noisy)
535 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
536 self.assertNotIn(b'Listing ', quiet)
537
Georg Brandl1463a3f2010-10-14 07:42:27 +0000538 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400539 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000540 for name, ext, switch in [
541 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400542 ('optimize', 'opt-1.pyc', ['-O']),
543 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000544 ]:
545 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000546 script_helper.assert_python_ok(*(switch +
547 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000548 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000549 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400550 expected = sorted(base.format(sys.implementation.cache_tag, ext)
551 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000552 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000553 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000554 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
555 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000556 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000557
558 def test_legacy_paths(self):
559 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400560 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000561 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000562 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000563 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400564 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
565 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000566 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
567
Barry Warsawc04317f2010-04-26 15:59:03 +0000568 def test_multiple_runs(self):
569 # Bug 8527 reported that multiple calls produced empty
570 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000571 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000572 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000573 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
574 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000575 self.assertFalse(os.path.exists(cachecachedir))
576 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000577 self.assertRunOK('-q', self.pkgdir)
578 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000579 self.assertFalse(os.path.exists(cachecachedir))
580
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400581 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000582 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000583 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400584 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000585 # set atime/mtime backward to avoid file timestamp resolution issues
586 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000587 mtime = os.stat(pycpath).st_mtime
588 # without force, no recompilation
589 self.assertRunOK('-q', self.pkgdir)
590 mtime2 = os.stat(pycpath).st_mtime
591 self.assertEqual(mtime, mtime2)
592 # now force it.
593 self.assertRunOK('-q', '-f', self.pkgdir)
594 mtime2 = os.stat(pycpath).st_mtime
595 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000596
R. David Murray95333e32010-12-14 22:32:50 +0000597 def test_recursion_control(self):
598 subpackage = os.path.join(self.pkgdir, 'spam')
599 os.mkdir(subpackage)
600 subinitfn = script_helper.make_script(subpackage, '__init__', '')
601 hamfn = script_helper.make_script(subpackage, 'ham', '')
602 self.assertRunOK('-q', '-l', self.pkgdir)
603 self.assertNotCompiled(subinitfn)
604 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
605 self.assertRunOK('-q', self.pkgdir)
606 self.assertCompiled(subinitfn)
607 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000608
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500609 def test_recursion_limit(self):
610 subpackage = os.path.join(self.pkgdir, 'spam')
611 subpackage2 = os.path.join(subpackage, 'ham')
612 subpackage3 = os.path.join(subpackage2, 'eggs')
613 for pkg in (subpackage, subpackage2, subpackage3):
614 script_helper.make_pkg(pkg)
615
616 subinitfn = os.path.join(subpackage, '__init__.py')
617 hamfn = script_helper.make_script(subpackage, 'ham', '')
618 spamfn = script_helper.make_script(subpackage2, 'spam', '')
619 eggfn = script_helper.make_script(subpackage3, 'egg', '')
620
621 self.assertRunOK('-q', '-r 0', self.pkgdir)
622 self.assertNotCompiled(subinitfn)
623 self.assertFalse(
624 os.path.exists(os.path.join(subpackage, '__pycache__')))
625
626 self.assertRunOK('-q', '-r 1', self.pkgdir)
627 self.assertCompiled(subinitfn)
628 self.assertCompiled(hamfn)
629 self.assertNotCompiled(spamfn)
630
631 self.assertRunOK('-q', '-r 2', self.pkgdir)
632 self.assertCompiled(subinitfn)
633 self.assertCompiled(hamfn)
634 self.assertCompiled(spamfn)
635 self.assertNotCompiled(eggfn)
636
637 self.assertRunOK('-q', '-r 5', self.pkgdir)
638 self.assertCompiled(subinitfn)
639 self.assertCompiled(hamfn)
640 self.assertCompiled(spamfn)
641 self.assertCompiled(eggfn)
642
Hai Shi883bc632020-07-06 17:12:49 +0800643 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200644 def test_symlink_loop(self):
645 # Currently, compileall ignores symlinks to directories.
646 # If that limitation is ever lifted, it should protect against
647 # recursion in symlink loops.
648 pkg = os.path.join(self.pkgdir, 'spam')
649 script_helper.make_pkg(pkg)
650 os.symlink('.', os.path.join(pkg, 'evil'))
651 os.symlink('.', os.path.join(pkg, 'evil2'))
652 self.assertRunOK('-q', self.pkgdir)
653 self.assertCompiled(os.path.join(
654 self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py'
655 ))
656
R. David Murray650f1472010-11-20 21:18:51 +0000657 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000658 noisy = self.assertRunOK(self.pkgdir)
659 quiet = self.assertRunOK('-q', self.pkgdir)
660 self.assertNotEqual(b'', noisy)
661 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000662
Berker Peksag6554b862014-10-15 11:10:57 +0300663 def test_silent(self):
664 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
665 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
666 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
667 self.assertNotEqual(b'', quiet)
668 self.assertEqual(b'', silent)
669
R. David Murray650f1472010-11-20 21:18:51 +0000670 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400671 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000672 self.assertNotCompiled(self.barfn)
673 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000674
R. David Murray95333e32010-12-14 22:32:50 +0000675 def test_multiple_dirs(self):
676 pkgdir2 = os.path.join(self.directory, 'foo2')
677 os.mkdir(pkgdir2)
678 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
679 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
680 self.assertRunOK('-q', self.pkgdir, pkgdir2)
681 self.assertCompiled(self.initfn)
682 self.assertCompiled(self.barfn)
683 self.assertCompiled(init2fn)
684 self.assertCompiled(bar2fn)
685
R. David Murray95333e32010-12-14 22:32:50 +0000686 def test_d_compile_error(self):
687 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
688 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
689 self.assertRegex(out, b'File "dinsdale')
690
691 def test_d_runtime_error(self):
692 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
693 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
694 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400695 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000696 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
697 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200698 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000699 self.assertRegex(err, b'File "dinsdale')
700
701 def test_include_bad_file(self):
702 rc, out, err = self.assertRunNotOK(
703 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
704 self.assertRegex(out, b'rror.*nosuchfile')
705 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400706 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000707 self.pkgdir_cachedir)))
708
709 def test_include_file_with_arg(self):
710 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
711 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
712 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
713 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Inada Naoki80017752021-04-02 09:01:57 +0900714 with open(os.path.join(self.directory, 'l1'), 'w', encoding="utf-8") as l1:
R. David Murray95333e32010-12-14 22:32:50 +0000715 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
716 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
717 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
718 self.assertCompiled(f1)
719 self.assertCompiled(f2)
720 self.assertNotCompiled(f3)
721 self.assertCompiled(f4)
722
723 def test_include_file_no_arg(self):
724 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
725 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
726 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
727 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Inada Naoki80017752021-04-02 09:01:57 +0900728 with open(os.path.join(self.directory, 'l1'), 'w', encoding="utf-8") as l1:
R. David Murray95333e32010-12-14 22:32:50 +0000729 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
730 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
731 self.assertNotCompiled(f1)
732 self.assertCompiled(f2)
733 self.assertNotCompiled(f3)
734 self.assertNotCompiled(f4)
735
736 def test_include_on_stdin(self):
737 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
738 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
739 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
740 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400741 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000742 p.stdin.write((f3+os.linesep).encode('ascii'))
743 script_helper.kill_python(p)
744 self.assertNotCompiled(f1)
745 self.assertNotCompiled(f2)
746 self.assertCompiled(f3)
747 self.assertNotCompiled(f4)
748
749 def test_compiles_as_much_as_possible(self):
750 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
751 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
752 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000753 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000754 self.assertNotCompiled(bingfn)
755 self.assertCompiled(self.initfn)
756 self.assertCompiled(self.barfn)
757
R. David Murray5317e9c2010-12-16 19:08:51 +0000758 def test_invalid_arg_produces_message(self):
759 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200760 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000761
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800762 def test_pyc_invalidation_mode(self):
763 script_helper.make_script(self.pkgdir, 'f1', '')
764 pyc = importlib.util.cache_from_source(
765 os.path.join(self.pkgdir, 'f1.py'))
766 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
767 with open(pyc, 'rb') as fp:
768 data = fp.read()
769 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
770 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
771 with open(pyc, 'rb') as fp:
772 data = fp.read()
773 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
774
Brett Cannonf1a8df02014-09-12 10:39:48 -0400775 @skipUnless(_have_multiprocessing, "requires multiprocessing")
776 def test_workers(self):
777 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
778 files = []
779 for suffix in range(5):
780 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
781 os.mkdir(pkgdir)
782 fn = script_helper.make_script(pkgdir, '__init__', '')
783 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
784
785 self.assertRunOK(self.directory, '-j', '0')
786 self.assertCompiled(bar2fn)
787 for file in files:
788 self.assertCompiled(file)
789
790 @mock.patch('compileall.compile_dir')
791 def test_workers_available_cores(self, compile_dir):
792 with mock.patch("sys.argv",
793 new=[sys.executable, self.directory, "-j0"]):
794 compileall.main()
795 self.assertTrue(compile_dir.called)
Antoine Pitrou1a2dd822019-05-15 23:45:18 +0200796 self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400797
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200798 def test_strip_and_prepend(self):
799 fullpath = ["test", "build", "real", "path"]
800 path = os.path.join(self.directory, *fullpath)
801 os.makedirs(path)
802 script = script_helper.make_script(path, "test", "1 / 0")
803 bc = importlib.util.cache_from_source(script)
804 stripdir = os.path.join(self.directory, *fullpath[:2])
805 prependdir = "/foo"
806 self.assertRunOK("-s", stripdir, "-p", prependdir, path)
807 rc, out, err = script_helper.assert_python_failure(bc)
808 expected_in = os.path.join(prependdir, *fullpath[2:])
809 self.assertIn(
810 expected_in,
811 str(err, encoding=sys.getdefaultencoding())
812 )
813 self.assertNotIn(
814 stripdir,
815 str(err, encoding=sys.getdefaultencoding())
816 )
817
818 def test_multiple_optimization_levels(self):
819 path = os.path.join(self.directory, "optimizations")
820 os.makedirs(path)
821 script = script_helper.make_script(path,
822 "test_optimization",
823 "a = 0")
824 bc = []
825 for opt_level in "", 1, 2, 3:
826 bc.append(importlib.util.cache_from_source(script,
827 optimization=opt_level))
828 test_combinations = [["0", "1"],
829 ["1", "2"],
830 ["0", "2"],
831 ["0", "1", "2"]]
832 for opt_combination in test_combinations:
833 self.assertRunOK(path, *("-o" + str(n) for n in opt_combination))
834 for opt_level in opt_combination:
835 self.assertTrue(os.path.isfile(bc[int(opt_level)]))
836 try:
837 os.unlink(bc[opt_level])
838 except Exception:
839 pass
840
Hai Shi883bc632020-07-06 17:12:49 +0800841 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200842 def test_ignore_symlink_destination(self):
843 # Create folders for allowed files, symlinks and prohibited area
844 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
845 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
846 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
847 os.makedirs(allowed_path)
848 os.makedirs(symlinks_path)
849 os.makedirs(prohibited_path)
850
851 # Create scripts and symlinks and remember their byte-compiled versions
852 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
853 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
854 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
855 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
856 os.symlink(allowed_script, allowed_symlink)
857 os.symlink(prohibited_script, prohibited_symlink)
858 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
859 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
860
861 self.assertRunOK(symlinks_path, "-e", allowed_path)
862
863 self.assertTrue(os.path.isfile(allowed_bc))
864 self.assertFalse(os.path.isfile(prohibited_bc))
865
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200866 def test_hardlink_bad_args(self):
867 # Bad arguments combination, hardlink deduplication make sense
868 # only for more than one optimization level
869 self.assertRunNotOK(self.directory, "-o 1", "--hardlink-dupes")
870
871 def test_hardlink(self):
872 # 'a = 0' code produces the same bytecode for the 3 optimization
873 # levels. All three .pyc files must have the same inode (hardlinks).
874 #
875 # If deduplication is disabled, all pyc files must have different
876 # inodes.
877 for dedup in (True, False):
878 with tempfile.TemporaryDirectory() as path:
879 with self.subTest(dedup=dedup):
880 script = script_helper.make_script(path, "script", "a = 0")
881 pycs = get_pycs(script)
882
883 args = ["-q", "-o 0", "-o 1", "-o 2"]
884 if dedup:
885 args.append("--hardlink-dupes")
886 self.assertRunOK(path, *args)
887
888 self.assertEqual(is_hardlink(pycs[0], pycs[1]), dedup)
889 self.assertEqual(is_hardlink(pycs[1], pycs[2]), dedup)
890 self.assertEqual(is_hardlink(pycs[0], pycs[2]), dedup)
891
Barry Warsaw28a691b2010-04-17 00:19:56 +0000892
Min ho Kimc4cacc82019-07-31 08:16:13 +1000893class CommandLineTestsWithSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400894 unittest.TestCase,
895 metaclass=SourceDateEpochTestMeta,
896 source_date_epoch=True):
897 pass
898
899
Min ho Kimc4cacc82019-07-31 08:16:13 +1000900class CommandLineTestsNoSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400901 unittest.TestCase,
902 metaclass=SourceDateEpochTestMeta,
903 source_date_epoch=False):
904 pass
905
906
907
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200908class HardlinkDedupTestsBase:
909 # Test hardlink_dupes parameter of compileall.compile_dir()
910
911 def setUp(self):
912 self.path = None
913
914 @contextlib.contextmanager
915 def temporary_directory(self):
916 with tempfile.TemporaryDirectory() as path:
917 self.path = path
918 yield path
919 self.path = None
920
921 def make_script(self, code, name="script"):
922 return script_helper.make_script(self.path, name, code)
923
924 def compile_dir(self, *, dedup=True, optimize=(0, 1, 2), force=False):
925 compileall.compile_dir(self.path, quiet=True, optimize=optimize,
926 hardlink_dupes=dedup, force=force)
927
928 def test_bad_args(self):
929 # Bad arguments combination, hardlink deduplication make sense
930 # only for more than one optimization level
931 with self.temporary_directory():
932 self.make_script("pass")
933 with self.assertRaises(ValueError):
934 compileall.compile_dir(self.path, quiet=True, optimize=0,
935 hardlink_dupes=True)
936 with self.assertRaises(ValueError):
937 # same optimization level specified twice:
938 # compile_dir() removes duplicates
939 compileall.compile_dir(self.path, quiet=True, optimize=[0, 0],
940 hardlink_dupes=True)
941
942 def create_code(self, docstring=False, assertion=False):
943 lines = []
944 if docstring:
945 lines.append("'module docstring'")
946 lines.append('x = 1')
947 if assertion:
948 lines.append("assert x == 1")
949 return '\n'.join(lines)
950
951 def iter_codes(self):
952 for docstring in (False, True):
953 for assertion in (False, True):
954 code = self.create_code(docstring=docstring, assertion=assertion)
955 yield (code, docstring, assertion)
956
957 def test_disabled(self):
958 # Deduplication disabled, no hardlinks
959 for code, docstring, assertion in self.iter_codes():
960 with self.subTest(docstring=docstring, assertion=assertion):
961 with self.temporary_directory():
962 script = self.make_script(code)
963 pycs = get_pycs(script)
964 self.compile_dir(dedup=False)
965 self.assertFalse(is_hardlink(pycs[0], pycs[1]))
966 self.assertFalse(is_hardlink(pycs[0], pycs[2]))
967 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
968
969 def check_hardlinks(self, script, docstring=False, assertion=False):
970 pycs = get_pycs(script)
971 self.assertEqual(is_hardlink(pycs[0], pycs[1]),
972 not assertion)
973 self.assertEqual(is_hardlink(pycs[0], pycs[2]),
974 not assertion and not docstring)
975 self.assertEqual(is_hardlink(pycs[1], pycs[2]),
976 not docstring)
977
978 def test_hardlink(self):
979 # Test deduplication on all combinations
980 for code, docstring, assertion in self.iter_codes():
981 with self.subTest(docstring=docstring, assertion=assertion):
982 with self.temporary_directory():
983 script = self.make_script(code)
984 self.compile_dir()
985 self.check_hardlinks(script, docstring, assertion)
986
987 def test_only_two_levels(self):
988 # Don't build the 3 optimization levels, but only 2
989 for opts in ((0, 1), (1, 2), (0, 2)):
990 with self.subTest(opts=opts):
991 with self.temporary_directory():
992 # code with no dostring and no assertion:
993 # same bytecode for all optimization levels
994 script = self.make_script(self.create_code())
995 self.compile_dir(optimize=opts)
996 pyc1 = get_pyc(script, opts[0])
997 pyc2 = get_pyc(script, opts[1])
998 self.assertTrue(is_hardlink(pyc1, pyc2))
999
1000 def test_duplicated_levels(self):
1001 # compile_dir() must not fail if optimize contains duplicated
1002 # optimization levels and/or if optimization levels are not sorted.
1003 with self.temporary_directory():
1004 # code with no dostring and no assertion:
1005 # same bytecode for all optimization levels
1006 script = self.make_script(self.create_code())
1007 self.compile_dir(optimize=[1, 0, 1, 0])
1008 pyc1 = get_pyc(script, 0)
1009 pyc2 = get_pyc(script, 1)
1010 self.assertTrue(is_hardlink(pyc1, pyc2))
1011
1012 def test_recompilation(self):
1013 # Test compile_dir() when pyc files already exists and the script
1014 # content changed
1015 with self.temporary_directory():
1016 script = self.make_script("a = 0")
1017 self.compile_dir()
1018 # All three levels have the same inode
1019 self.check_hardlinks(script)
1020
1021 pycs = get_pycs(script)
1022 inode = os.stat(pycs[0]).st_ino
1023
1024 # Change of the module content
1025 script = self.make_script("print(0)")
1026
1027 # Recompilation without -o 1
1028 self.compile_dir(optimize=[0, 2], force=True)
1029
1030 # opt-1.pyc should have the same inode as before and others should not
1031 self.assertEqual(inode, os.stat(pycs[1]).st_ino)
1032 self.assertTrue(is_hardlink(pycs[0], pycs[2]))
1033 self.assertNotEqual(inode, os.stat(pycs[2]).st_ino)
1034 # opt-1.pyc and opt-2.pyc have different content
1035 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1036
1037 def test_import(self):
1038 # Test that import updates a single pyc file when pyc files already
1039 # exists and the script content changed
1040 with self.temporary_directory():
1041 script = self.make_script(self.create_code(), name="module")
1042 self.compile_dir()
1043 # All three levels have the same inode
1044 self.check_hardlinks(script)
1045
1046 pycs = get_pycs(script)
1047 inode = os.stat(pycs[0]).st_ino
1048
1049 # Change of the module content
1050 script = self.make_script("print(0)", name="module")
1051
1052 # Import the module in Python with -O (optimization level 1)
1053 script_helper.assert_python_ok(
1054 "-O", "-c", "import module", __isolated=False, PYTHONPATH=self.path
1055 )
1056
1057 # Only opt-1.pyc is changed
1058 self.assertEqual(inode, os.stat(pycs[0]).st_ino)
1059 self.assertEqual(inode, os.stat(pycs[2]).st_ino)
1060 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
1061 # opt-1.pyc and opt-2.pyc have different content
1062 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1063
1064
1065class HardlinkDedupTestsWithSourceEpoch(HardlinkDedupTestsBase,
1066 unittest.TestCase,
1067 metaclass=SourceDateEpochTestMeta,
1068 source_date_epoch=True):
1069 pass
1070
1071
1072class HardlinkDedupTestsNoSourceEpoch(HardlinkDedupTestsBase,
1073 unittest.TestCase,
1074 metaclass=SourceDateEpochTestMeta,
1075 source_date_epoch=False):
1076 pass
1077
1078
Brett Cannonbefb14f2009-02-10 02:10:16 +00001079if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -04001080 unittest.main()