blob: ef2b669356823685d35768cbf816f64338b57113 [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
Brett Cannon65ed7502015-10-09 15:09:43 -07005import pathlib
Brett Cannonbefb14f2009-02-10 02:10:16 +00006import py_compile
7import shutil
8import struct
Brett Cannonbefb14f2009-02-10 02:10:16 +00009import tempfile
R. David Murray650f1472010-11-20 21:18:51 +000010import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000011import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000012import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000013
Brett Cannonf1a8df02014-09-12 10:39:48 -040014from unittest import mock, skipUnless
15try:
16 from concurrent.futures import ProcessPoolExecutor
17 _have_multiprocessing = True
18except ImportError:
19 _have_multiprocessing = False
20
Berker Peksagce643912015-05-06 06:33:17 +030021from test import support
22from test.support import script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000023
24class CompileallTests(unittest.TestCase):
25
26 def setUp(self):
27 self.directory = tempfile.mkdtemp()
28 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040029 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000030 with open(self.source_path, 'w') as file:
31 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000032 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040033 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000034 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000035 self.subdirectory = os.path.join(self.directory, '_subdir')
36 os.mkdir(self.subdirectory)
37 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
38 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000039
40 def tearDown(self):
41 shutil.rmtree(self.directory)
42
43 def data(self):
44 with open(self.bc_path, 'rb') as file:
45 data = file.read(8)
46 mtime = int(os.stat(self.source_path).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -040047 compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000048 return data, compare
49
Serhiy Storchaka43767632013-11-03 21:31:38 +020050 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000051 def recreation_check(self, metadata):
52 """Check that compileall recreates bytecode when the new metadata is
53 used."""
Brett Cannonbefb14f2009-02-10 02:10:16 +000054 py_compile.compile(self.source_path)
55 self.assertEqual(*self.data())
56 with open(self.bc_path, 'rb') as file:
57 bc = file.read()[len(metadata):]
58 with open(self.bc_path, 'wb') as file:
59 file.write(metadata)
60 file.write(bc)
61 self.assertNotEqual(*self.data())
62 compileall.compile_dir(self.directory, force=False, quiet=True)
63 self.assertTrue(*self.data())
64
65 def test_mtime(self):
66 # Test a change in mtime leads to a new .pyc.
Brett Cannon7822e122013-06-14 23:04:02 -040067 self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
68 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000069
70 def test_magic_number(self):
71 # Test a change in mtime leads to a new .pyc.
72 self.recreation_check(b'\0\0\0\0')
73
Matthias Klosec33b9022010-03-16 00:36:26 +000074 def test_compile_files(self):
75 # Test compiling a single file, and complete directory
76 for fn in (self.bc_path, self.bc_path2):
77 try:
78 os.unlink(fn)
79 except:
80 pass
81 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000082 self.assertTrue(os.path.isfile(self.bc_path) and
83 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000084 os.unlink(self.bc_path)
85 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000086 self.assertTrue(os.path.isfile(self.bc_path) and
87 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000088 os.unlink(self.bc_path)
89 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000090
Barry Warsawc8a99de2010-04-29 18:43:10 +000091 def test_no_pycache_in_non_package(self):
92 # Bug 8563 reported that __pycache__ directories got created by
93 # compile_file() for non-.py files.
94 data_dir = os.path.join(self.directory, 'data')
95 data_file = os.path.join(data_dir, 'file')
96 os.mkdir(data_dir)
97 # touch data/file
98 with open(data_file, 'w'):
99 pass
100 compileall.compile_file(data_file)
101 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
102
Georg Brandl8334fd92010-12-04 10:26:46 +0000103 def test_optimize(self):
104 # make sure compiling with different optimization settings than the
105 # interpreter's creates the correct file names
Brett Cannonf299abd2015-04-13 14:21:02 -0400106 optimize, opt = (1, 1) if __debug__ else (0, '')
Georg Brandl8334fd92010-12-04 10:26:46 +0000107 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400108 cached = importlib.util.cache_from_source(self.source_path,
Brett Cannonf299abd2015-04-13 14:21:02 -0400109 optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000110 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400111 cached2 = importlib.util.cache_from_source(self.source_path2,
Brett Cannonf299abd2015-04-13 14:21:02 -0400112 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000113 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400114 cached3 = importlib.util.cache_from_source(self.source_path3,
Brett Cannonf299abd2015-04-13 14:21:02 -0400115 optimization=opt)
Georg Brandl45438462011-02-07 12:36:54 +0000116 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000117
Brett Cannonf1a8df02014-09-12 10:39:48 -0400118 @mock.patch('compileall.ProcessPoolExecutor')
119 def test_compile_pool_called(self, pool_mock):
120 compileall.compile_dir(self.directory, quiet=True, workers=5)
121 self.assertTrue(pool_mock.called)
122
123 def test_compile_workers_non_positive(self):
124 with self.assertRaisesRegex(ValueError,
125 "workers must be greater or equal to 0"):
126 compileall.compile_dir(self.directory, workers=-1)
127
128 @mock.patch('compileall.ProcessPoolExecutor')
129 def test_compile_workers_cpu_count(self, pool_mock):
130 compileall.compile_dir(self.directory, quiet=True, workers=0)
131 self.assertEqual(pool_mock.call_args[1]['max_workers'], None)
132
133 @mock.patch('compileall.ProcessPoolExecutor')
134 @mock.patch('compileall.compile_file')
135 def test_compile_one_worker(self, compile_file_mock, pool_mock):
136 compileall.compile_dir(self.directory, quiet=True)
137 self.assertFalse(pool_mock.called)
138 self.assertTrue(compile_file_mock.called)
139
140 @mock.patch('compileall.ProcessPoolExecutor', new=None)
Berker Peksagd86ef052015-04-22 09:39:19 +0300141 @mock.patch('compileall.compile_file')
142 def test_compile_missing_multiprocessing(self, compile_file_mock):
143 compileall.compile_dir(self.directory, quiet=True, workers=5)
144 self.assertTrue(compile_file_mock.called)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000145
Martin v. Löwis4b003072010-03-16 13:19:21 +0000146class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000147 """Issue 6716: compileall should escape source code when printing errors
148 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000149
150 def setUp(self):
151 self.directory = tempfile.mkdtemp()
152 self.source_path = os.path.join(self.directory, '_test.py')
153 with open(self.source_path, 'w', encoding='utf-8') as file:
154 file.write('# -*- coding: utf-8 -*-\n')
155 file.write('print u"\u20ac"\n')
156
157 def tearDown(self):
158 shutil.rmtree(self.directory)
159
160 def test_error(self):
161 try:
162 orig_stdout = sys.stdout
163 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
164 compileall.compile_dir(self.directory)
165 finally:
166 sys.stdout = orig_stdout
167
Barry Warsawc8a99de2010-04-29 18:43:10 +0000168
Barry Warsaw28a691b2010-04-17 00:19:56 +0000169class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000170 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000171
Brett Cannon65ed7502015-10-09 15:09:43 -0700172 @classmethod
173 def setUpClass(cls):
174 for path in filter(os.path.isdir, sys.path):
175 directory_created = False
176 directory = pathlib.Path(path) / '__pycache__'
177 path = directory / 'test.try'
178 try:
179 if not directory.is_dir():
180 directory.mkdir()
181 directory_created = True
182 with path.open('w') as file:
183 file.write('# for test_compileall')
184 except OSError:
185 sys_path_writable = False
186 break
187 finally:
188 support.unlink(str(path))
189 if directory_created:
190 directory.rmdir()
191 else:
192 sys_path_writable = True
193 cls._sys_path_writable = sys_path_writable
194
195 def _skip_if_sys_path_not_writable(self):
196 if not self._sys_path_writable:
197 raise unittest.SkipTest('not all entries on sys.path are writable')
198
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400199 def _get_run_args(self, args):
200 interp_args = ['-S']
201 if sys.flags.optimize:
202 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
203 return interp_args + ['-m', 'compileall'] + list(args)
204
R. David Murray5317e9c2010-12-16 19:08:51 +0000205 def assertRunOK(self, *args, **env_vars):
206 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400207 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000208 self.assertEqual(b'', err)
209 return out
210
R. David Murray5317e9c2010-12-16 19:08:51 +0000211 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000212 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400213 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000214 return rc, out, err
215
216 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400217 path = importlib.util.cache_from_source(fn)
218 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000219
220 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400221 path = importlib.util.cache_from_source(fn)
222 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000223
Barry Warsaw28a691b2010-04-17 00:19:56 +0000224 def setUp(self):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000225 self.directory = tempfile.mkdtemp()
Brett Cannon65ed7502015-10-09 15:09:43 -0700226 self.addCleanup(support.rmtree, self.directory)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000227 self.pkgdir = os.path.join(self.directory, 'foo')
228 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000229 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
230 # Create the __init__.py and a package module.
231 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
232 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000233
R. David Murray5317e9c2010-12-16 19:08:51 +0000234 def test_no_args_compiles_path(self):
235 # Note that -l is implied for the no args case.
Brett Cannon65ed7502015-10-09 15:09:43 -0700236 self._skip_if_sys_path_not_writable()
R. David Murray5317e9c2010-12-16 19:08:51 +0000237 bazfn = script_helper.make_script(self.directory, 'baz', '')
238 self.assertRunOK(PYTHONPATH=self.directory)
239 self.assertCompiled(bazfn)
240 self.assertNotCompiled(self.initfn)
241 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000242
R David Murray8a1d1e62013-12-15 20:49:38 -0500243 def test_no_args_respects_force_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700244 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500245 bazfn = script_helper.make_script(self.directory, 'baz', '')
246 self.assertRunOK(PYTHONPATH=self.directory)
R David Murray755d5ea2013-12-15 20:56:00 -0500247 pycpath = importlib.util.cache_from_source(bazfn)
R David Murray8a1d1e62013-12-15 20:49:38 -0500248 # Set atime/mtime backward to avoid file timestamp resolution issues
249 os.utime(pycpath, (time.time()-60,)*2)
250 mtime = os.stat(pycpath).st_mtime
251 # Without force, no recompilation
252 self.assertRunOK(PYTHONPATH=self.directory)
253 mtime2 = os.stat(pycpath).st_mtime
254 self.assertEqual(mtime, mtime2)
255 # Now force it.
256 self.assertRunOK('-f', PYTHONPATH=self.directory)
257 mtime2 = os.stat(pycpath).st_mtime
258 self.assertNotEqual(mtime, mtime2)
259
260 def test_no_args_respects_quiet_flag(self):
Brett Cannon65ed7502015-10-09 15:09:43 -0700261 self._skip_if_sys_path_not_writable()
R David Murray8a1d1e62013-12-15 20:49:38 -0500262 script_helper.make_script(self.directory, 'baz', '')
263 noisy = self.assertRunOK(PYTHONPATH=self.directory)
264 self.assertIn(b'Listing ', noisy)
265 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
266 self.assertNotIn(b'Listing ', quiet)
267
Georg Brandl1463a3f2010-10-14 07:42:27 +0000268 # Ensure that the default behavior of compileall's CLI is to create
Brett Cannonf299abd2015-04-13 14:21:02 -0400269 # PEP 3147/PEP 488 pyc files.
Georg Brandl1463a3f2010-10-14 07:42:27 +0000270 for name, ext, switch in [
271 ('normal', 'pyc', []),
Brett Cannonf299abd2015-04-13 14:21:02 -0400272 ('optimize', 'opt-1.pyc', ['-O']),
273 ('doubleoptimize', 'opt-2.pyc', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000274 ]:
275 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000276 script_helper.assert_python_ok(*(switch +
277 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000278 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000279 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400280 expected = sorted(base.format(sys.implementation.cache_tag, ext)
281 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000282 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000283 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000284 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
285 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000286 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000287
288 def test_legacy_paths(self):
289 # Ensure that with the proper switch, compileall leaves legacy
Brett Cannonf299abd2015-04-13 14:21:02 -0400290 # pyc files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000291 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000292 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000293 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Brett Cannonf299abd2015-04-13 14:21:02 -0400294 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',
295 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000296 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
297
Barry Warsawc04317f2010-04-26 15:59:03 +0000298 def test_multiple_runs(self):
299 # Bug 8527 reported that multiple calls produced empty
300 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000301 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000302 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000303 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
304 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000305 self.assertFalse(os.path.exists(cachecachedir))
306 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000307 self.assertRunOK('-q', self.pkgdir)
308 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000309 self.assertFalse(os.path.exists(cachecachedir))
310
R. David Murray650f1472010-11-20 21:18:51 +0000311 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000312 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400313 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000314 # set atime/mtime backward to avoid file timestamp resolution issues
315 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000316 mtime = os.stat(pycpath).st_mtime
317 # without force, no recompilation
318 self.assertRunOK('-q', self.pkgdir)
319 mtime2 = os.stat(pycpath).st_mtime
320 self.assertEqual(mtime, mtime2)
321 # now force it.
322 self.assertRunOK('-q', '-f', self.pkgdir)
323 mtime2 = os.stat(pycpath).st_mtime
324 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000325
R. David Murray95333e32010-12-14 22:32:50 +0000326 def test_recursion_control(self):
327 subpackage = os.path.join(self.pkgdir, 'spam')
328 os.mkdir(subpackage)
329 subinitfn = script_helper.make_script(subpackage, '__init__', '')
330 hamfn = script_helper.make_script(subpackage, 'ham', '')
331 self.assertRunOK('-q', '-l', self.pkgdir)
332 self.assertNotCompiled(subinitfn)
333 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
334 self.assertRunOK('-q', self.pkgdir)
335 self.assertCompiled(subinitfn)
336 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000337
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500338 def test_recursion_limit(self):
339 subpackage = os.path.join(self.pkgdir, 'spam')
340 subpackage2 = os.path.join(subpackage, 'ham')
341 subpackage3 = os.path.join(subpackage2, 'eggs')
342 for pkg in (subpackage, subpackage2, subpackage3):
343 script_helper.make_pkg(pkg)
344
345 subinitfn = os.path.join(subpackage, '__init__.py')
346 hamfn = script_helper.make_script(subpackage, 'ham', '')
347 spamfn = script_helper.make_script(subpackage2, 'spam', '')
348 eggfn = script_helper.make_script(subpackage3, 'egg', '')
349
350 self.assertRunOK('-q', '-r 0', self.pkgdir)
351 self.assertNotCompiled(subinitfn)
352 self.assertFalse(
353 os.path.exists(os.path.join(subpackage, '__pycache__')))
354
355 self.assertRunOK('-q', '-r 1', self.pkgdir)
356 self.assertCompiled(subinitfn)
357 self.assertCompiled(hamfn)
358 self.assertNotCompiled(spamfn)
359
360 self.assertRunOK('-q', '-r 2', self.pkgdir)
361 self.assertCompiled(subinitfn)
362 self.assertCompiled(hamfn)
363 self.assertCompiled(spamfn)
364 self.assertNotCompiled(eggfn)
365
366 self.assertRunOK('-q', '-r 5', self.pkgdir)
367 self.assertCompiled(subinitfn)
368 self.assertCompiled(hamfn)
369 self.assertCompiled(spamfn)
370 self.assertCompiled(eggfn)
371
R. David Murray650f1472010-11-20 21:18:51 +0000372 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000373 noisy = self.assertRunOK(self.pkgdir)
374 quiet = self.assertRunOK('-q', self.pkgdir)
375 self.assertNotEqual(b'', noisy)
376 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000377
Berker Peksag6554b862014-10-15 11:10:57 +0300378 def test_silent(self):
379 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
380 _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)
381 _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)
382 self.assertNotEqual(b'', quiet)
383 self.assertEqual(b'', silent)
384
R. David Murray650f1472010-11-20 21:18:51 +0000385 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400386 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000387 self.assertNotCompiled(self.barfn)
388 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000389
R. David Murray95333e32010-12-14 22:32:50 +0000390 def test_multiple_dirs(self):
391 pkgdir2 = os.path.join(self.directory, 'foo2')
392 os.mkdir(pkgdir2)
393 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
394 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
395 self.assertRunOK('-q', self.pkgdir, pkgdir2)
396 self.assertCompiled(self.initfn)
397 self.assertCompiled(self.barfn)
398 self.assertCompiled(init2fn)
399 self.assertCompiled(bar2fn)
400
401 def test_d_takes_exactly_one_dir(self):
402 rc, out, err = self.assertRunNotOK('-d', 'foo')
403 self.assertEqual(out, b'')
404 self.assertRegex(err, b'-d')
405 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
406 self.assertEqual(out, b'')
407 self.assertRegex(err, b'-d')
408
409 def test_d_compile_error(self):
410 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
411 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
412 self.assertRegex(out, b'File "dinsdale')
413
414 def test_d_runtime_error(self):
415 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
416 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
417 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400418 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000419 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
420 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200421 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000422 self.assertRegex(err, b'File "dinsdale')
423
424 def test_include_bad_file(self):
425 rc, out, err = self.assertRunNotOK(
426 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
427 self.assertRegex(out, b'rror.*nosuchfile')
428 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400429 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000430 self.pkgdir_cachedir)))
431
432 def test_include_file_with_arg(self):
433 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
434 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
435 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
436 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
437 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
438 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
439 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
440 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
441 self.assertCompiled(f1)
442 self.assertCompiled(f2)
443 self.assertNotCompiled(f3)
444 self.assertCompiled(f4)
445
446 def test_include_file_no_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, 'f2.py')+os.linesep)
453 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
454 self.assertNotCompiled(f1)
455 self.assertCompiled(f2)
456 self.assertNotCompiled(f3)
457 self.assertNotCompiled(f4)
458
459 def test_include_on_stdin(self):
460 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
461 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
462 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
463 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400464 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000465 p.stdin.write((f3+os.linesep).encode('ascii'))
466 script_helper.kill_python(p)
467 self.assertNotCompiled(f1)
468 self.assertNotCompiled(f2)
469 self.assertCompiled(f3)
470 self.assertNotCompiled(f4)
471
472 def test_compiles_as_much_as_possible(self):
473 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
474 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
475 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000476 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000477 self.assertNotCompiled(bingfn)
478 self.assertCompiled(self.initfn)
479 self.assertCompiled(self.barfn)
480
R. David Murray5317e9c2010-12-16 19:08:51 +0000481 def test_invalid_arg_produces_message(self):
482 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200483 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000484
Brett Cannonf1a8df02014-09-12 10:39:48 -0400485 @skipUnless(_have_multiprocessing, "requires multiprocessing")
486 def test_workers(self):
487 bar2fn = script_helper.make_script(self.directory, 'bar2', '')
488 files = []
489 for suffix in range(5):
490 pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))
491 os.mkdir(pkgdir)
492 fn = script_helper.make_script(pkgdir, '__init__', '')
493 files.append(script_helper.make_script(pkgdir, 'bar2', ''))
494
495 self.assertRunOK(self.directory, '-j', '0')
496 self.assertCompiled(bar2fn)
497 for file in files:
498 self.assertCompiled(file)
499
500 @mock.patch('compileall.compile_dir')
501 def test_workers_available_cores(self, compile_dir):
502 with mock.patch("sys.argv",
503 new=[sys.executable, self.directory, "-j0"]):
504 compileall.main()
505 self.assertTrue(compile_dir.called)
506 self.assertEqual(compile_dir.call_args[-1]['workers'], None)
507
Barry Warsaw28a691b2010-04-17 00:19:56 +0000508
Brett Cannonbefb14f2009-02-10 02:10:16 +0000509if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400510 unittest.main()