blob: 96a0f8f729aa4eba84a9b1df89380971f668d079 [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
Georg Brandl8334fd92010-12-04 10:26:46 +0000172 def test_optimize(self):
173 # make sure compiling with different optimization settings than the
174 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400175 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000176 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400177 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400178 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000179 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400180 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400181 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000182 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400183 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400184 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000185 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000186
Berker Peksag812a2b62016-10-01 00:54:18 +0300187 def test_compile_dir_pathlike(self):
188 self.assertFalse(os.path.isfile(self.bc_path))
189 with support.captured_stdout() as stdout:
190 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300191 line = stdout.getvalue().splitlines()[0]
192 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300193 self.assertTrue(os.path.isfile(self.bc_path))
194
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800195 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500196 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400197 def test_compile_pool_called(self, pool_mock):
198 compileall.compile_dir(self.directory, quiet=True, workers=5)
199 self.assertTrue(pool_mock.called)
200
201 def test_compile_workers_non_positive(self):
202 with self.assertRaisesRegex(ValueError,
203 "workers must be greater or equal to 0"):
204 compileall.compile_dir(self.directory, workers=-1)
205
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800206 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500207 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400208 def test_compile_workers_cpu_count(self, pool_mock):
209 compileall.compile_dir(self.directory, quiet=True, workers=0)
210 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
211
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -0800212 @skipUnless(_have_multiprocessing, "requires multiprocessing")
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500213 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400214 @mock.patch('compileall.compile_file')
215 def test_compile_one_worker(self, compile_file_mock, pool_mock):
216 compileall.compile_dir(self.directory, quiet=True)
217 self.assertFalse(pool_mock.called)
218 self.assertTrue(compile_file_mock.called)
219
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500220 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300221 @mock.patch('compileall.compile_file')
222 def test_compile_missing_multiprocessing(self, compile_file_mock):
223 compileall.compile_dir(self.directory, quiet=True, workers=5)
224 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000225
Petr Viktorin4267c982019-09-26 11:53:51 +0200226 def test_compile_dir_maxlevels(self):
Victor Stinnereb1dda22019-10-15 11:26:13 +0200227 # Test the actual impact of maxlevels parameter
228 depth = 3
229 path = self.directory
230 for i in range(1, depth + 1):
231 path = os.path.join(path, f"dir_{i}")
232 source = os.path.join(path, 'script.py')
233 os.mkdir(path)
234 shutil.copyfile(self.source_path, source)
235 pyc_filename = importlib.util.cache_from_source(source)
236
237 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth - 1)
238 self.assertFalse(os.path.isfile(pyc_filename))
239
240 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth)
241 self.assertTrue(os.path.isfile(pyc_filename))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200242
Gregory P. Smith02673352020-02-28 17:28:37 -0800243 def _test_ddir_only(self, *, ddir, parallel=True):
244 """Recursive compile_dir ddir must contain package paths; bpo39769."""
245 fullpath = ["test", "foo"]
246 path = self.directory
247 mods = []
248 for subdir in fullpath:
249 path = os.path.join(path, subdir)
250 os.mkdir(path)
251 script_helper.make_script(path, "__init__", "")
252 mods.append(script_helper.make_script(path, "mod",
253 "def fn(): 1/0\nfn()\n"))
254 compileall.compile_dir(
255 self.directory, quiet=True, ddir=ddir,
256 workers=2 if parallel else 1)
257 self.assertTrue(mods)
258 for mod in mods:
259 self.assertTrue(mod.startswith(self.directory), mod)
260 modcode = importlib.util.cache_from_source(mod)
261 modpath = mod[len(self.directory+os.sep):]
262 _, _, err = script_helper.assert_python_failure(modcode)
263 expected_in = os.path.join(ddir, modpath)
264 mod_code_obj = test.test_importlib.util.get_code_from_pyc(modcode)
265 self.assertEqual(mod_code_obj.co_filename, expected_in)
266 self.assertIn(f'"{expected_in}"', os.fsdecode(err))
267
268 def test_ddir_only_one_worker(self):
269 """Recursive compile_dir ddir= contains package paths; bpo39769."""
270 return self._test_ddir_only(ddir="<a prefix>", parallel=False)
271
272 def test_ddir_multiple_workers(self):
273 """Recursive compile_dir ddir= contains package paths; bpo39769."""
274 return self._test_ddir_only(ddir="<a prefix>", parallel=True)
275
276 def test_ddir_empty_only_one_worker(self):
277 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
278 return self._test_ddir_only(ddir="", parallel=False)
279
280 def test_ddir_empty_multiple_workers(self):
281 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
282 return self._test_ddir_only(ddir="", parallel=True)
283
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200284 def test_strip_only(self):
285 fullpath = ["test", "build", "real", "path"]
286 path = os.path.join(self.directory, *fullpath)
287 os.makedirs(path)
288 script = script_helper.make_script(path, "test", "1 / 0")
289 bc = importlib.util.cache_from_source(script)
290 stripdir = os.path.join(self.directory, *fullpath[:2])
291 compileall.compile_dir(path, quiet=True, stripdir=stripdir)
292 rc, out, err = script_helper.assert_python_failure(bc)
293 expected_in = os.path.join(*fullpath[2:])
294 self.assertIn(
295 expected_in,
296 str(err, encoding=sys.getdefaultencoding())
297 )
298 self.assertNotIn(
299 stripdir,
300 str(err, encoding=sys.getdefaultencoding())
301 )
302
303 def test_prepend_only(self):
304 fullpath = ["test", "build", "real", "path"]
305 path = os.path.join(self.directory, *fullpath)
306 os.makedirs(path)
307 script = script_helper.make_script(path, "test", "1 / 0")
308 bc = importlib.util.cache_from_source(script)
309 prependdir = "/foo"
310 compileall.compile_dir(path, quiet=True, prependdir=prependdir)
311 rc, out, err = script_helper.assert_python_failure(bc)
312 expected_in = os.path.join(prependdir, self.directory, *fullpath)
313 self.assertIn(
314 expected_in,
315 str(err, encoding=sys.getdefaultencoding())
316 )
317
318 def test_strip_and_prepend(self):
319 fullpath = ["test", "build", "real", "path"]
320 path = os.path.join(self.directory, *fullpath)
321 os.makedirs(path)
322 script = script_helper.make_script(path, "test", "1 / 0")
323 bc = importlib.util.cache_from_source(script)
324 stripdir = os.path.join(self.directory, *fullpath[:2])
325 prependdir = "/foo"
326 compileall.compile_dir(path, quiet=True,
327 stripdir=stripdir, prependdir=prependdir)
328 rc, out, err = script_helper.assert_python_failure(bc)
329 expected_in = os.path.join(prependdir, *fullpath[2:])
330 self.assertIn(
331 expected_in,
332 str(err, encoding=sys.getdefaultencoding())
333 )
334 self.assertNotIn(
335 stripdir,
336 str(err, encoding=sys.getdefaultencoding())
337 )
338
339 def test_strip_prepend_and_ddir(self):
340 fullpath = ["test", "build", "real", "path", "ddir"]
341 path = os.path.join(self.directory, *fullpath)
342 os.makedirs(path)
343 script_helper.make_script(path, "test", "1 / 0")
344 with self.assertRaises(ValueError):
345 compileall.compile_dir(path, quiet=True, ddir="/bar",
346 stripdir="/foo", prependdir="/bar")
347
348 def test_multiple_optimization_levels(self):
349 script = script_helper.make_script(self.directory,
350 "test_optimization",
351 "a = 0")
352 bc = []
353 for opt_level in "", 1, 2, 3:
354 bc.append(importlib.util.cache_from_source(script,
355 optimization=opt_level))
356 test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]]
357 for opt_combination in test_combinations:
358 compileall.compile_file(script, quiet=True,
359 optimize=opt_combination)
360 for opt_level in opt_combination:
361 self.assertTrue(os.path.isfile(bc[opt_level]))
362 try:
363 os.unlink(bc[opt_level])
364 except Exception:
365 pass
366
Hai Shi883bc632020-07-06 17:12:49 +0800367 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200368 def test_ignore_symlink_destination(self):
369 # Create folders for allowed files, symlinks and prohibited area
370 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
371 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
372 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
373 os.makedirs(allowed_path)
374 os.makedirs(symlinks_path)
375 os.makedirs(prohibited_path)
376
377 # Create scripts and symlinks and remember their byte-compiled versions
378 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
379 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
380 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
381 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
382 os.symlink(allowed_script, allowed_symlink)
383 os.symlink(prohibited_script, prohibited_symlink)
384 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
385 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
386
387 compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path)
388
389 self.assertTrue(os.path.isfile(allowed_bc))
390 self.assertFalse(os.path.isfile(prohibited_bc))
391
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400392
393class CompileallTestsWithSourceEpoch(CompileallTestsBase,
394 unittest.TestCase,
395 metaclass=SourceDateEpochTestMeta,
396 source_date_epoch=True):
397 pass
398
399
400class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
401 unittest.TestCase,
402 metaclass=SourceDateEpochTestMeta,
403 source_date_epoch=False):
404 pass
405
406
Martin v. Löwis4b003072010-03-16 13:19:21 +0000407class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000408 """Issue 6716: compileall should escape source code when printing errors
409 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000410
411 def setUp(self):
412 self.directory = tempfile.mkdtemp()
413 self.source_path = os.path.join(self.directory, '_test.py')
414 with open(self.source_path, 'w', encoding='utf-8') as file:
415 file.write('# -*- coding: utf-8 -*-\n')
416 file.write('print u"\u20ac"\n')
417
418 def tearDown(self):
419 shutil.rmtree(self.directory)
420
421 def test_error(self):
422 try:
423 orig_stdout = sys.stdout
424 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
425 compileall.compile_dir(self.directory)
426 finally:
427 sys.stdout = orig_stdout
428
Barry Warsawc8a99de2010-04-29 18:43:10 +0000429
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400430class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000431 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000432
Brett Cannon65ed7502015-10-09 15:09:43 -0700433 @classmethod
434 def setUpClass(cls):
435 for path in filter(os.path.isdir, sys.path):
436 directory_created = False
437 directory = pathlib.Path(path) / '__pycache__'
438 path = directory / 'test.try'
439 try:
440 if not directory.is_dir():
441 directory.mkdir()
442 directory_created = True
Inada Naoki80017752021-04-02 09:01:57 +0900443 path.write_text('# for test_compileall', encoding="utf-8")
Brett Cannon65ed7502015-10-09 15:09:43 -0700444 except OSError:
445 sys_path_writable = False
446 break
447 finally:
Hai Shi883bc632020-07-06 17:12:49 +0800448 os_helper.unlink(str(path))
Brett Cannon65ed7502015-10-09 15:09:43 -0700449 if directory_created:
450 directory.rmdir()
451 else:
452 sys_path_writable = True
453 cls._sys_path_writable = sys_path_writable
454
455 def _skip_if_sys_path_not_writable(self):
456 if not self._sys_path_writable:
457 raise unittest.SkipTest('not all entries on sys.path are writable')
458
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400459 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100460 return [*support.optim_args_from_interpreter_flags(),
461 '-S', '-m', 'compileall',
462 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400463
R. David Murray5317e9c2010-12-16 19:08:51 +0000464 def assertRunOK(self, *args, **env_vars):
465 rc, out, err = script_helper.assert_python_ok(
Serhiy Storchaka700cfa82020-06-25 17:56:31 +0300466 *self._get_run_args(args), **env_vars,
467 PYTHONIOENCODING='utf-8')
R. David Murray95333e32010-12-14 22:32:50 +0000468 self.assertEqual(b'', err)
469 return out
470
R. David Murray5317e9c2010-12-16 19:08:51 +0000471 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000472 rc, out, err = script_helper.assert_python_failure(
Serhiy Storchaka700cfa82020-06-25 17:56:31 +0300473 *self._get_run_args(args), **env_vars,
474 PYTHONIOENCODING='utf-8')
R. David Murray95333e32010-12-14 22:32:50 +0000475 return rc, out, err
476
477 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400478 path = importlib.util.cache_from_source(fn)
479 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000480
481 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400482 path = importlib.util.cache_from_source(fn)
483 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000484
Barry Warsaw28a691b2010-04-17 00:19:56 +0000485 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000486 self.directory = tempfile.mkdtemp()
Hai Shi883bc632020-07-06 17:12:49 +0800487 self.addCleanup(os_helper.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000488 self.pkgdir = os.path.join(self.directory, 'foo')
489 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000490 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
491 # Create the __init__.py and a package module.
492 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
493 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000494
R. David Murray5317e9c2010-12-16 19:08:51 +0000495 def test_no_args_compiles_path(self):
496 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700497 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000498 bazfn = script_helper.make_script(self.directory, 'baz', '')
499 self.assertRunOK(PYTHONPATH=self.directory)
500 self.assertCompiled(bazfn)
501 self.assertNotCompiled(self.initfn)
502 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000503
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400504 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500505 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700506 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500507 bazfn = script_helper.make_script(self.directory, 'baz', '')
508 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500509 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500510 # Set atime/mtime backward to avoid file timestamp resolution issues
511 os.utime(pycpath, (time.time()-60,)*2)
512 mtime = os.stat(pycpath).st_mtime
513 # Without force, no recompilation
514 self.assertRunOK(PYTHONPATH=self.directory)
515 mtime2 = os.stat(pycpath).st_mtime
516 self.assertEqual(mtime, mtime2)
517 # Now force it.
518 self.assertRunOK('-f', PYTHONPATH=self.directory)
519 mtime2 = os.stat(pycpath).st_mtime
520 self.assertNotEqual(mtime, mtime2)
521
522 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700523 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500524 script_helper.make_script(self.directory, 'baz', '')
525 noisy = self.assertRunOK(PYTHONPATH=self.directory)
526 self.assertIn(b'Listing ', noisy)
527 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
528 self.assertNotIn(b'Listing ', quiet)
529
Georg Brandl1463a3f2010-10-14 07:42:27 +0000530 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400531 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000532 for name, ext, switch in [
533 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400534 ('optimize', 'opt-1.pyc', ['-O']),
535 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000536 ]:
537 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000538 script_helper.assert_python_ok(*(switch +
539 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000540 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000541 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400542 expected = sorted(base.format(sys.implementation.cache_tag, ext)
543 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000544 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000545 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000546 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
547 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000548 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549
550 def test_legacy_paths(self):
551 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400552 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000553 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000554 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000555 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400556 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
557 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000558 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
559
Barry Warsawc04317f2010-04-26 15:59:03 +0000560 def test_multiple_runs(self):
561 # Bug 8527 reported that multiple calls produced empty
562 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000563 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000564 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000565 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
566 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000567 self.assertFalse(os.path.exists(cachecachedir))
568 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000569 self.assertRunOK('-q', self.pkgdir)
570 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000571 self.assertFalse(os.path.exists(cachecachedir))
572
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400573 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000574 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000575 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400576 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000577 # set atime/mtime backward to avoid file timestamp resolution issues
578 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000579 mtime = os.stat(pycpath).st_mtime
580 # without force, no recompilation
581 self.assertRunOK('-q', self.pkgdir)
582 mtime2 = os.stat(pycpath).st_mtime
583 self.assertEqual(mtime, mtime2)
584 # now force it.
585 self.assertRunOK('-q', '-f', self.pkgdir)
586 mtime2 = os.stat(pycpath).st_mtime
587 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000588
R. David Murray95333e32010-12-14 22:32:50 +0000589 def test_recursion_control(self):
590 subpackage = os.path.join(self.pkgdir, 'spam')
591 os.mkdir(subpackage)
592 subinitfn = script_helper.make_script(subpackage, '__init__', '')
593 hamfn = script_helper.make_script(subpackage, 'ham', '')
594 self.assertRunOK('-q', '-l', self.pkgdir)
595 self.assertNotCompiled(subinitfn)
596 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
597 self.assertRunOK('-q', self.pkgdir)
598 self.assertCompiled(subinitfn)
599 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000600
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500601 def test_recursion_limit(self):
602 subpackage = os.path.join(self.pkgdir, 'spam')
603 subpackage2 = os.path.join(subpackage, 'ham')
604 subpackage3 = os.path.join(subpackage2, 'eggs')
605 for pkg in (subpackage, subpackage2, subpackage3):
606 script_helper.make_pkg(pkg)
607
608 subinitfn = os.path.join(subpackage, '__init__.py')
609 hamfn = script_helper.make_script(subpackage, 'ham', '')
610 spamfn = script_helper.make_script(subpackage2, 'spam', '')
611 eggfn = script_helper.make_script(subpackage3, 'egg', '')
612
613 self.assertRunOK('-q', '-r 0', self.pkgdir)
614 self.assertNotCompiled(subinitfn)
615 self.assertFalse(
616 os.path.exists(os.path.join(subpackage, '__pycache__')))
617
618 self.assertRunOK('-q', '-r 1', self.pkgdir)
619 self.assertCompiled(subinitfn)
620 self.assertCompiled(hamfn)
621 self.assertNotCompiled(spamfn)
622
623 self.assertRunOK('-q', '-r 2', self.pkgdir)
624 self.assertCompiled(subinitfn)
625 self.assertCompiled(hamfn)
626 self.assertCompiled(spamfn)
627 self.assertNotCompiled(eggfn)
628
629 self.assertRunOK('-q', '-r 5', self.pkgdir)
630 self.assertCompiled(subinitfn)
631 self.assertCompiled(hamfn)
632 self.assertCompiled(spamfn)
633 self.assertCompiled(eggfn)
634
Hai Shi883bc632020-07-06 17:12:49 +0800635 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200636 def test_symlink_loop(self):
637 # Currently, compileall ignores symlinks to directories.
638 # If that limitation is ever lifted, it should protect against
639 # recursion in symlink loops.
640 pkg = os.path.join(self.pkgdir, 'spam')
641 script_helper.make_pkg(pkg)
642 os.symlink('.', os.path.join(pkg, 'evil'))
643 os.symlink('.', os.path.join(pkg, 'evil2'))
644 self.assertRunOK('-q', self.pkgdir)
645 self.assertCompiled(os.path.join(
646 self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py'
647 ))
648
R. David Murray650f1472010-11-20 21:18:51 +0000649 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000650 noisy = self.assertRunOK(self.pkgdir)
651 quiet = self.assertRunOK('-q', self.pkgdir)
652 self.assertNotEqual(b'', noisy)
653 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000654
Berker Peksag6554b862014-10-15 11:10:57 +0300655 def test_silent(self):
656 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
657 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
658 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
659 self.assertNotEqual(b'', quiet)
660 self.assertEqual(b'', silent)
661
R. David Murray650f1472010-11-20 21:18:51 +0000662 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400663 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000664 self.assertNotCompiled(self.barfn)
665 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000666
R. David Murray95333e32010-12-14 22:32:50 +0000667 def test_multiple_dirs(self):
668 pkgdir2 = os.path.join(self.directory, 'foo2')
669 os.mkdir(pkgdir2)
670 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
671 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
672 self.assertRunOK('-q', self.pkgdir, pkgdir2)
673 self.assertCompiled(self.initfn)
674 self.assertCompiled(self.barfn)
675 self.assertCompiled(init2fn)
676 self.assertCompiled(bar2fn)
677
R. David Murray95333e32010-12-14 22:32:50 +0000678 def test_d_compile_error(self):
679 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
680 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
681 self.assertRegex(out, b'File "dinsdale')
682
683 def test_d_runtime_error(self):
684 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
685 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
686 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400687 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000688 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
689 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200690 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000691 self.assertRegex(err, b'File "dinsdale')
692
693 def test_include_bad_file(self):
694 rc, out, err = self.assertRunNotOK(
695 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
696 self.assertRegex(out, b'rror.*nosuchfile')
697 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400698 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000699 self.pkgdir_cachedir)))
700
701 def test_include_file_with_arg(self):
702 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
703 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
704 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
705 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Inada Naoki80017752021-04-02 09:01:57 +0900706 with open(os.path.join(self.directory, 'l1'), 'w', encoding="utf-8") as l1:
R. David Murray95333e32010-12-14 22:32:50 +0000707 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
708 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
709 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
710 self.assertCompiled(f1)
711 self.assertCompiled(f2)
712 self.assertNotCompiled(f3)
713 self.assertCompiled(f4)
714
715 def test_include_file_no_arg(self):
716 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
717 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
718 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
719 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Inada Naoki80017752021-04-02 09:01:57 +0900720 with open(os.path.join(self.directory, 'l1'), 'w', encoding="utf-8") as l1:
R. David Murray95333e32010-12-14 22:32:50 +0000721 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
722 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
723 self.assertNotCompiled(f1)
724 self.assertCompiled(f2)
725 self.assertNotCompiled(f3)
726 self.assertNotCompiled(f4)
727
728 def test_include_on_stdin(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', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400733 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000734 p.stdin.write((f3+os.linesep).encode('ascii'))
735 script_helper.kill_python(p)
736 self.assertNotCompiled(f1)
737 self.assertNotCompiled(f2)
738 self.assertCompiled(f3)
739 self.assertNotCompiled(f4)
740
741 def test_compiles_as_much_as_possible(self):
742 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
743 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
744 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000745 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000746 self.assertNotCompiled(bingfn)
747 self.assertCompiled(self.initfn)
748 self.assertCompiled(self.barfn)
749
R. David Murray5317e9c2010-12-16 19:08:51 +0000750 def test_invalid_arg_produces_message(self):
751 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200752 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000753
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800754 def test_pyc_invalidation_mode(self):
755 script_helper.make_script(self.pkgdir, 'f1', '')
756 pyc = importlib.util.cache_from_source(
757 os.path.join(self.pkgdir, 'f1.py'))
758 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
759 with open(pyc, 'rb') as fp:
760 data = fp.read()
761 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
762 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
763 with open(pyc, 'rb') as fp:
764 data = fp.read()
765 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
766
Brett Cannonf1a8df02014-09-12 10:39:48 -0400767 @skipUnless(_have_multiprocessing, "requires multiprocessing")
768 def test_workers(self):
769 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
770 files = []
771 for suffix in range(5):
772 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
773 os.mkdir(pkgdir)
774 fn = script_helper.make_script(pkgdir, '__init__', '')
775 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
776
777 self.assertRunOK(self.directory, '-j', '0')
778 self.assertCompiled(bar2fn)
779 for file in files:
780 self.assertCompiled(file)
781
782 @mock.patch('compileall.compile_dir')
783 def test_workers_available_cores(self, compile_dir):
784 with mock.patch("sys.argv",
785 new=[sys.executable, self.directory, "-j0"]):
786 compileall.main()
787 self.assertTrue(compile_dir.called)
Antoine Pitrou1a2dd822019-05-15 23:45:18 +0200788 self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400789
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200790 def test_strip_and_prepend(self):
791 fullpath = ["test", "build", "real", "path"]
792 path = os.path.join(self.directory, *fullpath)
793 os.makedirs(path)
794 script = script_helper.make_script(path, "test", "1 / 0")
795 bc = importlib.util.cache_from_source(script)
796 stripdir = os.path.join(self.directory, *fullpath[:2])
797 prependdir = "/foo"
798 self.assertRunOK("-s", stripdir, "-p", prependdir, path)
799 rc, out, err = script_helper.assert_python_failure(bc)
800 expected_in = os.path.join(prependdir, *fullpath[2:])
801 self.assertIn(
802 expected_in,
803 str(err, encoding=sys.getdefaultencoding())
804 )
805 self.assertNotIn(
806 stripdir,
807 str(err, encoding=sys.getdefaultencoding())
808 )
809
810 def test_multiple_optimization_levels(self):
811 path = os.path.join(self.directory, "optimizations")
812 os.makedirs(path)
813 script = script_helper.make_script(path,
814 "test_optimization",
815 "a = 0")
816 bc = []
817 for opt_level in "", 1, 2, 3:
818 bc.append(importlib.util.cache_from_source(script,
819 optimization=opt_level))
820 test_combinations = [["0", "1"],
821 ["1", "2"],
822 ["0", "2"],
823 ["0", "1", "2"]]
824 for opt_combination in test_combinations:
825 self.assertRunOK(path, *("-o" + str(n) for n in opt_combination))
826 for opt_level in opt_combination:
827 self.assertTrue(os.path.isfile(bc[int(opt_level)]))
828 try:
829 os.unlink(bc[opt_level])
830 except Exception:
831 pass
832
Hai Shi883bc632020-07-06 17:12:49 +0800833 @os_helper.skip_unless_symlink
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200834 def test_ignore_symlink_destination(self):
835 # Create folders for allowed files, symlinks and prohibited area
836 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
837 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
838 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
839 os.makedirs(allowed_path)
840 os.makedirs(symlinks_path)
841 os.makedirs(prohibited_path)
842
843 # Create scripts and symlinks and remember their byte-compiled versions
844 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
845 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
846 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
847 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
848 os.symlink(allowed_script, allowed_symlink)
849 os.symlink(prohibited_script, prohibited_symlink)
850 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
851 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
852
853 self.assertRunOK(symlinks_path, "-e", allowed_path)
854
855 self.assertTrue(os.path.isfile(allowed_bc))
856 self.assertFalse(os.path.isfile(prohibited_bc))
857
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200858 def test_hardlink_bad_args(self):
859 # Bad arguments combination, hardlink deduplication make sense
860 # only for more than one optimization level
861 self.assertRunNotOK(self.directory, "-o 1", "--hardlink-dupes")
862
863 def test_hardlink(self):
864 # 'a = 0' code produces the same bytecode for the 3 optimization
865 # levels. All three .pyc files must have the same inode (hardlinks).
866 #
867 # If deduplication is disabled, all pyc files must have different
868 # inodes.
869 for dedup in (True, False):
870 with tempfile.TemporaryDirectory() as path:
871 with self.subTest(dedup=dedup):
872 script = script_helper.make_script(path, "script", "a = 0")
873 pycs = get_pycs(script)
874
875 args = ["-q", "-o 0", "-o 1", "-o 2"]
876 if dedup:
877 args.append("--hardlink-dupes")
878 self.assertRunOK(path, *args)
879
880 self.assertEqual(is_hardlink(pycs[0], pycs[1]), dedup)
881 self.assertEqual(is_hardlink(pycs[1], pycs[2]), dedup)
882 self.assertEqual(is_hardlink(pycs[0], pycs[2]), dedup)
883
Barry Warsaw28a691b2010-04-17 00:19:56 +0000884
Min ho Kimc4cacc82019-07-31 08:16:13 +1000885class CommandLineTestsWithSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400886 unittest.TestCase,
887 metaclass=SourceDateEpochTestMeta,
888 source_date_epoch=True):
889 pass
890
891
Min ho Kimc4cacc82019-07-31 08:16:13 +1000892class CommandLineTestsNoSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400893 unittest.TestCase,
894 metaclass=SourceDateEpochTestMeta,
895 source_date_epoch=False):
896 pass
897
898
899
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200900class HardlinkDedupTestsBase:
901 # Test hardlink_dupes parameter of compileall.compile_dir()
902
903 def setUp(self):
904 self.path = None
905
906 @contextlib.contextmanager
907 def temporary_directory(self):
908 with tempfile.TemporaryDirectory() as path:
909 self.path = path
910 yield path
911 self.path = None
912
913 def make_script(self, code, name="script"):
914 return script_helper.make_script(self.path, name, code)
915
916 def compile_dir(self, *, dedup=True, optimize=(0, 1, 2), force=False):
917 compileall.compile_dir(self.path, quiet=True, optimize=optimize,
918 hardlink_dupes=dedup, force=force)
919
920 def test_bad_args(self):
921 # Bad arguments combination, hardlink deduplication make sense
922 # only for more than one optimization level
923 with self.temporary_directory():
924 self.make_script("pass")
925 with self.assertRaises(ValueError):
926 compileall.compile_dir(self.path, quiet=True, optimize=0,
927 hardlink_dupes=True)
928 with self.assertRaises(ValueError):
929 # same optimization level specified twice:
930 # compile_dir() removes duplicates
931 compileall.compile_dir(self.path, quiet=True, optimize=[0, 0],
932 hardlink_dupes=True)
933
934 def create_code(self, docstring=False, assertion=False):
935 lines = []
936 if docstring:
937 lines.append("'module docstring'")
938 lines.append('x = 1')
939 if assertion:
940 lines.append("assert x == 1")
941 return '\n'.join(lines)
942
943 def iter_codes(self):
944 for docstring in (False, True):
945 for assertion in (False, True):
946 code = self.create_code(docstring=docstring, assertion=assertion)
947 yield (code, docstring, assertion)
948
949 def test_disabled(self):
950 # Deduplication disabled, no hardlinks
951 for code, docstring, assertion in self.iter_codes():
952 with self.subTest(docstring=docstring, assertion=assertion):
953 with self.temporary_directory():
954 script = self.make_script(code)
955 pycs = get_pycs(script)
956 self.compile_dir(dedup=False)
957 self.assertFalse(is_hardlink(pycs[0], pycs[1]))
958 self.assertFalse(is_hardlink(pycs[0], pycs[2]))
959 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
960
961 def check_hardlinks(self, script, docstring=False, assertion=False):
962 pycs = get_pycs(script)
963 self.assertEqual(is_hardlink(pycs[0], pycs[1]),
964 not assertion)
965 self.assertEqual(is_hardlink(pycs[0], pycs[2]),
966 not assertion and not docstring)
967 self.assertEqual(is_hardlink(pycs[1], pycs[2]),
968 not docstring)
969
970 def test_hardlink(self):
971 # Test deduplication on all combinations
972 for code, docstring, assertion in self.iter_codes():
973 with self.subTest(docstring=docstring, assertion=assertion):
974 with self.temporary_directory():
975 script = self.make_script(code)
976 self.compile_dir()
977 self.check_hardlinks(script, docstring, assertion)
978
979 def test_only_two_levels(self):
980 # Don't build the 3 optimization levels, but only 2
981 for opts in ((0, 1), (1, 2), (0, 2)):
982 with self.subTest(opts=opts):
983 with self.temporary_directory():
984 # code with no dostring and no assertion:
985 # same bytecode for all optimization levels
986 script = self.make_script(self.create_code())
987 self.compile_dir(optimize=opts)
988 pyc1 = get_pyc(script, opts[0])
989 pyc2 = get_pyc(script, opts[1])
990 self.assertTrue(is_hardlink(pyc1, pyc2))
991
992 def test_duplicated_levels(self):
993 # compile_dir() must not fail if optimize contains duplicated
994 # optimization levels and/or if optimization levels are not sorted.
995 with self.temporary_directory():
996 # code with no dostring and no assertion:
997 # same bytecode for all optimization levels
998 script = self.make_script(self.create_code())
999 self.compile_dir(optimize=[1, 0, 1, 0])
1000 pyc1 = get_pyc(script, 0)
1001 pyc2 = get_pyc(script, 1)
1002 self.assertTrue(is_hardlink(pyc1, pyc2))
1003
1004 def test_recompilation(self):
1005 # Test compile_dir() when pyc files already exists and the script
1006 # content changed
1007 with self.temporary_directory():
1008 script = self.make_script("a = 0")
1009 self.compile_dir()
1010 # All three levels have the same inode
1011 self.check_hardlinks(script)
1012
1013 pycs = get_pycs(script)
1014 inode = os.stat(pycs[0]).st_ino
1015
1016 # Change of the module content
1017 script = self.make_script("print(0)")
1018
1019 # Recompilation without -o 1
1020 self.compile_dir(optimize=[0, 2], force=True)
1021
1022 # opt-1.pyc should have the same inode as before and others should not
1023 self.assertEqual(inode, os.stat(pycs[1]).st_ino)
1024 self.assertTrue(is_hardlink(pycs[0], pycs[2]))
1025 self.assertNotEqual(inode, os.stat(pycs[2]).st_ino)
1026 # opt-1.pyc and opt-2.pyc have different content
1027 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1028
1029 def test_import(self):
1030 # Test that import updates a single pyc file when pyc files already
1031 # exists and the script content changed
1032 with self.temporary_directory():
1033 script = self.make_script(self.create_code(), name="module")
1034 self.compile_dir()
1035 # All three levels have the same inode
1036 self.check_hardlinks(script)
1037
1038 pycs = get_pycs(script)
1039 inode = os.stat(pycs[0]).st_ino
1040
1041 # Change of the module content
1042 script = self.make_script("print(0)", name="module")
1043
1044 # Import the module in Python with -O (optimization level 1)
1045 script_helper.assert_python_ok(
1046 "-O", "-c", "import module", __isolated=False, PYTHONPATH=self.path
1047 )
1048
1049 # Only opt-1.pyc is changed
1050 self.assertEqual(inode, os.stat(pycs[0]).st_ino)
1051 self.assertEqual(inode, os.stat(pycs[2]).st_ino)
1052 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
1053 # opt-1.pyc and opt-2.pyc have different content
1054 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1055
1056
1057class HardlinkDedupTestsWithSourceEpoch(HardlinkDedupTestsBase,
1058 unittest.TestCase,
1059 metaclass=SourceDateEpochTestMeta,
1060 source_date_epoch=True):
1061 pass
1062
1063
1064class HardlinkDedupTestsNoSourceEpoch(HardlinkDedupTestsBase,
1065 unittest.TestCase,
1066 metaclass=SourceDateEpochTestMeta,
1067 source_date_epoch=False):
1068 pass
1069
1070
Brett Cannonbefb14f2009-02-10 02:10:16 +00001071if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -04001072 unittest.main()