blob: 439c125edb3de7f1e54a239de1883628cb5eff04 [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):
106 self.assertTrue(compileall.compile_path(quiet=2))
107
108 with test.test_importlib.util.import_state(path=[self.directory]):
109 self.add_bad_source_file()
110 self.assertFalse(compileall.compile_path(skip_curdir=False,
111 force=True, quiet=2))
Brett Cannonbefb14f2009-02-10 02:10:16 +0000112
Barry Warsawc8a99de2010-04-29 18:43:10 +0000113 def test_no_pycache_in_non_package(self):
114 # Bug 8563 reported that __pycache__ directories got created by
115 # compile_file() for non-.py files.
116 data_dir = os.path.join(self.directory, 'data')
117 data_file = os.path.join(data_dir, 'file')
118 os.mkdir(data_dir)
119 # touch data/file
120 with open(data_file, 'w'):
121 pass
122 compileall.compile_file(data_file)
123 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
124
Georg Brandl8334fd92010-12-04 10:26:46 +0000125 def test_optimize(self):
126 # make sure compiling with different optimization settings than the
127 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400128 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000129 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400130 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400131 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000132 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400133 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400134 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000135 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400136 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400137 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000138 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000139
Brett Cannonf1a8df02014-09-12 10:39:48 -0400140 @mock.patch('compileall.ProcessPoolExecutor')
141 def test_compile_pool_called(self, pool_mock):
142 compileall.compile_dir(self.directory, quiet=True, workers=5)
143 self.assertTrue(pool_mock.called)
144
145 def test_compile_workers_non_positive(self):
146 with self.assertRaisesRegex(ValueError,
147 "workers must be greater or equal to 0"):
148 compileall.compile_dir(self.directory, workers=-1)
149
150 @mock.patch('compileall.ProcessPoolExecutor')
151 def test_compile_workers_cpu_count(self, pool_mock):
152 compileall.compile_dir(self.directory, quiet=True, workers=0)
153 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
154
155 @mock.patch('compileall.ProcessPoolExecutor')
156 @mock.patch('compileall.compile_file')
157 def test_compile_one_worker(self, compile_file_mock, pool_mock):
158 compileall.compile_dir(self.directory, quiet=True)
159 self.assertFalse(pool_mock.called)
160 self.assertTrue(compile_file_mock.called)
161
162 @mock.patch('compileall.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300163 @mock.patch('compileall.compile_file')
164 def test_compile_missing_multiprocessing(self, compile_file_mock):
165 compileall.compile_dir(self.directory, quiet=True, workers=5)
166 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000167
Martin v. Löwis4b003072010-03-16 13:19:21 +0000168class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000169 """Issue 6716: compileall should escape source code when printing errors
170 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000171
172 def setUp(self):
173 self.directory = tempfile.mkdtemp()
174 self.source_path = os.path.join(self.directory, '_test.py')
175 with open(self.source_path, 'w', encoding='utf-8') as file:
176 file.write('# -*- coding: utf-8 -*-\n')
177 file.write('print u"\u20ac"\n')
178
179 def tearDown(self):
180 shutil.rmtree(self.directory)
181
182 def test_error(self):
183 try:
184 orig_stdout = sys.stdout
185 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
186 compileall.compile_dir(self.directory)
187 finally:
188 sys.stdout = orig_stdout
189
Barry Warsawc8a99de2010-04-29 18:43:10 +0000190
Barry Warsaw28a691b2010-04-17 00:19:56 +0000191class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000192 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000193
Brett Cannon65ed7502015-10-09 15:09:43 -0700194 @classmethod
195 def setUpClass(cls):
196 for path in filter(os.path.isdir, sys.path):
197 directory_created = False
198 directory = pathlib.Path(path) / '__pycache__'
199 path = directory / 'test.try'
200 try:
201 if not directory.is_dir():
202 directory.mkdir()
203 directory_created = True
204 with path.open('w') as file:
205 file.write('# for test_compileall')
206 except OSError:
207 sys_path_writable = False
208 break
209 finally:
210 support.unlink(str(path))
211 if directory_created:
212 directory.rmdir()
213 else:
214 sys_path_writable = True
215 cls._sys_path_writable = sys_path_writable
216
217 def _skip_if_sys_path_not_writable(self):
218 if not self._sys_path_writable:
219 raise unittest.SkipTest('not all entries on sys.path are writable')
220
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400221 def _get_run_args(self, args):
222 interp_args = ['-S']
223 if sys.flags.optimize:
224 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
225 return interp_args + ['-m', 'compileall'] + list(args)
226
R. David Murray5317e9c2010-12-16 19:08:51 +0000227 def assertRunOK(self, *args, **env_vars):
228 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400229 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000230 self.assertEqual(b'', err)
231 return out
232
R. David Murray5317e9c2010-12-16 19:08:51 +0000233 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000234 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400235 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000236 return rc, out, err
237
238 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400239 path = importlib.util.cache_from_source(fn)
240 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000241
242 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400243 path = importlib.util.cache_from_source(fn)
244 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000245
Barry Warsaw28a691b2010-04-17 00:19:56 +0000246 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000247 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700248 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000249 self.pkgdir = os.path.join(self.directory, 'foo')
250 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000251 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
252 # Create the __init__.py and a package module.
253 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
254 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000255
R. David Murray5317e9c2010-12-16 19:08:51 +0000256 def test_no_args_compiles_path(self):
257 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700258 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000259 bazfn = script_helper.make_script(self.directory, 'baz', '')
260 self.assertRunOK(PYTHONPATH=self.directory)
261 self.assertCompiled(bazfn)
262 self.assertNotCompiled(self.initfn)
263 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000264
R David Murray8a1d1e62013-12-15 20:49:38 -0500265 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700266 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500267 bazfn = script_helper.make_script(self.directory, 'baz', '')
268 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500269 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500270 # Set atime/mtime backward to avoid file timestamp resolution issues
271 os.utime(pycpath, (time.time()-60,)*2)
272 mtime = os.stat(pycpath).st_mtime
273 # Without force, no recompilation
274 self.assertRunOK(PYTHONPATH=self.directory)
275 mtime2 = os.stat(pycpath).st_mtime
276 self.assertEqual(mtime, mtime2)
277 # Now force it.
278 self.assertRunOK('-f', PYTHONPATH=self.directory)
279 mtime2 = os.stat(pycpath).st_mtime
280 self.assertNotEqual(mtime, mtime2)
281
282 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700283 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500284 script_helper.make_script(self.directory, 'baz', '')
285 noisy = self.assertRunOK(PYTHONPATH=self.directory)
286 self.assertIn(b'Listing ', noisy)
287 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
288 self.assertNotIn(b'Listing ', quiet)
289
Georg Brandl1463a3f2010-10-14 07:42:27 +0000290 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400291 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000292 for name, ext, switch in [
293 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400294 ('optimize', 'opt-1.pyc', ['-O']),
295 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000296 ]:
297 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000298 script_helper.assert_python_ok(*(switch +
299 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000300 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000301 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400302 expected = sorted(base.format(sys.implementation.cache_tag, ext)
303 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000304 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000305 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000306 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
307 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000308 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000309
310 def test_legacy_paths(self):
311 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400312 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000313 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000314 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000315 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400316 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
317 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000318 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
319
Barry Warsawc04317f2010-04-26 15:59:03 +0000320 def test_multiple_runs(self):
321 # Bug 8527 reported that multiple calls produced empty
322 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000323 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000324 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000325 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
326 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000327 self.assertFalse(os.path.exists(cachecachedir))
328 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000329 self.assertRunOK('-q', self.pkgdir)
330 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000331 self.assertFalse(os.path.exists(cachecachedir))
332
R. David Murray650f1472010-11-20 21:18:51 +0000333 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000334 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400335 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000336 # set atime/mtime backward to avoid file timestamp resolution issues
337 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000338 mtime = os.stat(pycpath).st_mtime
339 # without force, no recompilation
340 self.assertRunOK('-q', self.pkgdir)
341 mtime2 = os.stat(pycpath).st_mtime
342 self.assertEqual(mtime, mtime2)
343 # now force it.
344 self.assertRunOK('-q', '-f', self.pkgdir)
345 mtime2 = os.stat(pycpath).st_mtime
346 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000347
R. David Murray95333e32010-12-14 22:32:50 +0000348 def test_recursion_control(self):
349 subpackage = os.path.join(self.pkgdir, 'spam')
350 os.mkdir(subpackage)
351 subinitfn = script_helper.make_script(subpackage, '__init__', '')
352 hamfn = script_helper.make_script(subpackage, 'ham', '')
353 self.assertRunOK('-q', '-l', self.pkgdir)
354 self.assertNotCompiled(subinitfn)
355 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
356 self.assertRunOK('-q', self.pkgdir)
357 self.assertCompiled(subinitfn)
358 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000359
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500360 def test_recursion_limit(self):
361 subpackage = os.path.join(self.pkgdir, 'spam')
362 subpackage2 = os.path.join(subpackage, 'ham')
363 subpackage3 = os.path.join(subpackage2, 'eggs')
364 for pkg in (subpackage, subpackage2, subpackage3):
365 script_helper.make_pkg(pkg)
366
367 subinitfn = os.path.join(subpackage, '__init__.py')
368 hamfn = script_helper.make_script(subpackage, 'ham', '')
369 spamfn = script_helper.make_script(subpackage2, 'spam', '')
370 eggfn = script_helper.make_script(subpackage3, 'egg', '')
371
372 self.assertRunOK('-q', '-r 0', self.pkgdir)
373 self.assertNotCompiled(subinitfn)
374 self.assertFalse(
375 os.path.exists(os.path.join(subpackage, '__pycache__')))
376
377 self.assertRunOK('-q', '-r 1', self.pkgdir)
378 self.assertCompiled(subinitfn)
379 self.assertCompiled(hamfn)
380 self.assertNotCompiled(spamfn)
381
382 self.assertRunOK('-q', '-r 2', self.pkgdir)
383 self.assertCompiled(subinitfn)
384 self.assertCompiled(hamfn)
385 self.assertCompiled(spamfn)
386 self.assertNotCompiled(eggfn)
387
388 self.assertRunOK('-q', '-r 5', self.pkgdir)
389 self.assertCompiled(subinitfn)
390 self.assertCompiled(hamfn)
391 self.assertCompiled(spamfn)
392 self.assertCompiled(eggfn)
393
R. David Murray650f1472010-11-20 21:18:51 +0000394 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000395 noisy = self.assertRunOK(self.pkgdir)
396 quiet = self.assertRunOK('-q', self.pkgdir)
397 self.assertNotEqual(b'', noisy)
398 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000399
Berker Peksag6554b862014-10-15 11:10:57 +0300400 def test_silent(self):
401 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
402 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
403 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
404 self.assertNotEqual(b'', quiet)
405 self.assertEqual(b'', silent)
406
R. David Murray650f1472010-11-20 21:18:51 +0000407 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400408 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000409 self.assertNotCompiled(self.barfn)
410 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000411
R. David Murray95333e32010-12-14 22:32:50 +0000412 def test_multiple_dirs(self):
413 pkgdir2 = os.path.join(self.directory, 'foo2')
414 os.mkdir(pkgdir2)
415 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
416 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
417 self.assertRunOK('-q', self.pkgdir, pkgdir2)
418 self.assertCompiled(self.initfn)
419 self.assertCompiled(self.barfn)
420 self.assertCompiled(init2fn)
421 self.assertCompiled(bar2fn)
422
R. David Murray95333e32010-12-14 22:32:50 +0000423 def test_d_compile_error(self):
424 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
425 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
426 self.assertRegex(out, b'File "dinsdale')
427
428 def test_d_runtime_error(self):
429 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
430 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
431 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400432 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000433 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
434 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200435 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000436 self.assertRegex(err, b'File "dinsdale')
437
438 def test_include_bad_file(self):
439 rc, out, err = self.assertRunNotOK(
440 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
441 self.assertRegex(out, b'rror.*nosuchfile')
442 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400443 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000444 self.pkgdir_cachedir)))
445
446 def test_include_file_with_arg(self):
447 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
448 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
449 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
450 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
451 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
452 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
453 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
454 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
455 self.assertCompiled(f1)
456 self.assertCompiled(f2)
457 self.assertNotCompiled(f3)
458 self.assertCompiled(f4)
459
460 def test_include_file_no_arg(self):
461 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
462 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
463 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
464 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
465 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
466 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
467 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
468 self.assertNotCompiled(f1)
469 self.assertCompiled(f2)
470 self.assertNotCompiled(f3)
471 self.assertNotCompiled(f4)
472
473 def test_include_on_stdin(self):
474 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
475 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
476 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
477 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400478 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000479 p.stdin.write((f3+os.linesep).encode('ascii'))
480 script_helper.kill_python(p)
481 self.assertNotCompiled(f1)
482 self.assertNotCompiled(f2)
483 self.assertCompiled(f3)
484 self.assertNotCompiled(f4)
485
486 def test_compiles_as_much_as_possible(self):
487 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
488 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
489 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000490 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000491 self.assertNotCompiled(bingfn)
492 self.assertCompiled(self.initfn)
493 self.assertCompiled(self.barfn)
494
R. David Murray5317e9c2010-12-16 19:08:51 +0000495 def test_invalid_arg_produces_message(self):
496 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200497 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000498
Brett Cannonf1a8df02014-09-12 10:39:48 -0400499 @skipUnless(_have_multiprocessing, "requires multiprocessing")
500 def test_workers(self):
501 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
502 files = []
503 for suffix in range(5):
504 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
505 os.mkdir(pkgdir)
506 fn = script_helper.make_script(pkgdir, '__init__', '')
507 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
508
509 self.assertRunOK(self.directory, '-j', '0')
510 self.assertCompiled(bar2fn)
511 for file in files:
512 self.assertCompiled(file)
513
514 @mock.patch('compileall.compile_dir')
515 def test_workers_available_cores(self, compile_dir):
516 with mock.patch("sys.argv",
517 new=[sys.executable, self.directory, "-j0"]):
518 compileall.main()
519 self.assertTrue(compile_dir.called)
520 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
521
Barry Warsaw28a691b2010-04-17 00:19:56 +0000522
Brett Cannonbefb14f2009-02-10 02:10:16 +0000523if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400524 unittest.main()