blob: 7506c7018bfc9d3b65fd537471b05b03b03b67ba [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
104 optimize = 1 if __debug__ else 0
105 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,
107 debug_override=not optimize)
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,
110 debug_override=not optimize)
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,
113 debug_override=not optimize)
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
240 # PEP 3147 pyc/pyo files.
241 for name, ext, switch in [
242 ('normal', 'pyc', []),
243 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000244 ('doubleoptimize', 'pyo', ['-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
261 # pyc/pyo 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))
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400265 opt = 'c' if __debug__ else 'o'
266 expected = sorted(['__init__.py', '__init__.py' + opt, 'bar.py',
267 'bar.py' + opt])
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()