blob: 9b424a7250617d78f8420035098d09ad8fe878b4 [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
105 def test_compile_path(self):
Victor Stinnerc437d0c2016-01-18 11:25:50 +0100106 # Exclude Lib/test/ which contains invalid Python files like
107 # Lib/test/badsyntax_pep3120.py
108 testdir = os.path.realpath(os.path.dirname(__file__))
109 if testdir in sys.path:
110 self.addCleanup(setattr, sys, 'path', sys.path)
111
112 sys.path = list(sys.path)
113 try:
114 sys.path.remove(testdir)
115 except ValueError:
116 pass
117
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800118 self.assertTrue(compileall.compile_path(quiet=2))
119
120 with test.test_importlib.util.import_state(path=[self.directory]):
121 self.add_bad_source_file()
122 self.assertFalse(compileall.compile_path(skip_curdir=False,
123 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000124
Barry Warsawc8a99de2010-04-29 18:43:10 +0000125 def test_no_pycache_in_non_package(self):
126 # Bug 8563 reported that __pycache__ directories got created by
127 # compile_file() for non-.py files.
128 data_dir = os.path.join(self.directory, 'data')
129 data_file = os.path.join(data_dir, 'file')
130 os.mkdir(data_dir)
131 # touch data/file
132 with open(data_file, 'w'):
133 pass
134 compileall.compile_file(data_file)
135 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
136
Georg Brandl8334fd92010-12-04 10:26:46 +0000137 def test_optimize(self):
138 # make sure compiling with different optimization settings than the
139 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400140 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000141 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400142 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400143 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000144 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400145 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400146 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000147 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400148 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400149 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000150 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000151
Brett Cannonf1a8df02014-09-12 10:39:48 -0400152 @mock.patch('compileall.ProcessPoolExecutor')
153 def test_compile_pool_called(self, pool_mock):
154 compileall.compile_dir(self.directory, quiet=True, workers=5)
155 self.assertTrue(pool_mock.called)
156
157 def test_compile_workers_non_positive(self):
158 with self.assertRaisesRegex(ValueError,
159 "workers must be greater or equal to 0"):
160 compileall.compile_dir(self.directory, workers=-1)
161
162 @mock.patch('compileall.ProcessPoolExecutor')
163 def test_compile_workers_cpu_count(self, pool_mock):
164 compileall.compile_dir(self.directory, quiet=True, workers=0)
165 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
166
167 @mock.patch('compileall.ProcessPoolExecutor')
168 @mock.patch('compileall.compile_file')
169 def test_compile_one_worker(self, compile_file_mock, pool_mock):
170 compileall.compile_dir(self.directory, quiet=True)
171 self.assertFalse(pool_mock.called)
172 self.assertTrue(compile_file_mock.called)
173
174 @mock.patch('compileall.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300175 @mock.patch('compileall.compile_file')
176 def test_compile_missing_multiprocessing(self, compile_file_mock):
177 compileall.compile_dir(self.directory, quiet=True, workers=5)
178 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000179
Martin v. Löwis4b003072010-03-16 13:19:21 +0000180class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000181 """Issue 6716: compileall should escape source code when printing errors
182 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000183
184 def setUp(self):
185 self.directory = tempfile.mkdtemp()
186 self.source_path = os.path.join(self.directory, '_test.py')
187 with open(self.source_path, 'w', encoding='utf-8') as file:
188 file.write('# -*- coding: utf-8 -*-\n')
189 file.write('print u"\u20ac"\n')
190
191 def tearDown(self):
192 shutil.rmtree(self.directory)
193
194 def test_error(self):
195 try:
196 orig_stdout = sys.stdout
197 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
198 compileall.compile_dir(self.directory)
199 finally:
200 sys.stdout = orig_stdout
201
Barry Warsawc8a99de2010-04-29 18:43:10 +0000202
Barry Warsaw28a691b2010-04-17 00:19:56 +0000203class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000204 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000205
Brett Cannon65ed7502015-10-09 15:09:43 -0700206 @classmethod
207 def setUpClass(cls):
208 for path in filter(os.path.isdir, sys.path):
209 directory_created = False
210 directory = pathlib.Path(path) / '__pycache__'
211 path = directory / 'test.try'
212 try:
213 if not directory.is_dir():
214 directory.mkdir()
215 directory_created = True
216 with path.open('w') as file:
217 file.write('# for test_compileall')
218 except OSError:
219 sys_path_writable = False
220 break
221 finally:
222 support.unlink(str(path))
223 if directory_created:
224 directory.rmdir()
225 else:
226 sys_path_writable = True
227 cls._sys_path_writable = sys_path_writable
228
229 def _skip_if_sys_path_not_writable(self):
230 if not self._sys_path_writable:
231 raise unittest.SkipTest('not all entries on sys.path are writable')
232
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400233 def _get_run_args(self, args):
Victor Stinner9def2842016-01-18 12:15:08 +0100234 return [*support.optim_args_from_interpreter_flags(),
235 '-S', '-m', 'compileall',
236 *args]
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400237
R. David Murray5317e9c2010-12-16 19:08:51 +0000238 def assertRunOK(self, *args, **env_vars):
239 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400240 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000241 self.assertEqual(b'', err)
242 return out
243
R. David Murray5317e9c2010-12-16 19:08:51 +0000244 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000245 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400246 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000247 return rc, out, err
248
249 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400250 path = importlib.util.cache_from_source(fn)
251 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000252
253 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400254 path = importlib.util.cache_from_source(fn)
255 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000256
Barry Warsaw28a691b2010-04-17 00:19:56 +0000257 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000258 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700259 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000260 self.pkgdir = os.path.join(self.directory, 'foo')
261 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000262 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
263 # Create the __init__.py and a package module.
264 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
265 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000266
R. David Murray5317e9c2010-12-16 19:08:51 +0000267 def test_no_args_compiles_path(self):
268 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700269 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000270 bazfn = script_helper.make_script(self.directory, 'baz', '')
271 self.assertRunOK(PYTHONPATH=self.directory)
272 self.assertCompiled(bazfn)
273 self.assertNotCompiled(self.initfn)
274 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000275
R David Murray8a1d1e62013-12-15 20:49:38 -0500276 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700277 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500278 bazfn = script_helper.make_script(self.directory, 'baz', '')
279 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500280 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500281 # Set atime/mtime backward to avoid file timestamp resolution issues
282 os.utime(pycpath, (time.time()-60,)*2)
283 mtime = os.stat(pycpath).st_mtime
284 # Without force, no recompilation
285 self.assertRunOK(PYTHONPATH=self.directory)
286 mtime2 = os.stat(pycpath).st_mtime
287 self.assertEqual(mtime, mtime2)
288 # Now force it.
289 self.assertRunOK('-f', PYTHONPATH=self.directory)
290 mtime2 = os.stat(pycpath).st_mtime
291 self.assertNotEqual(mtime, mtime2)
292
293 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700294 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500295 script_helper.make_script(self.directory, 'baz', '')
296 noisy = self.assertRunOK(PYTHONPATH=self.directory)
297 self.assertIn(b'Listing ', noisy)
298 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
299 self.assertNotIn(b'Listing ', quiet)
300
Georg Brandl1463a3f2010-10-14 07:42:27 +0000301 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400302 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000303 for name, ext, switch in [
304 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400305 ('optimize', 'opt-1.pyc', ['-O']),
306 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000307 ]:
308 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000309 script_helper.assert_python_ok(*(switch +
310 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000311 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000312 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400313 expected = sorted(base.format(sys.implementation.cache_tag, ext)
314 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000315 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000316 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000317 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
318 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000319 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000320
321 def test_legacy_paths(self):
322 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400323 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000324 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000325 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000326 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400327 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
328 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000329 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
330
Barry Warsawc04317f2010-04-26 15:59:03 +0000331 def test_multiple_runs(self):
332 # Bug 8527 reported that multiple calls produced empty
333 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000334 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000335 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000336 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
337 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000338 self.assertFalse(os.path.exists(cachecachedir))
339 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000340 self.assertRunOK('-q', self.pkgdir)
341 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000342 self.assertFalse(os.path.exists(cachecachedir))
343
R. David Murray650f1472010-11-20 21:18:51 +0000344 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000345 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400346 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000347 # set atime/mtime backward to avoid file timestamp resolution issues
348 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000349 mtime = os.stat(pycpath).st_mtime
350 # without force, no recompilation
351 self.assertRunOK('-q', self.pkgdir)
352 mtime2 = os.stat(pycpath).st_mtime
353 self.assertEqual(mtime, mtime2)
354 # now force it.
355 self.assertRunOK('-q', '-f', self.pkgdir)
356 mtime2 = os.stat(pycpath).st_mtime
357 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000358
R. David Murray95333e32010-12-14 22:32:50 +0000359 def test_recursion_control(self):
360 subpackage = os.path.join(self.pkgdir, 'spam')
361 os.mkdir(subpackage)
362 subinitfn = script_helper.make_script(subpackage, '__init__', '')
363 hamfn = script_helper.make_script(subpackage, 'ham', '')
364 self.assertRunOK('-q', '-l', self.pkgdir)
365 self.assertNotCompiled(subinitfn)
366 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
367 self.assertRunOK('-q', self.pkgdir)
368 self.assertCompiled(subinitfn)
369 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000370
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500371 def test_recursion_limit(self):
372 subpackage = os.path.join(self.pkgdir, 'spam')
373 subpackage2 = os.path.join(subpackage, 'ham')
374 subpackage3 = os.path.join(subpackage2, 'eggs')
375 for pkg in (subpackage, subpackage2, subpackage3):
376 script_helper.make_pkg(pkg)
377
378 subinitfn = os.path.join(subpackage, '__init__.py')
379 hamfn = script_helper.make_script(subpackage, 'ham', '')
380 spamfn = script_helper.make_script(subpackage2, 'spam', '')
381 eggfn = script_helper.make_script(subpackage3, 'egg', '')
382
383 self.assertRunOK('-q', '-r 0', self.pkgdir)
384 self.assertNotCompiled(subinitfn)
385 self.assertFalse(
386 os.path.exists(os.path.join(subpackage, '__pycache__')))
387
388 self.assertRunOK('-q', '-r 1', self.pkgdir)
389 self.assertCompiled(subinitfn)
390 self.assertCompiled(hamfn)
391 self.assertNotCompiled(spamfn)
392
393 self.assertRunOK('-q', '-r 2', self.pkgdir)
394 self.assertCompiled(subinitfn)
395 self.assertCompiled(hamfn)
396 self.assertCompiled(spamfn)
397 self.assertNotCompiled(eggfn)
398
399 self.assertRunOK('-q', '-r 5', self.pkgdir)
400 self.assertCompiled(subinitfn)
401 self.assertCompiled(hamfn)
402 self.assertCompiled(spamfn)
403 self.assertCompiled(eggfn)
404
R. David Murray650f1472010-11-20 21:18:51 +0000405 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000406 noisy = self.assertRunOK(self.pkgdir)
407 quiet = self.assertRunOK('-q', self.pkgdir)
408 self.assertNotEqual(b'', noisy)
409 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000410
Berker Peksag6554b862014-10-15 11:10:57 +0300411 def test_silent(self):
412 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
413 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
414 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
415 self.assertNotEqual(b'', quiet)
416 self.assertEqual(b'', silent)
417
R. David Murray650f1472010-11-20 21:18:51 +0000418 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400419 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000420 self.assertNotCompiled(self.barfn)
421 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000422
R. David Murray95333e32010-12-14 22:32:50 +0000423 def test_multiple_dirs(self):
424 pkgdir2 = os.path.join(self.directory, 'foo2')
425 os.mkdir(pkgdir2)
426 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
427 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
428 self.assertRunOK('-q', self.pkgdir, pkgdir2)
429 self.assertCompiled(self.initfn)
430 self.assertCompiled(self.barfn)
431 self.assertCompiled(init2fn)
432 self.assertCompiled(bar2fn)
433
R. David Murray95333e32010-12-14 22:32:50 +0000434 def test_d_compile_error(self):
435 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
436 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
437 self.assertRegex(out, b'File "dinsdale')
438
439 def test_d_runtime_error(self):
440 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
441 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
442 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400443 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000444 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
445 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200446 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000447 self.assertRegex(err, b'File "dinsdale')
448
449 def test_include_bad_file(self):
450 rc, out, err = self.assertRunNotOK(
451 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
452 self.assertRegex(out, b'rror.*nosuchfile')
453 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400454 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000455 self.pkgdir_cachedir)))
456
457 def test_include_file_with_arg(self):
458 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
459 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
460 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
461 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
462 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
463 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
464 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
465 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
466 self.assertCompiled(f1)
467 self.assertCompiled(f2)
468 self.assertNotCompiled(f3)
469 self.assertCompiled(f4)
470
471 def test_include_file_no_arg(self):
472 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
473 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
474 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
475 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
476 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
477 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
478 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
479 self.assertNotCompiled(f1)
480 self.assertCompiled(f2)
481 self.assertNotCompiled(f3)
482 self.assertNotCompiled(f4)
483
484 def test_include_on_stdin(self):
485 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
486 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
487 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
488 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400489 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000490 p.stdin.write((f3+os.linesep).encode('ascii'))
491 script_helper.kill_python(p)
492 self.assertNotCompiled(f1)
493 self.assertNotCompiled(f2)
494 self.assertCompiled(f3)
495 self.assertNotCompiled(f4)
496
497 def test_compiles_as_much_as_possible(self):
498 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
499 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
500 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000501 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000502 self.assertNotCompiled(bingfn)
503 self.assertCompiled(self.initfn)
504 self.assertCompiled(self.barfn)
505
R. David Murray5317e9c2010-12-16 19:08:51 +0000506 def test_invalid_arg_produces_message(self):
507 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200508 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000509
Brett Cannonf1a8df02014-09-12 10:39:48 -0400510 @skipUnless(_have_multiprocessing, "requires multiprocessing")
511 def test_workers(self):
512 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
513 files = []
514 for suffix in range(5):
515 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
516 os.mkdir(pkgdir)
517 fn = script_helper.make_script(pkgdir, '__init__', '')
518 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
519
520 self.assertRunOK(self.directory, '-j', '0')
521 self.assertCompiled(bar2fn)
522 for file in files:
523 self.assertCompiled(file)
524
525 @mock.patch('compileall.compile_dir')
526 def test_workers_available_cores(self, compile_dir):
527 with mock.patch("sys.argv",
528 new=[sys.executable, self.directory, "-j0"]):
529 compileall.main()
530 self.assertTrue(compile_dir.called)
531 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
532
Barry Warsaw28a691b2010-04-17 00:19:56 +0000533
Brett Cannonbefb14f2009-02-10 02:10:16 +0000534if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400535 unittest.main()