blob: b4061b79357b87ad1b8fdfa80eb87822e241e2f7 [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
19try:
20 from concurrent.futures import ProcessPoolExecutor
21 _have_multiprocessing = True
22except ImportError:
23 _have_multiprocessing = False
24
Berker Peksagce643912015-05-06 06:33:17 +030025from test import support
26from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000027
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040028from .test_py_compile import without_source_date_epoch
29from .test_py_compile import SourceDateEpochTestMeta
30
31
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020032def get_pyc(script, opt):
33 if not opt:
34 # Replace None and 0 with ''
35 opt = ''
36 return importlib.util.cache_from_source(script, optimization=opt)
37
38
39def get_pycs(script):
40 return [get_pyc(script, opt) for opt in (0, 1, 2)]
41
42
43def is_hardlink(filename1, filename2):
44 """Returns True if two files have the same inode (hardlink)"""
45 inode1 = os.stat(filename1).st_ino
46 inode2 = os.stat(filename2).st_ino
47 return inode1 == inode2
48
49
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040050class CompileallTestsBase:
Brett Cannonbefb14f2009-02-10 02:10:16 +000051
52 def setUp(self):
53 self.directory = tempfile.mkdtemp()
54 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040055 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000056 with open(self.source_path, 'w') as file:
57 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000058 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040059 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000060 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000061 self.subdirectory = os.path.join(self.directory, '_subdir')
62 os.mkdir(self.subdirectory)
63 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
64 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000065
66 def tearDown(self):
67 shutil.rmtree(self.directory)
68
Brett Cannon1e3c3e92015-12-27 13:17:04 -080069 def add_bad_source_file(self):
70 self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
71 with open(self.bad_source_path, 'w') as file:
72 file.write('x (\n')
73
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040074 def timestamp_metadata(self):
Brett Cannonbefb14f2009-02-10 02:10:16 +000075 with open(self.bc_path, 'rb') as file:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080076 data = file.read(12)
Brett Cannonbefb14f2009-02-10 02:10:16 +000077 mtime = int(os.stat(self.source_path).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080078 compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000079 return data, compare
80
81 def recreation_check(self, metadata):
82 """Check that compileall recreates bytecode when the new metadata is
83 used."""
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040084 if os.environ.get('SOURCE_DATE_EPOCH'):
85 raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
Brett Cannonbefb14f2009-02-10 02:10:16 +000086 py_compile.compile(self.source_path)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040087 self.assertEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000088 with open(self.bc_path, 'rb') as file:
89 bc = file.read()[len(metadata):]
90 with open(self.bc_path, 'wb') as file:
91 file.write(metadata)
92 file.write(bc)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040093 self.assertNotEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000094 compileall.compile_dir(self.directory, force=False, quiet=True)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040095 self.assertTrue(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000096
97 def test_mtime(self):
98 # Test a change in mtime leads to a new .pyc.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080099 self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
100 0, 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000101
102 def test_magic_number(self):
103 # Test a change in mtime leads to a new .pyc.
104 self.recreation_check(b'\0\0\0\0')
105
Matthias Klosec33b9022010-03-16 00:36:26 +0000106 def test_compile_files(self):
107 # Test compiling a single file, and complete directory
108 for fn in (self.bc_path, self.bc_path2):
109 try:
110 os.unlink(fn)
111 except:
112 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800113 self.assertTrue(compileall.compile_file(self.source_path,
114 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000115 self.assertTrue(os.path.isfile(self.bc_path) and
116 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000117 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800118 self.assertTrue(compileall.compile_dir(self.directory, force=False,
119 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000120 self.assertTrue(os.path.isfile(self.bc_path) and
121 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000122 os.unlink(self.bc_path)
123 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800124 # Test against bad files
125 self.add_bad_source_file()
126 self.assertFalse(compileall.compile_file(self.bad_source_path,
127 force=False, quiet=2))
128 self.assertFalse(compileall.compile_dir(self.directory,
129 force=False, quiet=2))
130
Berker Peksag812a2b62016-10-01 00:54:18 +0300131 def test_compile_file_pathlike(self):
132 self.assertFalse(os.path.isfile(self.bc_path))
133 # we should also test the output
134 with support.captured_stdout() as stdout:
135 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300136 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300137 self.assertTrue(os.path.isfile(self.bc_path))
138
139 def test_compile_file_pathlike_ddir(self):
140 self.assertFalse(os.path.isfile(self.bc_path))
141 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
142 ddir=pathlib.Path('ddir_path'),
143 quiet=2))
144 self.assertTrue(os.path.isfile(self.bc_path))
145
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800146 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300147 with test.test_importlib.util.import_state(path=[self.directory]):
148 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800149
150 with test.test_importlib.util.import_state(path=[self.directory]):
151 self.add_bad_source_file()
152 self.assertFalse(compileall.compile_path(skip_curdir=False,
153 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000154
Barry Warsawc8a99de2010-04-29 18:43:10 +0000155 def test_no_pycache_in_non_package(self):
156 # Bug 8563 reported that __pycache__ directories got created by
157 # compile_file() for non-.py files.
158 data_dir = os.path.join(self.directory, 'data')
159 data_file = os.path.join(data_dir, 'file')
160 os.mkdir(data_dir)
161 # touch data/file
162 with open(data_file, 'w'):
163 pass
164 compileall.compile_file(data_file)
165 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
166
Georg Brandl8334fd92010-12-04 10:26:46 +0000167 def test_optimize(self):
168 # make sure compiling with different optimization settings than the
169 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400170 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000171 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400172 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400173 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000174 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400175 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400176 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000177 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400178 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400179 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000180 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000181
Berker Peksag812a2b62016-10-01 00:54:18 +0300182 def test_compile_dir_pathlike(self):
183 self.assertFalse(os.path.isfile(self.bc_path))
184 with support.captured_stdout() as stdout:
185 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300186 line = stdout.getvalue().splitlines()[0]
187 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300188 self.assertTrue(os.path.isfile(self.bc_path))
189
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500190 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400191 def test_compile_pool_called(self, pool_mock):
192 compileall.compile_dir(self.directory, quiet=True, workers=5)
193 self.assertTrue(pool_mock.called)
194
195 def test_compile_workers_non_positive(self):
196 with self.assertRaisesRegex(ValueError,
197 "workers must be greater or equal to 0"):
198 compileall.compile_dir(self.directory, workers=-1)
199
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500200 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400201 def test_compile_workers_cpu_count(self, pool_mock):
202 compileall.compile_dir(self.directory, quiet=True, workers=0)
203 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
204
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500205 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400206 @mock.patch('compileall.compile_file')
207 def test_compile_one_worker(self, compile_file_mock, pool_mock):
208 compileall.compile_dir(self.directory, quiet=True)
209 self.assertFalse(pool_mock.called)
210 self.assertTrue(compile_file_mock.called)
211
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500212 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300213 @mock.patch('compileall.compile_file')
214 def test_compile_missing_multiprocessing(self, compile_file_mock):
215 compileall.compile_dir(self.directory, quiet=True, workers=5)
216 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000217
Petr Viktorin4267c982019-09-26 11:53:51 +0200218 def test_compile_dir_maxlevels(self):
Victor Stinnereb1dda22019-10-15 11:26:13 +0200219 # Test the actual impact of maxlevels parameter
220 depth = 3
221 path = self.directory
222 for i in range(1, depth + 1):
223 path = os.path.join(path, f"dir_{i}")
224 source = os.path.join(path, 'script.py')
225 os.mkdir(path)
226 shutil.copyfile(self.source_path, source)
227 pyc_filename = importlib.util.cache_from_source(source)
228
229 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth - 1)
230 self.assertFalse(os.path.isfile(pyc_filename))
231
232 compileall.compile_dir(self.directory, quiet=True, maxlevels=depth)
233 self.assertTrue(os.path.isfile(pyc_filename))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200234
Gregory P. Smith02673352020-02-28 17:28:37 -0800235 def _test_ddir_only(self, *, ddir, parallel=True):
236 """Recursive compile_dir ddir must contain package paths; bpo39769."""
237 fullpath = ["test", "foo"]
238 path = self.directory
239 mods = []
240 for subdir in fullpath:
241 path = os.path.join(path, subdir)
242 os.mkdir(path)
243 script_helper.make_script(path, "__init__", "")
244 mods.append(script_helper.make_script(path, "mod",
245 "def fn(): 1/0\nfn()\n"))
246 compileall.compile_dir(
247 self.directory, quiet=True, ddir=ddir,
248 workers=2 if parallel else 1)
249 self.assertTrue(mods)
250 for mod in mods:
251 self.assertTrue(mod.startswith(self.directory), mod)
252 modcode = importlib.util.cache_from_source(mod)
253 modpath = mod[len(self.directory+os.sep):]
254 _, _, err = script_helper.assert_python_failure(modcode)
255 expected_in = os.path.join(ddir, modpath)
256 mod_code_obj = test.test_importlib.util.get_code_from_pyc(modcode)
257 self.assertEqual(mod_code_obj.co_filename, expected_in)
258 self.assertIn(f'"{expected_in}"', os.fsdecode(err))
259
260 def test_ddir_only_one_worker(self):
261 """Recursive compile_dir ddir= contains package paths; bpo39769."""
262 return self._test_ddir_only(ddir="<a prefix>", parallel=False)
263
264 def test_ddir_multiple_workers(self):
265 """Recursive compile_dir ddir= contains package paths; bpo39769."""
266 return self._test_ddir_only(ddir="<a prefix>", parallel=True)
267
268 def test_ddir_empty_only_one_worker(self):
269 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
270 return self._test_ddir_only(ddir="", parallel=False)
271
272 def test_ddir_empty_multiple_workers(self):
273 """Recursive compile_dir ddir='' contains package paths; bpo39769."""
274 return self._test_ddir_only(ddir="", parallel=True)
275
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200276 def test_strip_only(self):
277 fullpath = ["test", "build", "real", "path"]
278 path = os.path.join(self.directory, *fullpath)
279 os.makedirs(path)
280 script = script_helper.make_script(path, "test", "1 / 0")
281 bc = importlib.util.cache_from_source(script)
282 stripdir = os.path.join(self.directory, *fullpath[:2])
283 compileall.compile_dir(path, quiet=True, stripdir=stripdir)
284 rc, out, err = script_helper.assert_python_failure(bc)
285 expected_in = os.path.join(*fullpath[2:])
286 self.assertIn(
287 expected_in,
288 str(err, encoding=sys.getdefaultencoding())
289 )
290 self.assertNotIn(
291 stripdir,
292 str(err, encoding=sys.getdefaultencoding())
293 )
294
295 def test_prepend_only(self):
296 fullpath = ["test", "build", "real", "path"]
297 path = os.path.join(self.directory, *fullpath)
298 os.makedirs(path)
299 script = script_helper.make_script(path, "test", "1 / 0")
300 bc = importlib.util.cache_from_source(script)
301 prependdir = "/foo"
302 compileall.compile_dir(path, quiet=True, prependdir=prependdir)
303 rc, out, err = script_helper.assert_python_failure(bc)
304 expected_in = os.path.join(prependdir, self.directory, *fullpath)
305 self.assertIn(
306 expected_in,
307 str(err, encoding=sys.getdefaultencoding())
308 )
309
310 def test_strip_and_prepend(self):
311 fullpath = ["test", "build", "real", "path"]
312 path = os.path.join(self.directory, *fullpath)
313 os.makedirs(path)
314 script = script_helper.make_script(path, "test", "1 / 0")
315 bc = importlib.util.cache_from_source(script)
316 stripdir = os.path.join(self.directory, *fullpath[:2])
317 prependdir = "/foo"
318 compileall.compile_dir(path, quiet=True,
319 stripdir=stripdir, prependdir=prependdir)
320 rc, out, err = script_helper.assert_python_failure(bc)
321 expected_in = os.path.join(prependdir, *fullpath[2:])
322 self.assertIn(
323 expected_in,
324 str(err, encoding=sys.getdefaultencoding())
325 )
326 self.assertNotIn(
327 stripdir,
328 str(err, encoding=sys.getdefaultencoding())
329 )
330
331 def test_strip_prepend_and_ddir(self):
332 fullpath = ["test", "build", "real", "path", "ddir"]
333 path = os.path.join(self.directory, *fullpath)
334 os.makedirs(path)
335 script_helper.make_script(path, "test", "1 / 0")
336 with self.assertRaises(ValueError):
337 compileall.compile_dir(path, quiet=True, ddir="/bar",
338 stripdir="/foo", prependdir="/bar")
339
340 def test_multiple_optimization_levels(self):
341 script = script_helper.make_script(self.directory,
342 "test_optimization",
343 "a = 0")
344 bc = []
345 for opt_level in "", 1, 2, 3:
346 bc.append(importlib.util.cache_from_source(script,
347 optimization=opt_level))
348 test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]]
349 for opt_combination in test_combinations:
350 compileall.compile_file(script, quiet=True,
351 optimize=opt_combination)
352 for opt_level in opt_combination:
353 self.assertTrue(os.path.isfile(bc[opt_level]))
354 try:
355 os.unlink(bc[opt_level])
356 except Exception:
357 pass
358
359 @support.skip_unless_symlink
360 def test_ignore_symlink_destination(self):
361 # Create folders for allowed files, symlinks and prohibited area
362 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
363 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
364 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
365 os.makedirs(allowed_path)
366 os.makedirs(symlinks_path)
367 os.makedirs(prohibited_path)
368
369 # Create scripts and symlinks and remember their byte-compiled versions
370 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
371 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
372 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
373 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
374 os.symlink(allowed_script, allowed_symlink)
375 os.symlink(prohibited_script, prohibited_symlink)
376 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
377 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
378
379 compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path)
380
381 self.assertTrue(os.path.isfile(allowed_bc))
382 self.assertFalse(os.path.isfile(prohibited_bc))
383
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400384
385class CompileallTestsWithSourceEpoch(CompileallTestsBase,
386 unittest.TestCase,
387 metaclass=SourceDateEpochTestMeta,
388 source_date_epoch=True):
389 pass
390
391
392class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
393 unittest.TestCase,
394 metaclass=SourceDateEpochTestMeta,
395 source_date_epoch=False):
396 pass
397
398
Martin v. Löwis4b003072010-03-16 13:19:21 +0000399class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000400 """Issue 6716: compileall should escape source code when printing errors
401 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000402
403 def setUp(self):
404 self.directory = tempfile.mkdtemp()
405 self.source_path = os.path.join(self.directory, '_test.py')
406 with open(self.source_path, 'w', encoding='utf-8') as file:
407 file.write('# -*- coding: utf-8 -*-\n')
408 file.write('print u"\u20ac"\n')
409
410 def tearDown(self):
411 shutil.rmtree(self.directory)
412
413 def test_error(self):
414 try:
415 orig_stdout = sys.stdout
416 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
417 compileall.compile_dir(self.directory)
418 finally:
419 sys.stdout = orig_stdout
420
Barry Warsawc8a99de2010-04-29 18:43:10 +0000421
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400422class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000423 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000424
Brett Cannon65ed7502015-10-09 15:09:43 -0700425 @classmethod
426 def setUpClass(cls):
427 for path in filter(os.path.isdir, sys.path):
428 directory_created = False
429 directory = pathlib.Path(path) / '__pycache__'
430 path = directory / 'test.try'
431 try:
432 if not directory.is_dir():
433 directory.mkdir()
434 directory_created = True
435 with path.open('w') as file:
436 file.write('# for test_compileall')
437 except OSError:
438 sys_path_writable = False
439 break
440 finally:
441 support.unlink(str(path))
442 if directory_created:
443 directory.rmdir()
444 else:
445 sys_path_writable = True
446 cls._sys_path_writable = sys_path_writable
447
448 def _skip_if_sys_path_not_writable(self):
449 if not self._sys_path_writable:
450 raise unittest.SkipTest('not all entries on sys.path are writable')
451
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400452 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100453 return [*support.optim_args_from_interpreter_flags(),
454 '-S', '-m', 'compileall',
455 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400456
R. David Murray5317e9c2010-12-16 19:08:51 +0000457 def assertRunOK(self, *args, **env_vars):
458 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400459 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000460 self.assertEqual(b'', err)
461 return out
462
R. David Murray5317e9c2010-12-16 19:08:51 +0000463 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000464 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400465 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000466 return rc, out, err
467
468 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400469 path = importlib.util.cache_from_source(fn)
470 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000471
472 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400473 path = importlib.util.cache_from_source(fn)
474 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000475
Barry Warsaw28a691b2010-04-17 00:19:56 +0000476 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000477 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700478 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000479 self.pkgdir = os.path.join(self.directory, 'foo')
480 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000481 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
482 # Create the __init__.py and a package module.
483 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
484 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000485
R. David Murray5317e9c2010-12-16 19:08:51 +0000486 def test_no_args_compiles_path(self):
487 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700488 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000489 bazfn = script_helper.make_script(self.directory, 'baz', '')
490 self.assertRunOK(PYTHONPATH=self.directory)
491 self.assertCompiled(bazfn)
492 self.assertNotCompiled(self.initfn)
493 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000494
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400495 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500496 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700497 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500498 bazfn = script_helper.make_script(self.directory, 'baz', '')
499 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500500 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500501 # Set atime/mtime backward to avoid file timestamp resolution issues
502 os.utime(pycpath, (time.time()-60,)*2)
503 mtime = os.stat(pycpath).st_mtime
504 # Without force, no recompilation
505 self.assertRunOK(PYTHONPATH=self.directory)
506 mtime2 = os.stat(pycpath).st_mtime
507 self.assertEqual(mtime, mtime2)
508 # Now force it.
509 self.assertRunOK('-f', PYTHONPATH=self.directory)
510 mtime2 = os.stat(pycpath).st_mtime
511 self.assertNotEqual(mtime, mtime2)
512
513 def test_no_args_respects_quiet_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 script_helper.make_script(self.directory, 'baz', '')
516 noisy = self.assertRunOK(PYTHONPATH=self.directory)
517 self.assertIn(b'Listing ', noisy)
518 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
519 self.assertNotIn(b'Listing ', quiet)
520
Georg Brandl1463a3f2010-10-14 07:42:27 +0000521 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400522 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000523 for name, ext, switch in [
524 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400525 ('optimize', 'opt-1.pyc', ['-O']),
526 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000527 ]:
528 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000529 script_helper.assert_python_ok(*(switch +
530 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000531 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000532 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400533 expected = sorted(base.format(sys.implementation.cache_tag, ext)
534 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000535 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000536 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000537 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
538 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000539 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000540
541 def test_legacy_paths(self):
542 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400543 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000544 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000545 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000546 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400547 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
548 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
550
Barry Warsawc04317f2010-04-26 15:59:03 +0000551 def test_multiple_runs(self):
552 # Bug 8527 reported that multiple calls produced empty
553 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000554 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000555 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000556 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
557 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000558 self.assertFalse(os.path.exists(cachecachedir))
559 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000560 self.assertRunOK('-q', self.pkgdir)
561 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000562 self.assertFalse(os.path.exists(cachecachedir))
563
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400564 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000565 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000566 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400567 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000568 # set atime/mtime backward to avoid file timestamp resolution issues
569 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000570 mtime = os.stat(pycpath).st_mtime
571 # without force, no recompilation
572 self.assertRunOK('-q', self.pkgdir)
573 mtime2 = os.stat(pycpath).st_mtime
574 self.assertEqual(mtime, mtime2)
575 # now force it.
576 self.assertRunOK('-q', '-f', self.pkgdir)
577 mtime2 = os.stat(pycpath).st_mtime
578 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000579
R. David Murray95333e32010-12-14 22:32:50 +0000580 def test_recursion_control(self):
581 subpackage = os.path.join(self.pkgdir, 'spam')
582 os.mkdir(subpackage)
583 subinitfn = script_helper.make_script(subpackage, '__init__', '')
584 hamfn = script_helper.make_script(subpackage, 'ham', '')
585 self.assertRunOK('-q', '-l', self.pkgdir)
586 self.assertNotCompiled(subinitfn)
587 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
588 self.assertRunOK('-q', self.pkgdir)
589 self.assertCompiled(subinitfn)
590 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000591
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500592 def test_recursion_limit(self):
593 subpackage = os.path.join(self.pkgdir, 'spam')
594 subpackage2 = os.path.join(subpackage, 'ham')
595 subpackage3 = os.path.join(subpackage2, 'eggs')
596 for pkg in (subpackage, subpackage2, subpackage3):
597 script_helper.make_pkg(pkg)
598
599 subinitfn = os.path.join(subpackage, '__init__.py')
600 hamfn = script_helper.make_script(subpackage, 'ham', '')
601 spamfn = script_helper.make_script(subpackage2, 'spam', '')
602 eggfn = script_helper.make_script(subpackage3, 'egg', '')
603
604 self.assertRunOK('-q', '-r 0', self.pkgdir)
605 self.assertNotCompiled(subinitfn)
606 self.assertFalse(
607 os.path.exists(os.path.join(subpackage, '__pycache__')))
608
609 self.assertRunOK('-q', '-r 1', self.pkgdir)
610 self.assertCompiled(subinitfn)
611 self.assertCompiled(hamfn)
612 self.assertNotCompiled(spamfn)
613
614 self.assertRunOK('-q', '-r 2', self.pkgdir)
615 self.assertCompiled(subinitfn)
616 self.assertCompiled(hamfn)
617 self.assertCompiled(spamfn)
618 self.assertNotCompiled(eggfn)
619
620 self.assertRunOK('-q', '-r 5', self.pkgdir)
621 self.assertCompiled(subinitfn)
622 self.assertCompiled(hamfn)
623 self.assertCompiled(spamfn)
624 self.assertCompiled(eggfn)
625
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200626 @support.skip_unless_symlink
627 def test_symlink_loop(self):
628 # Currently, compileall ignores symlinks to directories.
629 # If that limitation is ever lifted, it should protect against
630 # recursion in symlink loops.
631 pkg = os.path.join(self.pkgdir, 'spam')
632 script_helper.make_pkg(pkg)
633 os.symlink('.', os.path.join(pkg, 'evil'))
634 os.symlink('.', os.path.join(pkg, 'evil2'))
635 self.assertRunOK('-q', self.pkgdir)
636 self.assertCompiled(os.path.join(
637 self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py'
638 ))
639
R. David Murray650f1472010-11-20 21:18:51 +0000640 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000641 noisy = self.assertRunOK(self.pkgdir)
642 quiet = self.assertRunOK('-q', self.pkgdir)
643 self.assertNotEqual(b'', noisy)
644 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000645
Berker Peksag6554b862014-10-15 11:10:57 +0300646 def test_silent(self):
647 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
648 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
649 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
650 self.assertNotEqual(b'', quiet)
651 self.assertEqual(b'', silent)
652
R. David Murray650f1472010-11-20 21:18:51 +0000653 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400654 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000655 self.assertNotCompiled(self.barfn)
656 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000657
R. David Murray95333e32010-12-14 22:32:50 +0000658 def test_multiple_dirs(self):
659 pkgdir2 = os.path.join(self.directory, 'foo2')
660 os.mkdir(pkgdir2)
661 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
662 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
663 self.assertRunOK('-q', self.pkgdir, pkgdir2)
664 self.assertCompiled(self.initfn)
665 self.assertCompiled(self.barfn)
666 self.assertCompiled(init2fn)
667 self.assertCompiled(bar2fn)
668
R. David Murray95333e32010-12-14 22:32:50 +0000669 def test_d_compile_error(self):
670 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
671 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
672 self.assertRegex(out, b'File "dinsdale')
673
674 def test_d_runtime_error(self):
675 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
676 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
677 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400678 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000679 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
680 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200681 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000682 self.assertRegex(err, b'File "dinsdale')
683
684 def test_include_bad_file(self):
685 rc, out, err = self.assertRunNotOK(
686 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
687 self.assertRegex(out, b'rror.*nosuchfile')
688 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400689 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000690 self.pkgdir_cachedir)))
691
692 def test_include_file_with_arg(self):
693 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
694 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
695 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
696 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
697 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
698 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
699 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
700 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
701 self.assertCompiled(f1)
702 self.assertCompiled(f2)
703 self.assertNotCompiled(f3)
704 self.assertCompiled(f4)
705
706 def test_include_file_no_arg(self):
707 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
708 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
709 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
710 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
711 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
712 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
713 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
714 self.assertNotCompiled(f1)
715 self.assertCompiled(f2)
716 self.assertNotCompiled(f3)
717 self.assertNotCompiled(f4)
718
719 def test_include_on_stdin(self):
720 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
721 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
722 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
723 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400724 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000725 p.stdin.write((f3+os.linesep).encode('ascii'))
726 script_helper.kill_python(p)
727 self.assertNotCompiled(f1)
728 self.assertNotCompiled(f2)
729 self.assertCompiled(f3)
730 self.assertNotCompiled(f4)
731
732 def test_compiles_as_much_as_possible(self):
733 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
734 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
735 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000736 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000737 self.assertNotCompiled(bingfn)
738 self.assertCompiled(self.initfn)
739 self.assertCompiled(self.barfn)
740
R. David Murray5317e9c2010-12-16 19:08:51 +0000741 def test_invalid_arg_produces_message(self):
742 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200743 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000744
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800745 def test_pyc_invalidation_mode(self):
746 script_helper.make_script(self.pkgdir, 'f1', '')
747 pyc = importlib.util.cache_from_source(
748 os.path.join(self.pkgdir, 'f1.py'))
749 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
750 with open(pyc, 'rb') as fp:
751 data = fp.read()
752 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
753 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
754 with open(pyc, 'rb') as fp:
755 data = fp.read()
756 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
757
Brett Cannonf1a8df02014-09-12 10:39:48 -0400758 @skipUnless(_have_multiprocessing, "requires multiprocessing")
759 def test_workers(self):
760 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
761 files = []
762 for suffix in range(5):
763 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
764 os.mkdir(pkgdir)
765 fn = script_helper.make_script(pkgdir, '__init__', '')
766 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
767
768 self.assertRunOK(self.directory, '-j', '0')
769 self.assertCompiled(bar2fn)
770 for file in files:
771 self.assertCompiled(file)
772
773 @mock.patch('compileall.compile_dir')
774 def test_workers_available_cores(self, compile_dir):
775 with mock.patch("sys.argv",
776 new=[sys.executable, self.directory, "-j0"]):
777 compileall.main()
778 self.assertTrue(compile_dir.called)
Antoine Pitrou1a2dd822019-05-15 23:45:18 +0200779 self.assertEqual(compile_dir.call_args[-1]['workers'], 0)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400780
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200781 def test_strip_and_prepend(self):
782 fullpath = ["test", "build", "real", "path"]
783 path = os.path.join(self.directory, *fullpath)
784 os.makedirs(path)
785 script = script_helper.make_script(path, "test", "1 / 0")
786 bc = importlib.util.cache_from_source(script)
787 stripdir = os.path.join(self.directory, *fullpath[:2])
788 prependdir = "/foo"
789 self.assertRunOK("-s", stripdir, "-p", prependdir, path)
790 rc, out, err = script_helper.assert_python_failure(bc)
791 expected_in = os.path.join(prependdir, *fullpath[2:])
792 self.assertIn(
793 expected_in,
794 str(err, encoding=sys.getdefaultencoding())
795 )
796 self.assertNotIn(
797 stripdir,
798 str(err, encoding=sys.getdefaultencoding())
799 )
800
801 def test_multiple_optimization_levels(self):
802 path = os.path.join(self.directory, "optimizations")
803 os.makedirs(path)
804 script = script_helper.make_script(path,
805 "test_optimization",
806 "a = 0")
807 bc = []
808 for opt_level in "", 1, 2, 3:
809 bc.append(importlib.util.cache_from_source(script,
810 optimization=opt_level))
811 test_combinations = [["0", "1"],
812 ["1", "2"],
813 ["0", "2"],
814 ["0", "1", "2"]]
815 for opt_combination in test_combinations:
816 self.assertRunOK(path, *("-o" + str(n) for n in opt_combination))
817 for opt_level in opt_combination:
818 self.assertTrue(os.path.isfile(bc[int(opt_level)]))
819 try:
820 os.unlink(bc[opt_level])
821 except Exception:
822 pass
823
824 @support.skip_unless_symlink
825 def test_ignore_symlink_destination(self):
826 # Create folders for allowed files, symlinks and prohibited area
827 allowed_path = os.path.join(self.directory, "test", "dir", "allowed")
828 symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks")
829 prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited")
830 os.makedirs(allowed_path)
831 os.makedirs(symlinks_path)
832 os.makedirs(prohibited_path)
833
834 # Create scripts and symlinks and remember their byte-compiled versions
835 allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0")
836 prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0")
837 allowed_symlink = os.path.join(symlinks_path, "test_allowed.py")
838 prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py")
839 os.symlink(allowed_script, allowed_symlink)
840 os.symlink(prohibited_script, prohibited_symlink)
841 allowed_bc = importlib.util.cache_from_source(allowed_symlink)
842 prohibited_bc = importlib.util.cache_from_source(prohibited_symlink)
843
844 self.assertRunOK(symlinks_path, "-e", allowed_path)
845
846 self.assertTrue(os.path.isfile(allowed_bc))
847 self.assertFalse(os.path.isfile(prohibited_bc))
848
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200849 def test_hardlink_bad_args(self):
850 # Bad arguments combination, hardlink deduplication make sense
851 # only for more than one optimization level
852 self.assertRunNotOK(self.directory, "-o 1", "--hardlink-dupes")
853
854 def test_hardlink(self):
855 # 'a = 0' code produces the same bytecode for the 3 optimization
856 # levels. All three .pyc files must have the same inode (hardlinks).
857 #
858 # If deduplication is disabled, all pyc files must have different
859 # inodes.
860 for dedup in (True, False):
861 with tempfile.TemporaryDirectory() as path:
862 with self.subTest(dedup=dedup):
863 script = script_helper.make_script(path, "script", "a = 0")
864 pycs = get_pycs(script)
865
866 args = ["-q", "-o 0", "-o 1", "-o 2"]
867 if dedup:
868 args.append("--hardlink-dupes")
869 self.assertRunOK(path, *args)
870
871 self.assertEqual(is_hardlink(pycs[0], pycs[1]), dedup)
872 self.assertEqual(is_hardlink(pycs[1], pycs[2]), dedup)
873 self.assertEqual(is_hardlink(pycs[0], pycs[2]), dedup)
874
Barry Warsaw28a691b2010-04-17 00:19:56 +0000875
Min ho Kimc4cacc82019-07-31 08:16:13 +1000876class CommandLineTestsWithSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400877 unittest.TestCase,
878 metaclass=SourceDateEpochTestMeta,
879 source_date_epoch=True):
880 pass
881
882
Min ho Kimc4cacc82019-07-31 08:16:13 +1000883class CommandLineTestsNoSourceEpoch(CommandLineTestsBase,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400884 unittest.TestCase,
885 metaclass=SourceDateEpochTestMeta,
886 source_date_epoch=False):
887 pass
888
889
890
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200891class HardlinkDedupTestsBase:
892 # Test hardlink_dupes parameter of compileall.compile_dir()
893
894 def setUp(self):
895 self.path = None
896
897 @contextlib.contextmanager
898 def temporary_directory(self):
899 with tempfile.TemporaryDirectory() as path:
900 self.path = path
901 yield path
902 self.path = None
903
904 def make_script(self, code, name="script"):
905 return script_helper.make_script(self.path, name, code)
906
907 def compile_dir(self, *, dedup=True, optimize=(0, 1, 2), force=False):
908 compileall.compile_dir(self.path, quiet=True, optimize=optimize,
909 hardlink_dupes=dedup, force=force)
910
911 def test_bad_args(self):
912 # Bad arguments combination, hardlink deduplication make sense
913 # only for more than one optimization level
914 with self.temporary_directory():
915 self.make_script("pass")
916 with self.assertRaises(ValueError):
917 compileall.compile_dir(self.path, quiet=True, optimize=0,
918 hardlink_dupes=True)
919 with self.assertRaises(ValueError):
920 # same optimization level specified twice:
921 # compile_dir() removes duplicates
922 compileall.compile_dir(self.path, quiet=True, optimize=[0, 0],
923 hardlink_dupes=True)
924
925 def create_code(self, docstring=False, assertion=False):
926 lines = []
927 if docstring:
928 lines.append("'module docstring'")
929 lines.append('x = 1')
930 if assertion:
931 lines.append("assert x == 1")
932 return '\n'.join(lines)
933
934 def iter_codes(self):
935 for docstring in (False, True):
936 for assertion in (False, True):
937 code = self.create_code(docstring=docstring, assertion=assertion)
938 yield (code, docstring, assertion)
939
940 def test_disabled(self):
941 # Deduplication disabled, no hardlinks
942 for code, docstring, assertion in self.iter_codes():
943 with self.subTest(docstring=docstring, assertion=assertion):
944 with self.temporary_directory():
945 script = self.make_script(code)
946 pycs = get_pycs(script)
947 self.compile_dir(dedup=False)
948 self.assertFalse(is_hardlink(pycs[0], pycs[1]))
949 self.assertFalse(is_hardlink(pycs[0], pycs[2]))
950 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
951
952 def check_hardlinks(self, script, docstring=False, assertion=False):
953 pycs = get_pycs(script)
954 self.assertEqual(is_hardlink(pycs[0], pycs[1]),
955 not assertion)
956 self.assertEqual(is_hardlink(pycs[0], pycs[2]),
957 not assertion and not docstring)
958 self.assertEqual(is_hardlink(pycs[1], pycs[2]),
959 not docstring)
960
961 def test_hardlink(self):
962 # Test deduplication on all combinations
963 for code, docstring, assertion in self.iter_codes():
964 with self.subTest(docstring=docstring, assertion=assertion):
965 with self.temporary_directory():
966 script = self.make_script(code)
967 self.compile_dir()
968 self.check_hardlinks(script, docstring, assertion)
969
970 def test_only_two_levels(self):
971 # Don't build the 3 optimization levels, but only 2
972 for opts in ((0, 1), (1, 2), (0, 2)):
973 with self.subTest(opts=opts):
974 with self.temporary_directory():
975 # code with no dostring and no assertion:
976 # same bytecode for all optimization levels
977 script = self.make_script(self.create_code())
978 self.compile_dir(optimize=opts)
979 pyc1 = get_pyc(script, opts[0])
980 pyc2 = get_pyc(script, opts[1])
981 self.assertTrue(is_hardlink(pyc1, pyc2))
982
983 def test_duplicated_levels(self):
984 # compile_dir() must not fail if optimize contains duplicated
985 # optimization levels and/or if optimization levels are not sorted.
986 with self.temporary_directory():
987 # code with no dostring and no assertion:
988 # same bytecode for all optimization levels
989 script = self.make_script(self.create_code())
990 self.compile_dir(optimize=[1, 0, 1, 0])
991 pyc1 = get_pyc(script, 0)
992 pyc2 = get_pyc(script, 1)
993 self.assertTrue(is_hardlink(pyc1, pyc2))
994
995 def test_recompilation(self):
996 # Test compile_dir() when pyc files already exists and the script
997 # content changed
998 with self.temporary_directory():
999 script = self.make_script("a = 0")
1000 self.compile_dir()
1001 # All three levels have the same inode
1002 self.check_hardlinks(script)
1003
1004 pycs = get_pycs(script)
1005 inode = os.stat(pycs[0]).st_ino
1006
1007 # Change of the module content
1008 script = self.make_script("print(0)")
1009
1010 # Recompilation without -o 1
1011 self.compile_dir(optimize=[0, 2], force=True)
1012
1013 # opt-1.pyc should have the same inode as before and others should not
1014 self.assertEqual(inode, os.stat(pycs[1]).st_ino)
1015 self.assertTrue(is_hardlink(pycs[0], pycs[2]))
1016 self.assertNotEqual(inode, os.stat(pycs[2]).st_ino)
1017 # opt-1.pyc and opt-2.pyc have different content
1018 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1019
1020 def test_import(self):
1021 # Test that import updates a single pyc file when pyc files already
1022 # exists and the script content changed
1023 with self.temporary_directory():
1024 script = self.make_script(self.create_code(), name="module")
1025 self.compile_dir()
1026 # All three levels have the same inode
1027 self.check_hardlinks(script)
1028
1029 pycs = get_pycs(script)
1030 inode = os.stat(pycs[0]).st_ino
1031
1032 # Change of the module content
1033 script = self.make_script("print(0)", name="module")
1034
1035 # Import the module in Python with -O (optimization level 1)
1036 script_helper.assert_python_ok(
1037 "-O", "-c", "import module", __isolated=False, PYTHONPATH=self.path
1038 )
1039
1040 # Only opt-1.pyc is changed
1041 self.assertEqual(inode, os.stat(pycs[0]).st_ino)
1042 self.assertEqual(inode, os.stat(pycs[2]).st_ino)
1043 self.assertFalse(is_hardlink(pycs[1], pycs[2]))
1044 # opt-1.pyc and opt-2.pyc have different content
1045 self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True))
1046
1047
1048class HardlinkDedupTestsWithSourceEpoch(HardlinkDedupTestsBase,
1049 unittest.TestCase,
1050 metaclass=SourceDateEpochTestMeta,
1051 source_date_epoch=True):
1052 pass
1053
1054
1055class HardlinkDedupTestsNoSourceEpoch(HardlinkDedupTestsBase,
1056 unittest.TestCase,
1057 metaclass=SourceDateEpochTestMeta,
1058 source_date_epoch=False):
1059 pass
1060
1061
Brett Cannonbefb14f2009-02-10 02:10:16 +00001062if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -04001063 unittest.main()