blob: 2356efcaec78bebb5d1c06284e1e9aca63af8ee9 [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
25class CompileallTests(unittest.TestCase):
26
27 def setUp(self):
28 self.directory = tempfile.mkdtemp()
29 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040030 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000031 with open(self.source_path, 'w') as file:
32 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000033 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040034 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000035 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000036 self.subdirectory = os.path.join(self.directory, '_subdir')
37 os.mkdir(self.subdirectory)
38 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
39 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000040
41 def tearDown(self):
42 shutil.rmtree(self.directory)
43
Brett Cannon1e3c3e92015-12-27 13:17:04 -080044 def add_bad_source_file(self):
45 self.bad_source_path = os.path.join(self.directory, '_test_bad.py')
46 with open(self.bad_source_path, 'w') as file:
47 file.write('x (\n')
48
Brett Cannonbefb14f2009-02-10 02:10:16 +000049 def data(self):
50 with open(self.bc_path, 'rb') as file:
51 data = file.read(8)
52 mtime = int(os.stat(self.source_path).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -040053 compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000054 return data, compare
55
Serhiy Storchaka43767632013-11-03 21:31:38 +020056 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000057 def recreation_check(self, metadata):
58 """Check that compileall recreates bytecode when the new metadata is
59 used."""
Brett Cannonbefb14f2009-02-10 02:10:16 +000060 py_compile.compile(self.source_path)
61 self.assertEqual(*self.data())
62 with open(self.bc_path, 'rb') as file:
63 bc = file.read()[len(metadata):]
64 with open(self.bc_path, 'wb') as file:
65 file.write(metadata)
66 file.write(bc)
67 self.assertNotEqual(*self.data())
68 compileall.compile_dir(self.directory, force=False, quiet=True)
69 self.assertTrue(*self.data())
70
71 def test_mtime(self):
72 # Test a change in mtime leads to a new .pyc.
Brett Cannon7822e122013-06-14 23:04:02 -040073 self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
74 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000075
76 def test_magic_number(self):
77 # Test a change in mtime leads to a new .pyc.
78 self.recreation_check(b'\0\0\0\0')
79
Matthias Klosec33b9022010-03-16 00:36:26 +000080 def test_compile_files(self):
81 # Test compiling a single file, and complete directory
82 for fn in (self.bc_path, self.bc_path2):
83 try:
84 os.unlink(fn)
85 except:
86 pass
Brett Cannon1e3c3e92015-12-27 13:17:04 -080087 self.assertTrue(compileall.compile_file(self.source_path,
88 force=False, quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +000089 self.assertTrue(os.path.isfile(self.bc_path) and
90 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000091 os.unlink(self.bc_path)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080092 self.assertTrue(compileall.compile_dir(self.directory, force=False,
93 quiet=True))
Barry Warsaw28a691b2010-04-17 00:19:56 +000094 self.assertTrue(os.path.isfile(self.bc_path) and
95 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000096 os.unlink(self.bc_path)
97 os.unlink(self.bc_path2)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080098 # Test against bad files
99 self.add_bad_source_file()
100 self.assertFalse(compileall.compile_file(self.bad_source_path,
101 force=False, quiet=2))
102 self.assertFalse(compileall.compile_dir(self.directory,
103 force=False, quiet=2))
104
Berker Peksag812a2b62016-10-01 00:54:18 +0300105 def test_compile_file_pathlike(self):
106 self.assertFalse(os.path.isfile(self.bc_path))
107 # we should also test the output
108 with support.captured_stdout() as stdout:
109 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
Berker Peksagd8e97132016-10-01 02:44:37 +0300110 self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300111 self.assertTrue(os.path.isfile(self.bc_path))
112
113 def test_compile_file_pathlike_ddir(self):
114 self.assertFalse(os.path.isfile(self.bc_path))
115 self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
116 ddir=pathlib.Path('ddir_path'),
117 quiet=2))
118 self.assertTrue(os.path.isfile(self.bc_path))
119
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800120 def test_compile_path(self):
Berker Peksag408b78c2016-09-28 17:38:53 +0300121 with test.test_importlib.util.import_state(path=[self.directory]):
122 self.assertTrue(compileall.compile_path(quiet=2))
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800123
124 with test.test_importlib.util.import_state(path=[self.directory]):
125 self.add_bad_source_file()
126 self.assertFalse(compileall.compile_path(skip_curdir=False,
127 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000128
Barry Warsawc8a99de2010-04-29 18:43:10 +0000129 def test_no_pycache_in_non_package(self):
130 # Bug 8563 reported that __pycache__ directories got created by
131 # compile_file() for non-.py files.
132 data_dir = os.path.join(self.directory, 'data')
133 data_file = os.path.join(data_dir, 'file')
134 os.mkdir(data_dir)
135 # touch data/file
136 with open(data_file, 'w'):
137 pass
138 compileall.compile_file(data_file)
139 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
140
Georg Brandl8334fd92010-12-04 10:26:46 +0000141 def test_optimize(self):
142 # make sure compiling with different optimization settings than the
143 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400144 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000145 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400146 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400147 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000148 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400149 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400150 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000151 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400152 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400153 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000154 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000155
Berker Peksag812a2b62016-10-01 00:54:18 +0300156 def test_compile_dir_pathlike(self):
157 self.assertFalse(os.path.isfile(self.bc_path))
158 with support.captured_stdout() as stdout:
159 compileall.compile_dir(pathlib.Path(self.directory))
Berker Peksagd8e97132016-10-01 02:44:37 +0300160 line = stdout.getvalue().splitlines()[0]
161 self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
Berker Peksag812a2b62016-10-01 00:54:18 +0300162 self.assertTrue(os.path.isfile(self.bc_path))
163
Brett Cannonf1a8df02014-09-12 10:39:48 -0400164 @mock.patch('compileall.ProcessPoolExecutor')
165 def test_compile_pool_called(self, pool_mock):
166 compileall.compile_dir(self.directory, quiet=True, workers=5)
167 self.assertTrue(pool_mock.called)
168
169 def test_compile_workers_non_positive(self):
170 with self.assertRaisesRegex(ValueError,
171 "workers must be greater or equal to 0"):
172 compileall.compile_dir(self.directory, workers=-1)
173
174 @mock.patch('compileall.ProcessPoolExecutor')
175 def test_compile_workers_cpu_count(self, pool_mock):
176 compileall.compile_dir(self.directory, quiet=True, workers=0)
177 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
178
179 @mock.patch('compileall.ProcessPoolExecutor')
180 @mock.patch('compileall.compile_file')
181 def test_compile_one_worker(self, compile_file_mock, pool_mock):
182 compileall.compile_dir(self.directory, quiet=True)
183 self.assertFalse(pool_mock.called)
184 self.assertTrue(compile_file_mock.called)
185
186 @mock.patch('compileall.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300187 @mock.patch('compileall.compile_file')
188 def test_compile_missing_multiprocessing(self, compile_file_mock):
189 compileall.compile_dir(self.directory, quiet=True, workers=5)
190 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000191
Martin v. Löwis4b003072010-03-16 13:19:21 +0000192class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000193 """Issue 6716: compileall should escape source code when printing errors
194 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000195
196 def setUp(self):
197 self.directory = tempfile.mkdtemp()
198 self.source_path = os.path.join(self.directory, '_test.py')
199 with open(self.source_path, 'w', encoding='utf-8') as file:
200 file.write('# -*- coding: utf-8 -*-\n')
201 file.write('print u"\u20ac"\n')
202
203 def tearDown(self):
204 shutil.rmtree(self.directory)
205
206 def test_error(self):
207 try:
208 orig_stdout = sys.stdout
209 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
210 compileall.compile_dir(self.directory)
211 finally:
212 sys.stdout = orig_stdout
213
Barry Warsawc8a99de2010-04-29 18:43:10 +0000214
Barry Warsaw28a691b2010-04-17 00:19:56 +0000215class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000216 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000217
Brett Cannon65ed7502015-10-09 15:09:43 -0700218 @classmethod
219 def setUpClass(cls):
220 for path in filter(os.path.isdir, sys.path):
221 directory_created = False
222 directory = pathlib.Path(path) / '__pycache__'
223 path = directory / 'test.try'
224 try:
225 if not directory.is_dir():
226 directory.mkdir()
227 directory_created = True
228 with path.open('w') as file:
229 file.write('# for test_compileall')
230 except OSError:
231 sys_path_writable = False
232 break
233 finally:
234 support.unlink(str(path))
235 if directory_created:
236 directory.rmdir()
237 else:
238 sys_path_writable = True
239 cls._sys_path_writable = sys_path_writable
240
241 def _skip_if_sys_path_not_writable(self):
242 if not self._sys_path_writable:
243 raise unittest.SkipTest('not all entries on sys.path are writable')
244
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400245 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100246 return [*support.optim_args_from_interpreter_flags(),
247 '-S', '-m', 'compileall',
248 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400249
R. David Murray5317e9c2010-12-16 19:08:51 +0000250 def assertRunOK(self, *args, **env_vars):
251 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400252 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000253 self.assertEqual(b'', err)
254 return out
255
R. David Murray5317e9c2010-12-16 19:08:51 +0000256 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000257 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400258 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000259 return rc, out, err
260
261 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400262 path = importlib.util.cache_from_source(fn)
263 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000264
265 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400266 path = importlib.util.cache_from_source(fn)
267 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000268
Barry Warsaw28a691b2010-04-17 00:19:56 +0000269 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000270 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700271 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000272 self.pkgdir = os.path.join(self.directory, 'foo')
273 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000274 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
275 # Create the __init__.py and a package module.
276 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
277 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000278
R. David Murray5317e9c2010-12-16 19:08:51 +0000279 def test_no_args_compiles_path(self):
280 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700281 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000282 bazfn = script_helper.make_script(self.directory, 'baz', '')
283 self.assertRunOK(PYTHONPATH=self.directory)
284 self.assertCompiled(bazfn)
285 self.assertNotCompiled(self.initfn)
286 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000287
R David Murray8a1d1e62013-12-15 20:49:38 -0500288 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700289 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500290 bazfn = script_helper.make_script(self.directory, 'baz', '')
291 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500292 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500293 # Set atime/mtime backward to avoid file timestamp resolution issues
294 os.utime(pycpath, (time.time()-60,)*2)
295 mtime = os.stat(pycpath).st_mtime
296 # Without force, no recompilation
297 self.assertRunOK(PYTHONPATH=self.directory)
298 mtime2 = os.stat(pycpath).st_mtime
299 self.assertEqual(mtime, mtime2)
300 # Now force it.
301 self.assertRunOK('-f', PYTHONPATH=self.directory)
302 mtime2 = os.stat(pycpath).st_mtime
303 self.assertNotEqual(mtime, mtime2)
304
305 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700306 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500307 script_helper.make_script(self.directory, 'baz', '')
308 noisy = self.assertRunOK(PYTHONPATH=self.directory)
309 self.assertIn(b'Listing ', noisy)
310 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
311 self.assertNotIn(b'Listing ', quiet)
312
Georg Brandl1463a3f2010-10-14 07:42:27 +0000313 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400314 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000315 for name, ext, switch in [
316 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400317 ('optimize', 'opt-1.pyc', ['-O']),
318 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000319 ]:
320 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000321 script_helper.assert_python_ok(*(switch +
322 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000323 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000324 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400325 expected = sorted(base.format(sys.implementation.cache_tag, ext)
326 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000327 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000328 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000329 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
330 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000331 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000332
333 def test_legacy_paths(self):
334 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400335 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000336 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000337 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000338 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400339 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
340 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000341 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
342
Barry Warsawc04317f2010-04-26 15:59:03 +0000343 def test_multiple_runs(self):
344 # Bug 8527 reported that multiple calls produced empty
345 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000346 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000347 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000348 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
349 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000350 self.assertFalse(os.path.exists(cachecachedir))
351 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000352 self.assertRunOK('-q', self.pkgdir)
353 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000354 self.assertFalse(os.path.exists(cachecachedir))
355
R. David Murray650f1472010-11-20 21:18:51 +0000356 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000357 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400358 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000359 # set atime/mtime backward to avoid file timestamp resolution issues
360 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000361 mtime = os.stat(pycpath).st_mtime
362 # without force, no recompilation
363 self.assertRunOK('-q', self.pkgdir)
364 mtime2 = os.stat(pycpath).st_mtime
365 self.assertEqual(mtime, mtime2)
366 # now force it.
367 self.assertRunOK('-q', '-f', self.pkgdir)
368 mtime2 = os.stat(pycpath).st_mtime
369 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000370
R. David Murray95333e32010-12-14 22:32:50 +0000371 def test_recursion_control(self):
372 subpackage = os.path.join(self.pkgdir, 'spam')
373 os.mkdir(subpackage)
374 subinitfn = script_helper.make_script(subpackage, '__init__', '')
375 hamfn = script_helper.make_script(subpackage, 'ham', '')
376 self.assertRunOK('-q', '-l', self.pkgdir)
377 self.assertNotCompiled(subinitfn)
378 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
379 self.assertRunOK('-q', self.pkgdir)
380 self.assertCompiled(subinitfn)
381 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000382
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500383 def test_recursion_limit(self):
384 subpackage = os.path.join(self.pkgdir, 'spam')
385 subpackage2 = os.path.join(subpackage, 'ham')
386 subpackage3 = os.path.join(subpackage2, 'eggs')
387 for pkg in (subpackage, subpackage2, subpackage3):
388 script_helper.make_pkg(pkg)
389
390 subinitfn = os.path.join(subpackage, '__init__.py')
391 hamfn = script_helper.make_script(subpackage, 'ham', '')
392 spamfn = script_helper.make_script(subpackage2, 'spam', '')
393 eggfn = script_helper.make_script(subpackage3, 'egg', '')
394
395 self.assertRunOK('-q', '-r 0', self.pkgdir)
396 self.assertNotCompiled(subinitfn)
397 self.assertFalse(
398 os.path.exists(os.path.join(subpackage, '__pycache__')))
399
400 self.assertRunOK('-q', '-r 1', self.pkgdir)
401 self.assertCompiled(subinitfn)
402 self.assertCompiled(hamfn)
403 self.assertNotCompiled(spamfn)
404
405 self.assertRunOK('-q', '-r 2', self.pkgdir)
406 self.assertCompiled(subinitfn)
407 self.assertCompiled(hamfn)
408 self.assertCompiled(spamfn)
409 self.assertNotCompiled(eggfn)
410
411 self.assertRunOK('-q', '-r 5', self.pkgdir)
412 self.assertCompiled(subinitfn)
413 self.assertCompiled(hamfn)
414 self.assertCompiled(spamfn)
415 self.assertCompiled(eggfn)
416
R. David Murray650f1472010-11-20 21:18:51 +0000417 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000418 noisy = self.assertRunOK(self.pkgdir)
419 quiet = self.assertRunOK('-q', self.pkgdir)
420 self.assertNotEqual(b'', noisy)
421 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000422
Berker Peksag6554b862014-10-15 11:10:57 +0300423 def test_silent(self):
424 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
425 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
426 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
427 self.assertNotEqual(b'', quiet)
428 self.assertEqual(b'', silent)
429
R. David Murray650f1472010-11-20 21:18:51 +0000430 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400431 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000432 self.assertNotCompiled(self.barfn)
433 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000434
R. David Murray95333e32010-12-14 22:32:50 +0000435 def test_multiple_dirs(self):
436 pkgdir2 = os.path.join(self.directory, 'foo2')
437 os.mkdir(pkgdir2)
438 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
439 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
440 self.assertRunOK('-q', self.pkgdir, pkgdir2)
441 self.assertCompiled(self.initfn)
442 self.assertCompiled(self.barfn)
443 self.assertCompiled(init2fn)
444 self.assertCompiled(bar2fn)
445
R. David Murray95333e32010-12-14 22:32:50 +0000446 def test_d_compile_error(self):
447 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
448 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
449 self.assertRegex(out, b'File "dinsdale')
450
451 def test_d_runtime_error(self):
452 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
453 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
454 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400455 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000456 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
457 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200458 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000459 self.assertRegex(err, b'File "dinsdale')
460
461 def test_include_bad_file(self):
462 rc, out, err = self.assertRunNotOK(
463 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
464 self.assertRegex(out, b'rror.*nosuchfile')
465 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400466 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000467 self.pkgdir_cachedir)))
468
469 def test_include_file_with_arg(self):
470 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
471 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
472 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
473 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
474 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
475 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
476 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
477 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
478 self.assertCompiled(f1)
479 self.assertCompiled(f2)
480 self.assertNotCompiled(f3)
481 self.assertCompiled(f4)
482
483 def test_include_file_no_arg(self):
484 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
485 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
486 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
487 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
488 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
489 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
490 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
491 self.assertNotCompiled(f1)
492 self.assertCompiled(f2)
493 self.assertNotCompiled(f3)
494 self.assertNotCompiled(f4)
495
496 def test_include_on_stdin(self):
497 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
498 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
499 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
500 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400501 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000502 p.stdin.write((f3+os.linesep).encode('ascii'))
503 script_helper.kill_python(p)
504 self.assertNotCompiled(f1)
505 self.assertNotCompiled(f2)
506 self.assertCompiled(f3)
507 self.assertNotCompiled(f4)
508
509 def test_compiles_as_much_as_possible(self):
510 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
511 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
512 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000513 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000514 self.assertNotCompiled(bingfn)
515 self.assertCompiled(self.initfn)
516 self.assertCompiled(self.barfn)
517
R. David Murray5317e9c2010-12-16 19:08:51 +0000518 def test_invalid_arg_produces_message(self):
519 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200520 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000521
Brett Cannonf1a8df02014-09-12 10:39:48 -0400522 @skipUnless(_have_multiprocessing, "requires multiprocessing")
523 def test_workers(self):
524 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
525 files = []
526 for suffix in range(5):
527 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
528 os.mkdir(pkgdir)
529 fn = script_helper.make_script(pkgdir, '__init__', '')
530 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
531
532 self.assertRunOK(self.directory, '-j', '0')
533 self.assertCompiled(bar2fn)
534 for file in files:
535 self.assertCompiled(file)
536
537 @mock.patch('compileall.compile_dir')
538 def test_workers_available_cores(self, compile_dir):
539 with mock.patch("sys.argv",
540 new=[sys.executable, self.directory, "-j0"]):
541 compileall.main()
542 self.assertTrue(compile_dir.called)
543 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
544
Barry Warsaw28a691b2010-04-17 00:19:56 +0000545
Brett Cannonbefb14f2009-02-10 02:10:16 +0000546if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400547 unittest.main()