blob: 07756f6874717ff69be1f4820aab4372301ba302 [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
R. David Murray95333e32010-12-14 22:32:50 +000020from test import support, script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000021
22class CompileallTests(unittest.TestCase):
23
24 def setUp(self):
25 self.directory = tempfile.mkdtemp()
26 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040027 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000028 with open(self.source_path, 'w') as file:
29 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000030 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040031 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000032 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000033 self.subdirectory = os.path.join(self.directory, '_subdir')
34 os.mkdir(self.subdirectory)
35 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
36 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000037
38 def tearDown(self):
39 shutil.rmtree(self.directory)
40
41 def data(self):
42 with open(self.bc_path, 'rb') as file:
43 data = file.read(8)
44 mtime = int(os.stat(self.source_path).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -040045 compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000046 return data, compare
47
Serhiy Storchaka43767632013-11-03 21:31:38 +020048 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000049 def recreation_check(self, metadata):
50 """Check that compileall recreates bytecode when the new metadata is
51 used."""
Brett Cannonbefb14f2009-02-10 02:10:16 +000052 py_compile.compile(self.source_path)
53 self.assertEqual(*self.data())
54 with open(self.bc_path, 'rb') as file:
55 bc = file.read()[len(metadata):]
56 with open(self.bc_path, 'wb') as file:
57 file.write(metadata)
58 file.write(bc)
59 self.assertNotEqual(*self.data())
60 compileall.compile_dir(self.directory, force=False, quiet=True)
61 self.assertTrue(*self.data())
62
63 def test_mtime(self):
64 # Test a change in mtime leads to a new .pyc.
Brett Cannon7822e122013-06-14 23:04:02 -040065 self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
66 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000067
68 def test_magic_number(self):
69 # Test a change in mtime leads to a new .pyc.
70 self.recreation_check(b'\0\0\0\0')
71
Matthias Klosec33b9022010-03-16 00:36:26 +000072 def test_compile_files(self):
73 # Test compiling a single file, and complete directory
74 for fn in (self.bc_path, self.bc_path2):
75 try:
76 os.unlink(fn)
77 except:
78 pass
79 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000080 self.assertTrue(os.path.isfile(self.bc_path) and
81 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000082 os.unlink(self.bc_path)
83 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000084 self.assertTrue(os.path.isfile(self.bc_path) and
85 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000086 os.unlink(self.bc_path)
87 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000088
Barry Warsawc8a99de2010-04-29 18:43:10 +000089 def test_no_pycache_in_non_package(self):
90 # Bug 8563 reported that __pycache__ directories got created by
91 # compile_file() for non-.py files.
92 data_dir = os.path.join(self.directory, 'data')
93 data_file = os.path.join(data_dir, 'file')
94 os.mkdir(data_dir)
95 # touch data/file
96 with open(data_file, 'w'):
97 pass
98 compileall.compile_file(data_file)
99 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
100
Georg Brandl8334fd92010-12-04 10:26:46 +0000101 def test_optimize(self):
102 # make sure compiling with different optimization settings than the
103 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400104 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000105 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400106 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400107 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000108 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400109 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400110 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000111 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400112 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400113 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000114 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000115
Brett Cannonf1a8df02014-09-12 10:39:48 -0400116 @mock.patch('compileall.ProcessPoolExecutor')
117 def test_compile_pool_called(self, pool_mock):
118 compileall.compile_dir(self.directory, quiet=True, workers=5)
119 self.assertTrue(pool_mock.called)
120
121 def test_compile_workers_non_positive(self):
122 with self.assertRaisesRegex(ValueError,
123 "workers must be greater or equal to 0"):
124 compileall.compile_dir(self.directory, workers=-1)
125
126 @mock.patch('compileall.ProcessPoolExecutor')
127 def test_compile_workers_cpu_count(self, pool_mock):
128 compileall.compile_dir(self.directory, quiet=True, workers=0)
129 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
130
131 @mock.patch('compileall.ProcessPoolExecutor')
132 @mock.patch('compileall.compile_file')
133 def test_compile_one_worker(self, compile_file_mock, pool_mock):
134 compileall.compile_dir(self.directory, quiet=True)
135 self.assertFalse(pool_mock.called)
136 self.assertTrue(compile_file_mock.called)
137
138 @mock.patch('compileall.ProcessPoolExecutor', new=None)
139 def test_compile_missing_multiprocessing(self):
140 with self.assertRaisesRegex(NotImplementedError,
141 "multiprocessing support not available"):
142 compileall.compile_dir(self.directory, quiet=True, workers=5)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000143
Martin v. Löwis4b003072010-03-16 13:19:21 +0000144class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000145 """Issue 6716: compileall should escape source code when printing errors
146 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000147
148 def setUp(self):
149 self.directory = tempfile.mkdtemp()
150 self.source_path = os.path.join(self.directory, '_test.py')
151 with open(self.source_path, 'w', encoding='utf-8') as file:
152 file.write('# -*- coding: utf-8 -*-\n')
153 file.write('print u"\u20ac"\n')
154
155 def tearDown(self):
156 shutil.rmtree(self.directory)
157
158 def test_error(self):
159 try:
160 orig_stdout = sys.stdout
161 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
162 compileall.compile_dir(self.directory)
163 finally:
164 sys.stdout = orig_stdout
165
Barry Warsawc8a99de2010-04-29 18:43:10 +0000166
Barry Warsaw28a691b2010-04-17 00:19:56 +0000167class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000168 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000169
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400170 def _get_run_args(self, args):
171 interp_args = ['-S']
172 if sys.flags.optimize:
173 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
174 return interp_args + ['-m', 'compileall'] + list(args)
175
R. David Murray5317e9c2010-12-16 19:08:51 +0000176 def assertRunOK(self, *args, **env_vars):
177 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400178 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000179 self.assertEqual(b'', err)
180 return out
181
R. David Murray5317e9c2010-12-16 19:08:51 +0000182 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000183 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400184 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000185 return rc, out, err
186
187 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400188 path = importlib.util.cache_from_source(fn)
189 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000190
191 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400192 path = importlib.util.cache_from_source(fn)
193 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000194
Barry Warsaw28a691b2010-04-17 00:19:56 +0000195 def setUp(self):
196 self.addCleanup(self._cleanup)
197 self.directory = tempfile.mkdtemp()
198 self.pkgdir = os.path.join(self.directory, 'foo')
199 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000200 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
201 # Create the __init__.py and a package module.
202 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
203 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000204
205 def _cleanup(self):
206 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000207
208 def test_no_args_compiles_path(self):
209 # Note that -l is implied for the no args case.
210 bazfn = script_helper.make_script(self.directory, 'baz', '')
211 self.assertRunOK(PYTHONPATH=self.directory)
212 self.assertCompiled(bazfn)
213 self.assertNotCompiled(self.initfn)
214 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000215
R David Murray8a1d1e62013-12-15 20:49:38 -0500216 def test_no_args_respects_force_flag(self):
217 bazfn = script_helper.make_script(self.directory, 'baz', '')
218 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500219 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500220 # Set atime/mtime backward to avoid file timestamp resolution issues
221 os.utime(pycpath, (time.time()-60,)*2)
222 mtime = os.stat(pycpath).st_mtime
223 # Without force, no recompilation
224 self.assertRunOK(PYTHONPATH=self.directory)
225 mtime2 = os.stat(pycpath).st_mtime
226 self.assertEqual(mtime, mtime2)
227 # Now force it.
228 self.assertRunOK('-f', PYTHONPATH=self.directory)
229 mtime2 = os.stat(pycpath).st_mtime
230 self.assertNotEqual(mtime, mtime2)
231
232 def test_no_args_respects_quiet_flag(self):
233 script_helper.make_script(self.directory, 'baz', '')
234 noisy = self.assertRunOK(PYTHONPATH=self.directory)
235 self.assertIn(b'Listing ', noisy)
236 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
237 self.assertNotIn(b'Listing ', quiet)
238
Georg Brandl1463a3f2010-10-14 07:42:27 +0000239 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400240 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000241 for name, ext, switch in [
242 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400243 ('optimize', 'opt-1.pyc', ['-O']),
244 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000245 ]:
246 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000247 script_helper.assert_python_ok(*(switch +
248 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000249 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000250 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400251 expected = sorted(base.format(sys.implementation.cache_tag, ext)
252 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000253 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000254 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000255 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
256 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000257 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000258
259 def test_legacy_paths(self):
260 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400261 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000262 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000263 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000264 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400265 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
266 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000267 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
268
Barry Warsawc04317f2010-04-26 15:59:03 +0000269 def test_multiple_runs(self):
270 # Bug 8527 reported that multiple calls produced empty
271 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000272 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000273 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000274 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
275 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000276 self.assertFalse(os.path.exists(cachecachedir))
277 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000278 self.assertRunOK('-q', self.pkgdir)
279 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000280 self.assertFalse(os.path.exists(cachecachedir))
281
R. David Murray650f1472010-11-20 21:18:51 +0000282 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000283 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400284 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000285 # set atime/mtime backward to avoid file timestamp resolution issues
286 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000287 mtime = os.stat(pycpath).st_mtime
288 # without force, no recompilation
289 self.assertRunOK('-q', self.pkgdir)
290 mtime2 = os.stat(pycpath).st_mtime
291 self.assertEqual(mtime, mtime2)
292 # now force it.
293 self.assertRunOK('-q', '-f', self.pkgdir)
294 mtime2 = os.stat(pycpath).st_mtime
295 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000296
R. David Murray95333e32010-12-14 22:32:50 +0000297 def test_recursion_control(self):
298 subpackage = os.path.join(self.pkgdir, 'spam')
299 os.mkdir(subpackage)
300 subinitfn = script_helper.make_script(subpackage, '__init__', '')
301 hamfn = script_helper.make_script(subpackage, 'ham', '')
302 self.assertRunOK('-q', '-l', self.pkgdir)
303 self.assertNotCompiled(subinitfn)
304 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
305 self.assertRunOK('-q', self.pkgdir)
306 self.assertCompiled(subinitfn)
307 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000308
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500309 def test_recursion_limit(self):
310 subpackage = os.path.join(self.pkgdir, 'spam')
311 subpackage2 = os.path.join(subpackage, 'ham')
312 subpackage3 = os.path.join(subpackage2, 'eggs')
313 for pkg in (subpackage, subpackage2, subpackage3):
314 script_helper.make_pkg(pkg)
315
316 subinitfn = os.path.join(subpackage, '__init__.py')
317 hamfn = script_helper.make_script(subpackage, 'ham', '')
318 spamfn = script_helper.make_script(subpackage2, 'spam', '')
319 eggfn = script_helper.make_script(subpackage3, 'egg', '')
320
321 self.assertRunOK('-q', '-r 0', self.pkgdir)
322 self.assertNotCompiled(subinitfn)
323 self.assertFalse(
324 os.path.exists(os.path.join(subpackage, '__pycache__')))
325
326 self.assertRunOK('-q', '-r 1', self.pkgdir)
327 self.assertCompiled(subinitfn)
328 self.assertCompiled(hamfn)
329 self.assertNotCompiled(spamfn)
330
331 self.assertRunOK('-q', '-r 2', self.pkgdir)
332 self.assertCompiled(subinitfn)
333 self.assertCompiled(hamfn)
334 self.assertCompiled(spamfn)
335 self.assertNotCompiled(eggfn)
336
337 self.assertRunOK('-q', '-r 5', self.pkgdir)
338 self.assertCompiled(subinitfn)
339 self.assertCompiled(hamfn)
340 self.assertCompiled(spamfn)
341 self.assertCompiled(eggfn)
342
R. David Murray650f1472010-11-20 21:18:51 +0000343 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000344 noisy = self.assertRunOK(self.pkgdir)
345 quiet = self.assertRunOK('-q', self.pkgdir)
346 self.assertNotEqual(b'', noisy)
347 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000348
Berker Peksag6554b862014-10-15 11:10:57 +0300349 def test_silent(self):
350 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
351 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
352 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
353 self.assertNotEqual(b'', quiet)
354 self.assertEqual(b'', silent)
355
R. David Murray650f1472010-11-20 21:18:51 +0000356 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400357 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000358 self.assertNotCompiled(self.barfn)
359 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000360
R. David Murray95333e32010-12-14 22:32:50 +0000361 def test_multiple_dirs(self):
362 pkgdir2 = os.path.join(self.directory, 'foo2')
363 os.mkdir(pkgdir2)
364 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
365 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
366 self.assertRunOK('-q', self.pkgdir, pkgdir2)
367 self.assertCompiled(self.initfn)
368 self.assertCompiled(self.barfn)
369 self.assertCompiled(init2fn)
370 self.assertCompiled(bar2fn)
371
372 def test_d_takes_exactly_one_dir(self):
373 rc, out, err = self.assertRunNotOK('-d', 'foo')
374 self.assertEqual(out, b'')
375 self.assertRegex(err, b'-d')
376 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
377 self.assertEqual(out, b'')
378 self.assertRegex(err, b'-d')
379
380 def test_d_compile_error(self):
381 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
382 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
383 self.assertRegex(out, b'File "dinsdale')
384
385 def test_d_runtime_error(self):
386 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
387 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
388 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400389 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000390 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
391 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200392 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000393 self.assertRegex(err, b'File "dinsdale')
394
395 def test_include_bad_file(self):
396 rc, out, err = self.assertRunNotOK(
397 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
398 self.assertRegex(out, b'rror.*nosuchfile')
399 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400400 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000401 self.pkgdir_cachedir)))
402
403 def test_include_file_with_arg(self):
404 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
405 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
406 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
407 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
408 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
409 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
410 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
411 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
412 self.assertCompiled(f1)
413 self.assertCompiled(f2)
414 self.assertNotCompiled(f3)
415 self.assertCompiled(f4)
416
417 def test_include_file_no_arg(self):
418 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
419 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
420 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
421 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
422 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
423 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
424 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
425 self.assertNotCompiled(f1)
426 self.assertCompiled(f2)
427 self.assertNotCompiled(f3)
428 self.assertNotCompiled(f4)
429
430 def test_include_on_stdin(self):
431 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
432 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
433 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
434 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400435 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000436 p.stdin.write((f3+os.linesep).encode('ascii'))
437 script_helper.kill_python(p)
438 self.assertNotCompiled(f1)
439 self.assertNotCompiled(f2)
440 self.assertCompiled(f3)
441 self.assertNotCompiled(f4)
442
443 def test_compiles_as_much_as_possible(self):
444 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
445 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
446 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000447 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000448 self.assertNotCompiled(bingfn)
449 self.assertCompiled(self.initfn)
450 self.assertCompiled(self.barfn)
451
R. David Murray5317e9c2010-12-16 19:08:51 +0000452 def test_invalid_arg_produces_message(self):
453 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200454 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000455
Brett Cannonf1a8df02014-09-12 10:39:48 -0400456 @skipUnless(_have_multiprocessing, "requires multiprocessing")
457 def test_workers(self):
458 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
459 files = []
460 for suffix in range(5):
461 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
462 os.mkdir(pkgdir)
463 fn = script_helper.make_script(pkgdir, '__init__', '')
464 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
465
466 self.assertRunOK(self.directory, '-j', '0')
467 self.assertCompiled(bar2fn)
468 for file in files:
469 self.assertCompiled(file)
470
471 @mock.patch('compileall.compile_dir')
472 def test_workers_available_cores(self, compile_dir):
473 with mock.patch("sys.argv",
474 new=[sys.executable, self.directory, "-j0"]):
475 compileall.main()
476 self.assertTrue(compile_dir.called)
477 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
478
Barry Warsaw28a691b2010-04-17 00:19:56 +0000479
Brett Cannonbefb14f2009-02-10 02:10:16 +0000480if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400481 unittest.main()