blob: 2e2552303f8d595fce1be687a25b2abc7ebff85b [file] [log] [blame]
Martin v. Löwis4b003072010-03-16 13:19:21 +00001import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +00002import compileall
Brett Cannon7822e122013-06-14 23:04:02 -04003import importlib.util
Brett Cannon1e3c3e92015-12-27 13:17:04 -08004import test.test_importlib.util
Brett Cannonbefb14f2009-02-10 02:10:16 +00005import os
Brett Cannon65ed7502015-10-09 15:09:43 -07006import pathlib
Brett Cannonbefb14f2009-02-10 02:10:16 +00007import py_compile
8import shutil
9import struct
Brett Cannonbefb14f2009-02-10 02:10:16 +000010import tempfile
R. David Murray650f1472010-11-20 21:18:51 +000011import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000012import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000013import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
Brett Cannonf1a8df02014-09-12 10:39:48 -040015from unittest import mock, skipUnless
16try:
17 from concurrent.futures import ProcessPoolExecutor
18 _have_multiprocessing = True
19except ImportError:
20 _have_multiprocessing = False
21
Berker Peksagce643912015-05-06 06:33:17 +030022from test import support
23from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000024
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040025from .test_py_compile import without_source_date_epoch
26from .test_py_compile import SourceDateEpochTestMeta
27
28
29class CompileallTestsBase:
Brett Cannonbefb14f2009-02-10 02:10:16 +000030
31 def setUp(self):
32 self.directory = tempfile.mkdtemp()
33 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040034 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000035 with open(self.source_path, 'w') as file:
36 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000037 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040038 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000039 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000040 self.subdirectory = os.path.join(self.directory, '_subdir')
41 os.mkdir(self.subdirectory)
42 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
43 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000044
45 def tearDown(self):
46 shutil.rmtree(self.directory)
47
Brett Cannon1e3c3e92015-12-27 13:17:04 -080048 def add_bad_source_file(self):
49 self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
50 with open(self.bad_source_path, 'w') as file:
51 file.write('x (\n')
52
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040053 def timestamp_metadata(self):
Brett Cannonbefb14f2009-02-10 02:10:16 +000054 with open(self.bc_path, 'rb') as file:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080055 data = file.read(12)
Brett Cannonbefb14f2009-02-10 02:10:16 +000056 mtime = int(os.stat(self.source_path).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080057 compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000058 return data, compare
59
Serhiy Storchaka43767632013-11-03 21:31:38 +020060 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000061 def recreation_check(self, metadata):
62 """Check that compileall recreates bytecode when the new metadata is
63 used."""
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040064 if os.environ.get('SOURCE_DATE_EPOCH'):
65 raise unittest.SkipTest('SOURCE_DATE_EPOCH is set')
Brett Cannonbefb14f2009-02-10 02:10:16 +000066 py_compile.compile(self.source_path)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040067 self.assertEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000068 with open(self.bc_path, 'rb') as file:
69 bc = file.read()[len(metadata):]
70 with open(self.bc_path, 'wb') as file:
71 file.write(metadata)
72 file.write(bc)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040073 self.assertNotEqual(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000074 compileall.compile_dir(self.directory, force=False, quiet=True)
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040075 self.assertTrue(*self.timestamp_metadata())
Brett Cannonbefb14f2009-02-10 02:10:16 +000076
77 def test_mtime(self):
78 # Test a change in mtime leads to a new .pyc.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080079 self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
80 0, 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000081
82 def test_magic_number(self):
83 # Test a change in mtime leads to a new .pyc.
84 self.recreation_check(b'\0\0\0\0')
85
Matthias Klosec33b9022010-03-16 00:36:26 +000086 def test_compile_files(self):
87 # Test compiling a single file, and complete directory
88 for fn in (self.bc_path, self.bc_path2):
89 try:
90 os.unlink(fn)
91 except:
92 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -080093 self.assertTrue(compileall.compile_file(self.source_path,
94 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +000095 self.assertTrue(os.path.isfile(self.bc_path) and
96 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000097 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080098 self.assertTrue(compileall.compile_dir(self.directory, force=False,
99 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000100 self.assertTrue(os.path.isfile(self.bc_path) and
101 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +0000102 os.unlink(self.bc_path)
103 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800104 # Test against bad files
105 self.add_bad_source_file()
106 self.assertFalse(compileall.compile_file(self.bad_source_path,
107 force=False, quiet=2))
108 self.assertFalse(compileall.compile_dir(self.directory,
109 force=False, quiet=2))
110
Berker Peksag812a2b62016-10-01 00:54:18 +0300111 def test_compile_file_pathlike(self):
112 self.assertFalse(os.path.isfile(self.bc_path))
113 # we should also test the output
114 with support.captured_stdout() as stdout:
115 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300116 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300117 self.assertTrue(os.path.isfile(self.bc_path))
118
119 def test_compile_file_pathlike_ddir(self):
120 self.assertFalse(os.path.isfile(self.bc_path))
121 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
122 ddir=pathlib.Path('ddir_path'),
123 quiet=2))
124 self.assertTrue(os.path.isfile(self.bc_path))
125
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800126 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300127 with test.test_importlib.util.import_state(path=[self.directory]):
128 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800129
130 with test.test_importlib.util.import_state(path=[self.directory]):
131 self.add_bad_source_file()
132 self.assertFalse(compileall.compile_path(skip_curdir=False,
133 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000134
Barry Warsawc8a99de2010-04-29 18:43:10 +0000135 def test_no_pycache_in_non_package(self):
136 # Bug 8563 reported that __pycache__ directories got created by
137 # compile_file() for non-.py files.
138 data_dir = os.path.join(self.directory, 'data')
139 data_file = os.path.join(data_dir, 'file')
140 os.mkdir(data_dir)
141 # touch data/file
142 with open(data_file, 'w'):
143 pass
144 compileall.compile_file(data_file)
145 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
146
Georg Brandl8334fd92010-12-04 10:26:46 +0000147 def test_optimize(self):
148 # make sure compiling with different optimization settings than the
149 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400150 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000151 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400152 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400153 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000154 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400155 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400156 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000157 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400158 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400159 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000160 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000161
Berker Peksag812a2b62016-10-01 00:54:18 +0300162 def test_compile_dir_pathlike(self):
163 self.assertFalse(os.path.isfile(self.bc_path))
164 with support.captured_stdout() as stdout:
165 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300166 line = stdout.getvalue().splitlines()[0]
167 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300168 self.assertTrue(os.path.isfile(self.bc_path))
169
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500170 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400171 def test_compile_pool_called(self, pool_mock):
172 compileall.compile_dir(self.directory, quiet=True, workers=5)
173 self.assertTrue(pool_mock.called)
174
175 def test_compile_workers_non_positive(self):
176 with self.assertRaisesRegex(ValueError,
177 "workers must be greater or equal to 0"):
178 compileall.compile_dir(self.directory, workers=-1)
179
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500180 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400181 def test_compile_workers_cpu_count(self, pool_mock):
182 compileall.compile_dir(self.directory, quiet=True, workers=0)
183 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
184
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500185 @mock.patch('concurrent.futures.ProcessPoolExecutor')
Brett Cannonf1a8df02014-09-12 10:39:48 -0400186 @mock.patch('compileall.compile_file')
187 def test_compile_one_worker(self, compile_file_mock, pool_mock):
188 compileall.compile_dir(self.directory, quiet=True)
189 self.assertFalse(pool_mock.called)
190 self.assertTrue(compile_file_mock.called)
191
Dustin Spicuzza1d817e42018-11-23 12:06:55 -0500192 @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300193 @mock.patch('compileall.compile_file')
194 def test_compile_missing_multiprocessing(self, compile_file_mock):
195 compileall.compile_dir(self.directory, quiet=True, workers=5)
196 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000197
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400198
199class CompileallTestsWithSourceEpoch(CompileallTestsBase,
200 unittest.TestCase,
201 metaclass=SourceDateEpochTestMeta,
202 source_date_epoch=True):
203 pass
204
205
206class CompileallTestsWithoutSourceEpoch(CompileallTestsBase,
207 unittest.TestCase,
208 metaclass=SourceDateEpochTestMeta,
209 source_date_epoch=False):
210 pass
211
212
Martin v. Löwis4b003072010-03-16 13:19:21 +0000213class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000214 """Issue 6716: compileall should escape source code when printing errors
215 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000216
217 def setUp(self):
218 self.directory = tempfile.mkdtemp()
219 self.source_path = os.path.join(self.directory, '_test.py')
220 with open(self.source_path, 'w', encoding='utf-8') as file:
221 file.write('# -*- coding: utf-8 -*-\n')
222 file.write('print u"\u20ac"\n')
223
224 def tearDown(self):
225 shutil.rmtree(self.directory)
226
227 def test_error(self):
228 try:
229 orig_stdout = sys.stdout
230 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
231 compileall.compile_dir(self.directory)
232 finally:
233 sys.stdout = orig_stdout
234
Barry Warsawc8a99de2010-04-29 18:43:10 +0000235
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400236class CommandLineTestsBase:
R. David Murray650f1472010-11-20 21:18:51 +0000237 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000238
Brett Cannon65ed7502015-10-09 15:09:43 -0700239 @classmethod
240 def setUpClass(cls):
241 for path in filter(os.path.isdir, sys.path):
242 directory_created = False
243 directory = pathlib.Path(path) / '__pycache__'
244 path = directory / 'test.try'
245 try:
246 if not directory.is_dir():
247 directory.mkdir()
248 directory_created = True
249 with path.open('w') as file:
250 file.write('# for test_compileall')
251 except OSError:
252 sys_path_writable = False
253 break
254 finally:
255 support.unlink(str(path))
256 if directory_created:
257 directory.rmdir()
258 else:
259 sys_path_writable = True
260 cls._sys_path_writable = sys_path_writable
261
262 def _skip_if_sys_path_not_writable(self):
263 if not self._sys_path_writable:
264 raise unittest.SkipTest('not all entries on sys.path are writable')
265
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400266 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100267 return [*support.optim_args_from_interpreter_flags(),
268 '-S', '-m', 'compileall',
269 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400270
R. David Murray5317e9c2010-12-16 19:08:51 +0000271 def assertRunOK(self, *args, **env_vars):
272 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400273 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000274 self.assertEqual(b'', err)
275 return out
276
R. David Murray5317e9c2010-12-16 19:08:51 +0000277 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000278 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400279 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000280 return rc, out, err
281
282 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400283 path = importlib.util.cache_from_source(fn)
284 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000285
286 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400287 path = importlib.util.cache_from_source(fn)
288 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000289
Barry Warsaw28a691b2010-04-17 00:19:56 +0000290 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000291 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700292 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000293 self.pkgdir = os.path.join(self.directory, 'foo')
294 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000295 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
296 # Create the __init__.py and a package module.
297 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
298 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000299
R. David Murray5317e9c2010-12-16 19:08:51 +0000300 def test_no_args_compiles_path(self):
301 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700302 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000303 bazfn = script_helper.make_script(self.directory, 'baz', '')
304 self.assertRunOK(PYTHONPATH=self.directory)
305 self.assertCompiled(bazfn)
306 self.assertNotCompiled(self.initfn)
307 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000308
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400309 @without_source_date_epoch # timestamp invalidation test
R David Murray8a1d1e62013-12-15 20:49:38 -0500310 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700311 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500312 bazfn = script_helper.make_script(self.directory, 'baz', '')
313 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500314 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500315 # Set atime/mtime backward to avoid file timestamp resolution issues
316 os.utime(pycpath, (time.time()-60,)*2)
317 mtime = os.stat(pycpath).st_mtime
318 # Without force, no recompilation
319 self.assertRunOK(PYTHONPATH=self.directory)
320 mtime2 = os.stat(pycpath).st_mtime
321 self.assertEqual(mtime, mtime2)
322 # Now force it.
323 self.assertRunOK('-f', PYTHONPATH=self.directory)
324 mtime2 = os.stat(pycpath).st_mtime
325 self.assertNotEqual(mtime, mtime2)
326
327 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700328 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500329 script_helper.make_script(self.directory, 'baz', '')
330 noisy = self.assertRunOK(PYTHONPATH=self.directory)
331 self.assertIn(b'Listing ', noisy)
332 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
333 self.assertNotIn(b'Listing ', quiet)
334
Georg Brandl1463a3f2010-10-14 07:42:27 +0000335 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400336 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000337 for name, ext, switch in [
338 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400339 ('optimize', 'opt-1.pyc', ['-O']),
340 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000341 ]:
342 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000343 script_helper.assert_python_ok(*(switch +
344 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000345 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000346 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400347 expected = sorted(base.format(sys.implementation.cache_tag, ext)
348 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000349 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000350 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000351 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
352 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000353 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000354
355 def test_legacy_paths(self):
356 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400357 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000358 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000359 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000360 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400361 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
362 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000363 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
364
Barry Warsawc04317f2010-04-26 15:59:03 +0000365 def test_multiple_runs(self):
366 # Bug 8527 reported that multiple calls produced empty
367 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000368 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000369 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000370 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
371 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000372 self.assertFalse(os.path.exists(cachecachedir))
373 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000374 self.assertRunOK('-q', self.pkgdir)
375 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000376 self.assertFalse(os.path.exists(cachecachedir))
377
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400378 @without_source_date_epoch # timestamp invalidation test
R. David Murray650f1472010-11-20 21:18:51 +0000379 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000380 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400381 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000382 # set atime/mtime backward to avoid file timestamp resolution issues
383 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000384 mtime = os.stat(pycpath).st_mtime
385 # without force, no recompilation
386 self.assertRunOK('-q', self.pkgdir)
387 mtime2 = os.stat(pycpath).st_mtime
388 self.assertEqual(mtime, mtime2)
389 # now force it.
390 self.assertRunOK('-q', '-f', self.pkgdir)
391 mtime2 = os.stat(pycpath).st_mtime
392 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000393
R. David Murray95333e32010-12-14 22:32:50 +0000394 def test_recursion_control(self):
395 subpackage = os.path.join(self.pkgdir, 'spam')
396 os.mkdir(subpackage)
397 subinitfn = script_helper.make_script(subpackage, '__init__', '')
398 hamfn = script_helper.make_script(subpackage, 'ham', '')
399 self.assertRunOK('-q', '-l', self.pkgdir)
400 self.assertNotCompiled(subinitfn)
401 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
402 self.assertRunOK('-q', self.pkgdir)
403 self.assertCompiled(subinitfn)
404 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000405
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500406 def test_recursion_limit(self):
407 subpackage = os.path.join(self.pkgdir, 'spam')
408 subpackage2 = os.path.join(subpackage, 'ham')
409 subpackage3 = os.path.join(subpackage2, 'eggs')
410 for pkg in (subpackage, subpackage2, subpackage3):
411 script_helper.make_pkg(pkg)
412
413 subinitfn = os.path.join(subpackage, '__init__.py')
414 hamfn = script_helper.make_script(subpackage, 'ham', '')
415 spamfn = script_helper.make_script(subpackage2, 'spam', '')
416 eggfn = script_helper.make_script(subpackage3, 'egg', '')
417
418 self.assertRunOK('-q', '-r 0', self.pkgdir)
419 self.assertNotCompiled(subinitfn)
420 self.assertFalse(
421 os.path.exists(os.path.join(subpackage, '__pycache__')))
422
423 self.assertRunOK('-q', '-r 1', self.pkgdir)
424 self.assertCompiled(subinitfn)
425 self.assertCompiled(hamfn)
426 self.assertNotCompiled(spamfn)
427
428 self.assertRunOK('-q', '-r 2', self.pkgdir)
429 self.assertCompiled(subinitfn)
430 self.assertCompiled(hamfn)
431 self.assertCompiled(spamfn)
432 self.assertNotCompiled(eggfn)
433
434 self.assertRunOK('-q', '-r 5', self.pkgdir)
435 self.assertCompiled(subinitfn)
436 self.assertCompiled(hamfn)
437 self.assertCompiled(spamfn)
438 self.assertCompiled(eggfn)
439
R. David Murray650f1472010-11-20 21:18:51 +0000440 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000441 noisy = self.assertRunOK(self.pkgdir)
442 quiet = self.assertRunOK('-q', self.pkgdir)
443 self.assertNotEqual(b'', noisy)
444 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000445
Berker Peksag6554b862014-10-15 11:10:57 +0300446 def test_silent(self):
447 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
448 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
449 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
450 self.assertNotEqual(b'', quiet)
451 self.assertEqual(b'', silent)
452
R. David Murray650f1472010-11-20 21:18:51 +0000453 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400454 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000455 self.assertNotCompiled(self.barfn)
456 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000457
R. David Murray95333e32010-12-14 22:32:50 +0000458 def test_multiple_dirs(self):
459 pkgdir2 = os.path.join(self.directory, 'foo2')
460 os.mkdir(pkgdir2)
461 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
462 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
463 self.assertRunOK('-q', self.pkgdir, pkgdir2)
464 self.assertCompiled(self.initfn)
465 self.assertCompiled(self.barfn)
466 self.assertCompiled(init2fn)
467 self.assertCompiled(bar2fn)
468
R. David Murray95333e32010-12-14 22:32:50 +0000469 def test_d_compile_error(self):
470 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
471 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
472 self.assertRegex(out, b'File "dinsdale')
473
474 def test_d_runtime_error(self):
475 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
476 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
477 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400478 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000479 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
480 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200481 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000482 self.assertRegex(err, b'File "dinsdale')
483
484 def test_include_bad_file(self):
485 rc, out, err = self.assertRunNotOK(
486 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
487 self.assertRegex(out, b'rror.*nosuchfile')
488 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400489 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000490 self.pkgdir_cachedir)))
491
492 def test_include_file_with_arg(self):
493 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
494 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
495 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
496 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
497 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
498 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
499 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
500 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
501 self.assertCompiled(f1)
502 self.assertCompiled(f2)
503 self.assertNotCompiled(f3)
504 self.assertCompiled(f4)
505
506 def test_include_file_no_arg(self):
507 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
508 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
509 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
510 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
511 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
512 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
513 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
514 self.assertNotCompiled(f1)
515 self.assertCompiled(f2)
516 self.assertNotCompiled(f3)
517 self.assertNotCompiled(f4)
518
519 def test_include_on_stdin(self):
520 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
521 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
522 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
523 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400524 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000525 p.stdin.write((f3+os.linesep).encode('ascii'))
526 script_helper.kill_python(p)
527 self.assertNotCompiled(f1)
528 self.assertNotCompiled(f2)
529 self.assertCompiled(f3)
530 self.assertNotCompiled(f4)
531
532 def test_compiles_as_much_as_possible(self):
533 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
534 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
535 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000536 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000537 self.assertNotCompiled(bingfn)
538 self.assertCompiled(self.initfn)
539 self.assertCompiled(self.barfn)
540
R. David Murray5317e9c2010-12-16 19:08:51 +0000541 def test_invalid_arg_produces_message(self):
542 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200543 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000544
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800545 def test_pyc_invalidation_mode(self):
546 script_helper.make_script(self.pkgdir, 'f1', '')
547 pyc = importlib.util.cache_from_source(
548 os.path.join(self.pkgdir, 'f1.py'))
549 self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)
550 with open(pyc, 'rb') as fp:
551 data = fp.read()
552 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)
553 self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)
554 with open(pyc, 'rb') as fp:
555 data = fp.read()
556 self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)
557
Brett Cannonf1a8df02014-09-12 10:39:48 -0400558 @skipUnless(_have_multiprocessing, "requires multiprocessing")
559 def test_workers(self):
560 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
561 files = []
562 for suffix in range(5):
563 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
564 os.mkdir(pkgdir)
565 fn = script_helper.make_script(pkgdir, '__init__', '')
566 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
567
568 self.assertRunOK(self.directory, '-j', '0')
569 self.assertCompiled(bar2fn)
570 for file in files:
571 self.assertCompiled(file)
572
573 @mock.patch('compileall.compile_dir')
574 def test_workers_available_cores(self, compile_dir):
575 with mock.patch("sys.argv",
576 new=[sys.executable, self.directory, "-j0"]):
577 compileall.main()
578 self.assertTrue(compile_dir.called)
579 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
580
Barry Warsaw28a691b2010-04-17 00:19:56 +0000581
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400582class CommmandLineTestsWithSourceEpoch(CommandLineTestsBase,
583 unittest.TestCase,
584 metaclass=SourceDateEpochTestMeta,
585 source_date_epoch=True):
586 pass
587
588
589class CommmandLineTestsNoSourceEpoch(CommandLineTestsBase,
590 unittest.TestCase,
591 metaclass=SourceDateEpochTestMeta,
592 source_date_epoch=False):
593 pass
594
595
596
Brett Cannonbefb14f2009-02-10 02:10:16 +0000597if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400598 unittest.main()