blob: 9479776abf7e8f8a072c5abc62c2371aaca6f837 [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 Cannonbefb14f2009-02-10 02:10:16 +00004import os
5import py_compile
6import shutil
7import struct
Brett Cannonbefb14f2009-02-10 02:10:16 +00008import tempfile
R. David Murray650f1472010-11-20 21:18:51 +00009import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000010import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000011import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000012
Brett Cannonf1a8df02014-09-12 10:39:48 -040013from unittest import mock, skipUnless
14try:
15 from concurrent.futures import ProcessPoolExecutor
16 _have_multiprocessing = True
17except ImportError:
18 _have_multiprocessing = False
19
Berker Peksagce643912015-05-06 06:33:17 +030020from test import support
21from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000022
23class CompileallTests(unittest.TestCase):
24
25 def setUp(self):
26 self.directory = tempfile.mkdtemp()
27 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040028 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000029 with open(self.source_path, 'w') as file:
30 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000031 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040032 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000033 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000034 self.subdirectory = os.path.join(self.directory, '_subdir')
35 os.mkdir(self.subdirectory)
36 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
37 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000038
39 def tearDown(self):
40 shutil.rmtree(self.directory)
41
42 def data(self):
43 with open(self.bc_path, 'rb') as file:
44 data = file.read(8)
45 mtime = int(os.stat(self.source_path).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -040046 compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000047 return data, compare
48
Serhiy Storchaka43767632013-11-03 21:31:38 +020049 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000050 def recreation_check(self, metadata):
51 """Check that compileall recreates bytecode when the new metadata is
52 used."""
Brett Cannonbefb14f2009-02-10 02:10:16 +000053 py_compile.compile(self.source_path)
54 self.assertEqual(*self.data())
55 with open(self.bc_path, 'rb') as file:
56 bc = file.read()[len(metadata):]
57 with open(self.bc_path, 'wb') as file:
58 file.write(metadata)
59 file.write(bc)
60 self.assertNotEqual(*self.data())
61 compileall.compile_dir(self.directory, force=False, quiet=True)
62 self.assertTrue(*self.data())
63
64 def test_mtime(self):
65 # Test a change in mtime leads to a new .pyc.
Brett Cannon7822e122013-06-14 23:04:02 -040066 self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
67 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000068
69 def test_magic_number(self):
70 # Test a change in mtime leads to a new .pyc.
71 self.recreation_check(b'\0\0\0\0')
72
Matthias Klosec33b9022010-03-16 00:36:26 +000073 def test_compile_files(self):
74 # Test compiling a single file, and complete directory
75 for fn in (self.bc_path, self.bc_path2):
76 try:
77 os.unlink(fn)
78 except:
79 pass
80 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000081 self.assertTrue(os.path.isfile(self.bc_path) and
82 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000083 os.unlink(self.bc_path)
84 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000085 self.assertTrue(os.path.isfile(self.bc_path) and
86 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000087 os.unlink(self.bc_path)
88 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000089
Barry Warsawc8a99de2010-04-29 18:43:10 +000090 def test_no_pycache_in_non_package(self):
91 # Bug 8563 reported that __pycache__ directories got created by
92 # compile_file() for non-.py files.
93 data_dir = os.path.join(self.directory, 'data')
94 data_file = os.path.join(data_dir, 'file')
95 os.mkdir(data_dir)
96 # touch data/file
97 with open(data_file, 'w'):
98 pass
99 compileall.compile_file(data_file)
100 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
101
Georg Brandl8334fd92010-12-04 10:26:46 +0000102 def test_optimize(self):
103 # make sure compiling with different optimization settings than the
104 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400105 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000106 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400107 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400108 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000109 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400110 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400111 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000112 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400113 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400114 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000115 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000116
Brett Cannonf1a8df02014-09-12 10:39:48 -0400117 @mock.patch('compileall.ProcessPoolExecutor')
118 def test_compile_pool_called(self, pool_mock):
119 compileall.compile_dir(self.directory, quiet=True, workers=5)
120 self.assertTrue(pool_mock.called)
121
122 def test_compile_workers_non_positive(self):
123 with self.assertRaisesRegex(ValueError,
124 "workers must be greater or equal to 0"):
125 compileall.compile_dir(self.directory, workers=-1)
126
127 @mock.patch('compileall.ProcessPoolExecutor')
128 def test_compile_workers_cpu_count(self, pool_mock):
129 compileall.compile_dir(self.directory, quiet=True, workers=0)
130 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
131
132 @mock.patch('compileall.ProcessPoolExecutor')
133 @mock.patch('compileall.compile_file')
134 def test_compile_one_worker(self, compile_file_mock, pool_mock):
135 compileall.compile_dir(self.directory, quiet=True)
136 self.assertFalse(pool_mock.called)
137 self.assertTrue(compile_file_mock.called)
138
139 @mock.patch('compileall.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300140 @mock.patch('compileall.compile_file')
141 def test_compile_missing_multiprocessing(self, compile_file_mock):
142 compileall.compile_dir(self.directory, quiet=True, workers=5)
143 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000144
Martin v. Löwis4b003072010-03-16 13:19:21 +0000145class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000146 """Issue 6716: compileall should escape source code when printing errors
147 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000148
149 def setUp(self):
150 self.directory = tempfile.mkdtemp()
151 self.source_path = os.path.join(self.directory, '_test.py')
152 with open(self.source_path, 'w', encoding='utf-8') as file:
153 file.write('# -*- coding: utf-8 -*-\n')
154 file.write('print u"\u20ac"\n')
155
156 def tearDown(self):
157 shutil.rmtree(self.directory)
158
159 def test_error(self):
160 try:
161 orig_stdout = sys.stdout
162 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
163 compileall.compile_dir(self.directory)
164 finally:
165 sys.stdout = orig_stdout
166
Barry Warsawc8a99de2010-04-29 18:43:10 +0000167
Barry Warsaw28a691b2010-04-17 00:19:56 +0000168class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000169 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000170
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400171 def _get_run_args(self, args):
172 interp_args = ['-S']
173 if sys.flags.optimize:
174 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
175 return interp_args + ['-m', 'compileall'] + list(args)
176
R. David Murray5317e9c2010-12-16 19:08:51 +0000177 def assertRunOK(self, *args, **env_vars):
178 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400179 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000180 self.assertEqual(b'', err)
181 return out
182
R. David Murray5317e9c2010-12-16 19:08:51 +0000183 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000184 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400185 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000186 return rc, out, err
187
188 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400189 path = importlib.util.cache_from_source(fn)
190 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000191
192 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400193 path = importlib.util.cache_from_source(fn)
194 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000195
Barry Warsaw28a691b2010-04-17 00:19:56 +0000196 def setUp(self):
197 self.addCleanup(self._cleanup)
198 self.directory = tempfile.mkdtemp()
199 self.pkgdir = os.path.join(self.directory, 'foo')
200 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000201 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
202 # Create the __init__.py and a package module.
203 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
204 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000205
206 def _cleanup(self):
207 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000208
209 def test_no_args_compiles_path(self):
210 # Note that -l is implied for the no args case.
211 bazfn = script_helper.make_script(self.directory, 'baz', '')
212 self.assertRunOK(PYTHONPATH=self.directory)
213 self.assertCompiled(bazfn)
214 self.assertNotCompiled(self.initfn)
215 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000216
R David Murray8a1d1e62013-12-15 20:49:38 -0500217 def test_no_args_respects_force_flag(self):
218 bazfn = script_helper.make_script(self.directory, 'baz', '')
219 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500220 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500221 # Set atime/mtime backward to avoid file timestamp resolution issues
222 os.utime(pycpath, (time.time()-60,)*2)
223 mtime = os.stat(pycpath).st_mtime
224 # Without force, no recompilation
225 self.assertRunOK(PYTHONPATH=self.directory)
226 mtime2 = os.stat(pycpath).st_mtime
227 self.assertEqual(mtime, mtime2)
228 # Now force it.
229 self.assertRunOK('-f', PYTHONPATH=self.directory)
230 mtime2 = os.stat(pycpath).st_mtime
231 self.assertNotEqual(mtime, mtime2)
232
233 def test_no_args_respects_quiet_flag(self):
234 script_helper.make_script(self.directory, 'baz', '')
235 noisy = self.assertRunOK(PYTHONPATH=self.directory)
236 self.assertIn(b'Listing ', noisy)
237 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
238 self.assertNotIn(b'Listing ', quiet)
239
Georg Brandl1463a3f2010-10-14 07:42:27 +0000240 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400241 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000242 for name, ext, switch in [
243 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400244 ('optimize', 'opt-1.pyc', ['-O']),
245 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000246 ]:
247 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000248 script_helper.assert_python_ok(*(switch +
249 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000250 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000251 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400252 expected = sorted(base.format(sys.implementation.cache_tag, ext)
253 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000254 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000255 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000256 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
257 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000258 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000259
260 def test_legacy_paths(self):
261 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400262 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000263 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000264 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000265 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400266 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
267 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000268 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
269
Barry Warsawc04317f2010-04-26 15:59:03 +0000270 def test_multiple_runs(self):
271 # Bug 8527 reported that multiple calls produced empty
272 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000273 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000274 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000275 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
276 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000277 self.assertFalse(os.path.exists(cachecachedir))
278 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000279 self.assertRunOK('-q', self.pkgdir)
280 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000281 self.assertFalse(os.path.exists(cachecachedir))
282
R. David Murray650f1472010-11-20 21:18:51 +0000283 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000284 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400285 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000286 # set atime/mtime backward to avoid file timestamp resolution issues
287 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000288 mtime = os.stat(pycpath).st_mtime
289 # without force, no recompilation
290 self.assertRunOK('-q', self.pkgdir)
291 mtime2 = os.stat(pycpath).st_mtime
292 self.assertEqual(mtime, mtime2)
293 # now force it.
294 self.assertRunOK('-q', '-f', self.pkgdir)
295 mtime2 = os.stat(pycpath).st_mtime
296 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000297
R. David Murray95333e32010-12-14 22:32:50 +0000298 def test_recursion_control(self):
299 subpackage = os.path.join(self.pkgdir, 'spam')
300 os.mkdir(subpackage)
301 subinitfn = script_helper.make_script(subpackage, '__init__', '')
302 hamfn = script_helper.make_script(subpackage, 'ham', '')
303 self.assertRunOK('-q', '-l', self.pkgdir)
304 self.assertNotCompiled(subinitfn)
305 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
306 self.assertRunOK('-q', self.pkgdir)
307 self.assertCompiled(subinitfn)
308 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000309
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500310 def test_recursion_limit(self):
311 subpackage = os.path.join(self.pkgdir, 'spam')
312 subpackage2 = os.path.join(subpackage, 'ham')
313 subpackage3 = os.path.join(subpackage2, 'eggs')
314 for pkg in (subpackage, subpackage2, subpackage3):
315 script_helper.make_pkg(pkg)
316
317 subinitfn = os.path.join(subpackage, '__init__.py')
318 hamfn = script_helper.make_script(subpackage, 'ham', '')
319 spamfn = script_helper.make_script(subpackage2, 'spam', '')
320 eggfn = script_helper.make_script(subpackage3, 'egg', '')
321
322 self.assertRunOK('-q', '-r 0', self.pkgdir)
323 self.assertNotCompiled(subinitfn)
324 self.assertFalse(
325 os.path.exists(os.path.join(subpackage, '__pycache__')))
326
327 self.assertRunOK('-q', '-r 1', self.pkgdir)
328 self.assertCompiled(subinitfn)
329 self.assertCompiled(hamfn)
330 self.assertNotCompiled(spamfn)
331
332 self.assertRunOK('-q', '-r 2', self.pkgdir)
333 self.assertCompiled(subinitfn)
334 self.assertCompiled(hamfn)
335 self.assertCompiled(spamfn)
336 self.assertNotCompiled(eggfn)
337
338 self.assertRunOK('-q', '-r 5', self.pkgdir)
339 self.assertCompiled(subinitfn)
340 self.assertCompiled(hamfn)
341 self.assertCompiled(spamfn)
342 self.assertCompiled(eggfn)
343
R. David Murray650f1472010-11-20 21:18:51 +0000344 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000345 noisy = self.assertRunOK(self.pkgdir)
346 quiet = self.assertRunOK('-q', self.pkgdir)
347 self.assertNotEqual(b'', noisy)
348 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000349
Berker Peksag6554b862014-10-15 11:10:57 +0300350 def test_silent(self):
351 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
352 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
353 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
354 self.assertNotEqual(b'', quiet)
355 self.assertEqual(b'', silent)
356
R. David Murray650f1472010-11-20 21:18:51 +0000357 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400358 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000359 self.assertNotCompiled(self.barfn)
360 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000361
R. David Murray95333e32010-12-14 22:32:50 +0000362 def test_multiple_dirs(self):
363 pkgdir2 = os.path.join(self.directory, 'foo2')
364 os.mkdir(pkgdir2)
365 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
366 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
367 self.assertRunOK('-q', self.pkgdir, pkgdir2)
368 self.assertCompiled(self.initfn)
369 self.assertCompiled(self.barfn)
370 self.assertCompiled(init2fn)
371 self.assertCompiled(bar2fn)
372
373 def test_d_takes_exactly_one_dir(self):
374 rc, out, err = self.assertRunNotOK('-d', 'foo')
375 self.assertEqual(out, b'')
376 self.assertRegex(err, b'-d')
377 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
378 self.assertEqual(out, b'')
379 self.assertRegex(err, b'-d')
380
381 def test_d_compile_error(self):
382 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
383 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
384 self.assertRegex(out, b'File "dinsdale')
385
386 def test_d_runtime_error(self):
387 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
388 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
389 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400390 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000391 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
392 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200393 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000394 self.assertRegex(err, b'File "dinsdale')
395
396 def test_include_bad_file(self):
397 rc, out, err = self.assertRunNotOK(
398 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
399 self.assertRegex(out, b'rror.*nosuchfile')
400 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400401 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000402 self.pkgdir_cachedir)))
403
404 def test_include_file_with_arg(self):
405 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
406 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
407 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
408 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
409 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
410 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
411 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
412 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
413 self.assertCompiled(f1)
414 self.assertCompiled(f2)
415 self.assertNotCompiled(f3)
416 self.assertCompiled(f4)
417
418 def test_include_file_no_arg(self):
419 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
420 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
421 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
422 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
423 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
424 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
425 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
426 self.assertNotCompiled(f1)
427 self.assertCompiled(f2)
428 self.assertNotCompiled(f3)
429 self.assertNotCompiled(f4)
430
431 def test_include_on_stdin(self):
432 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
433 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
434 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
435 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400436 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000437 p.stdin.write((f3+os.linesep).encode('ascii'))
438 script_helper.kill_python(p)
439 self.assertNotCompiled(f1)
440 self.assertNotCompiled(f2)
441 self.assertCompiled(f3)
442 self.assertNotCompiled(f4)
443
444 def test_compiles_as_much_as_possible(self):
445 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
446 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
447 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000448 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000449 self.assertNotCompiled(bingfn)
450 self.assertCompiled(self.initfn)
451 self.assertCompiled(self.barfn)
452
R. David Murray5317e9c2010-12-16 19:08:51 +0000453 def test_invalid_arg_produces_message(self):
454 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200455 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000456
Brett Cannonf1a8df02014-09-12 10:39:48 -0400457 @skipUnless(_have_multiprocessing, "requires multiprocessing")
458 def test_workers(self):
459 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
460 files = []
461 for suffix in range(5):
462 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
463 os.mkdir(pkgdir)
464 fn = script_helper.make_script(pkgdir, '__init__', '')
465 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
466
467 self.assertRunOK(self.directory, '-j', '0')
468 self.assertCompiled(bar2fn)
469 for file in files:
470 self.assertCompiled(file)
471
472 @mock.patch('compileall.compile_dir')
473 def test_workers_available_cores(self, compile_dir):
474 with mock.patch("sys.argv",
475 new=[sys.executable, self.directory, "-j0"]):
476 compileall.main()
477 self.assertTrue(compile_dir.called)
478 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
479
Barry Warsaw28a691b2010-04-17 00:19:56 +0000480
Brett Cannonbefb14f2009-02-10 02:10:16 +0000481if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400482 unittest.main()