blob: ff2515df4cf137ecaf3a68e7a734191af0049f24 [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
Barry Warsaw28a691b2010-04-17 00:19:56 +00008import subprocess
Brett Cannon7822e122013-06-14 23:04:02 -04009import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +000010import tempfile
R. David Murray650f1472010-11-20 21:18:51 +000011import time
Brett Cannonbefb14f2009-02-10 02:10:16 +000012import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000013import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
R. David Murray95333e32010-12-14 22:32:50 +000015from test import support, script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000016
17class CompileallTests(unittest.TestCase):
18
19 def setUp(self):
20 self.directory = tempfile.mkdtemp()
21 self.source_path = os.path.join(self.directory, '_test.py')
Brett Cannon7822e122013-06-14 23:04:02 -040022 self.bc_path = importlib.util.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000023 with open(self.source_path, 'w') as file:
24 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000025 self.source_path2 = os.path.join(self.directory, '_test2.py')
Brett Cannon7822e122013-06-14 23:04:02 -040026 self.bc_path2 = importlib.util.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000027 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000028 self.subdirectory = os.path.join(self.directory, '_subdir')
29 os.mkdir(self.subdirectory)
30 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
31 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000032
33 def tearDown(self):
34 shutil.rmtree(self.directory)
35
36 def data(self):
37 with open(self.bc_path, 'rb') as file:
38 data = file.read(8)
39 mtime = int(os.stat(self.source_path).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -040040 compare = struct.pack('<4sl', importlib.util.MAGIC_NUMBER, mtime)
Brett Cannonbefb14f2009-02-10 02:10:16 +000041 return data, compare
42
Serhiy Storchaka43767632013-11-03 21:31:38 +020043 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000044 def recreation_check(self, metadata):
45 """Check that compileall recreates bytecode when the new metadata is
46 used."""
Brett Cannonbefb14f2009-02-10 02:10:16 +000047 py_compile.compile(self.source_path)
48 self.assertEqual(*self.data())
49 with open(self.bc_path, 'rb') as file:
50 bc = file.read()[len(metadata):]
51 with open(self.bc_path, 'wb') as file:
52 file.write(metadata)
53 file.write(bc)
54 self.assertNotEqual(*self.data())
55 compileall.compile_dir(self.directory, force=False, quiet=True)
56 self.assertTrue(*self.data())
57
58 def test_mtime(self):
59 # Test a change in mtime leads to a new .pyc.
Brett Cannon7822e122013-06-14 23:04:02 -040060 self.recreation_check(struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
61 1))
Brett Cannonbefb14f2009-02-10 02:10:16 +000062
63 def test_magic_number(self):
64 # Test a change in mtime leads to a new .pyc.
65 self.recreation_check(b'\0\0\0\0')
66
Matthias Klosec33b9022010-03-16 00:36:26 +000067 def test_compile_files(self):
68 # Test compiling a single file, and complete directory
69 for fn in (self.bc_path, self.bc_path2):
70 try:
71 os.unlink(fn)
72 except:
73 pass
74 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000075 self.assertTrue(os.path.isfile(self.bc_path) and
76 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000077 os.unlink(self.bc_path)
78 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000079 self.assertTrue(os.path.isfile(self.bc_path) and
80 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000081 os.unlink(self.bc_path)
82 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000083
Barry Warsawc8a99de2010-04-29 18:43:10 +000084 def test_no_pycache_in_non_package(self):
85 # Bug 8563 reported that __pycache__ directories got created by
86 # compile_file() for non-.py files.
87 data_dir = os.path.join(self.directory, 'data')
88 data_file = os.path.join(data_dir, 'file')
89 os.mkdir(data_dir)
90 # touch data/file
91 with open(data_file, 'w'):
92 pass
93 compileall.compile_file(data_file)
94 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
95
Georg Brandl8334fd92010-12-04 10:26:46 +000096 def test_optimize(self):
97 # make sure compiling with different optimization settings than the
98 # interpreter's creates the correct file names
99 optimize = 1 if __debug__ else 0
100 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
Brett Cannon7822e122013-06-14 23:04:02 -0400101 cached = importlib.util.cache_from_source(self.source_path,
102 debug_override=not optimize)
Georg Brandl8334fd92010-12-04 10:26:46 +0000103 self.assertTrue(os.path.isfile(cached))
Brett Cannon7822e122013-06-14 23:04:02 -0400104 cached2 = importlib.util.cache_from_source(self.source_path2,
105 debug_override=not optimize)
Georg Brandl45438462011-02-07 12:36:54 +0000106 self.assertTrue(os.path.isfile(cached2))
Brett Cannon7822e122013-06-14 23:04:02 -0400107 cached3 = importlib.util.cache_from_source(self.source_path3,
108 debug_override=not optimize)
Georg Brandl45438462011-02-07 12:36:54 +0000109 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000110
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111
Martin v. Löwis4b003072010-03-16 13:19:21 +0000112class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000113 """Issue 6716: compileall should escape source code when printing errors
114 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000115
116 def setUp(self):
117 self.directory = tempfile.mkdtemp()
118 self.source_path = os.path.join(self.directory, '_test.py')
119 with open(self.source_path, 'w', encoding='utf-8') as file:
120 file.write('# -*- coding: utf-8 -*-\n')
121 file.write('print u"\u20ac"\n')
122
123 def tearDown(self):
124 shutil.rmtree(self.directory)
125
126 def test_error(self):
127 try:
128 orig_stdout = sys.stdout
129 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
130 compileall.compile_dir(self.directory)
131 finally:
132 sys.stdout = orig_stdout
133
Barry Warsawc8a99de2010-04-29 18:43:10 +0000134
Barry Warsaw28a691b2010-04-17 00:19:56 +0000135class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000136 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000137
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400138 def _get_run_args(self, args):
139 interp_args = ['-S']
140 if sys.flags.optimize:
141 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
142 return interp_args + ['-m', 'compileall'] + list(args)
143
R. David Murray5317e9c2010-12-16 19:08:51 +0000144 def assertRunOK(self, *args, **env_vars):
145 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400146 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000147 self.assertEqual(b'', err)
148 return out
149
R. David Murray5317e9c2010-12-16 19:08:51 +0000150 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000151 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400152 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000153 return rc, out, err
154
155 def assertCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400156 path = importlib.util.cache_from_source(fn)
157 self.assertTrue(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000158
159 def assertNotCompiled(self, fn):
Brett Cannon7822e122013-06-14 23:04:02 -0400160 path = importlib.util.cache_from_source(fn)
161 self.assertFalse(os.path.exists(path))
R. David Murray95333e32010-12-14 22:32:50 +0000162
Barry Warsaw28a691b2010-04-17 00:19:56 +0000163 def setUp(self):
164 self.addCleanup(self._cleanup)
165 self.directory = tempfile.mkdtemp()
166 self.pkgdir = os.path.join(self.directory, 'foo')
167 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000168 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
169 # Create the __init__.py and a package module.
170 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
171 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000172
173 def _cleanup(self):
174 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000175
176 def test_no_args_compiles_path(self):
177 # Note that -l is implied for the no args case.
178 bazfn = script_helper.make_script(self.directory, 'baz', '')
179 self.assertRunOK(PYTHONPATH=self.directory)
180 self.assertCompiled(bazfn)
181 self.assertNotCompiled(self.initfn)
182 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000183
Georg Brandl1463a3f2010-10-14 07:42:27 +0000184 # Ensure that the default behavior of compileall's CLI is to create
185 # PEP 3147 pyc/pyo files.
186 for name, ext, switch in [
187 ('normal', 'pyc', []),
188 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000189 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000190 ]:
191 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000192 script_helper.assert_python_ok(*(switch +
193 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000194 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000195 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Brett Cannon7822e122013-06-14 23:04:02 -0400196 expected = sorted(base.format(sys.implementation.cache_tag, ext)
197 for base in ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000198 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000199 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000200 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
201 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000202 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000203
204 def test_legacy_paths(self):
205 # Ensure that with the proper switch, compileall leaves legacy
206 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000207 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000208 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000209 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400210 opt = 'c' if __debug__ else 'o'
211 expected = sorted(['__init__.py', '__init__.py' + opt, 'bar.py',
212 'bar.py' + opt])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000213 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
214
Barry Warsawc04317f2010-04-26 15:59:03 +0000215 def test_multiple_runs(self):
216 # Bug 8527 reported that multiple calls produced empty
217 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000218 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000219 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000220 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
221 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000222 self.assertFalse(os.path.exists(cachecachedir))
223 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000224 self.assertRunOK('-q', self.pkgdir)
225 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000226 self.assertFalse(os.path.exists(cachecachedir))
227
R. David Murray650f1472010-11-20 21:18:51 +0000228 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000229 self.assertRunOK('-q', self.pkgdir)
Brett Cannon7822e122013-06-14 23:04:02 -0400230 pycpath = importlib.util.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000231 # set atime/mtime backward to avoid file timestamp resolution issues
232 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000233 mtime = os.stat(pycpath).st_mtime
234 # without force, no recompilation
235 self.assertRunOK('-q', self.pkgdir)
236 mtime2 = os.stat(pycpath).st_mtime
237 self.assertEqual(mtime, mtime2)
238 # now force it.
239 self.assertRunOK('-q', '-f', self.pkgdir)
240 mtime2 = os.stat(pycpath).st_mtime
241 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000242
R. David Murray95333e32010-12-14 22:32:50 +0000243 def test_recursion_control(self):
244 subpackage = os.path.join(self.pkgdir, 'spam')
245 os.mkdir(subpackage)
246 subinitfn = script_helper.make_script(subpackage, '__init__', '')
247 hamfn = script_helper.make_script(subpackage, 'ham', '')
248 self.assertRunOK('-q', '-l', self.pkgdir)
249 self.assertNotCompiled(subinitfn)
250 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
251 self.assertRunOK('-q', self.pkgdir)
252 self.assertCompiled(subinitfn)
253 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000254
255 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000256 noisy = self.assertRunOK(self.pkgdir)
257 quiet = self.assertRunOK('-q', self.pkgdir)
258 self.assertNotEqual(b'', noisy)
259 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000260
261 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400262 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000263 self.assertNotCompiled(self.barfn)
264 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000265
R. David Murray95333e32010-12-14 22:32:50 +0000266 def test_multiple_dirs(self):
267 pkgdir2 = os.path.join(self.directory, 'foo2')
268 os.mkdir(pkgdir2)
269 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
270 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
271 self.assertRunOK('-q', self.pkgdir, pkgdir2)
272 self.assertCompiled(self.initfn)
273 self.assertCompiled(self.barfn)
274 self.assertCompiled(init2fn)
275 self.assertCompiled(bar2fn)
276
277 def test_d_takes_exactly_one_dir(self):
278 rc, out, err = self.assertRunNotOK('-d', 'foo')
279 self.assertEqual(out, b'')
280 self.assertRegex(err, b'-d')
281 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
282 self.assertEqual(out, b'')
283 self.assertRegex(err, b'-d')
284
285 def test_d_compile_error(self):
286 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
287 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
288 self.assertRegex(out, b'File "dinsdale')
289
290 def test_d_runtime_error(self):
291 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
292 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
293 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
Brett Cannon7822e122013-06-14 23:04:02 -0400294 pyc = importlib.util.cache_from_source(bazfn)
R. David Murray95333e32010-12-14 22:32:50 +0000295 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
296 os.remove(bazfn)
Victor Stinnere8785ff2013-10-12 14:44:01 +0200297 rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)
R. David Murray95333e32010-12-14 22:32:50 +0000298 self.assertRegex(err, b'File "dinsdale')
299
300 def test_include_bad_file(self):
301 rc, out, err = self.assertRunNotOK(
302 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
303 self.assertRegex(out, b'rror.*nosuchfile')
304 self.assertNotRegex(err, b'Traceback')
Brett Cannon7822e122013-06-14 23:04:02 -0400305 self.assertFalse(os.path.exists(importlib.util.cache_from_source(
R. David Murray95333e32010-12-14 22:32:50 +0000306 self.pkgdir_cachedir)))
307
308 def test_include_file_with_arg(self):
309 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
310 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
311 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
312 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
313 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
314 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
315 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
316 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
317 self.assertCompiled(f1)
318 self.assertCompiled(f2)
319 self.assertNotCompiled(f3)
320 self.assertCompiled(f4)
321
322 def test_include_file_no_arg(self):
323 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
324 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
325 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
326 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
327 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
328 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
329 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
330 self.assertNotCompiled(f1)
331 self.assertCompiled(f2)
332 self.assertNotCompiled(f3)
333 self.assertNotCompiled(f4)
334
335 def test_include_on_stdin(self):
336 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
337 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
338 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
339 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400340 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000341 p.stdin.write((f3+os.linesep).encode('ascii'))
342 script_helper.kill_python(p)
343 self.assertNotCompiled(f1)
344 self.assertNotCompiled(f2)
345 self.assertCompiled(f3)
346 self.assertNotCompiled(f4)
347
348 def test_compiles_as_much_as_possible(self):
349 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
350 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
351 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000352 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000353 self.assertNotCompiled(bingfn)
354 self.assertCompiled(self.initfn)
355 self.assertCompiled(self.barfn)
356
R. David Murray5317e9c2010-12-16 19:08:51 +0000357 def test_invalid_arg_produces_message(self):
358 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200359 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000360
Barry Warsaw28a691b2010-04-17 00:19:56 +0000361
Brett Cannonbefb14f2009-02-10 02:10:16 +0000362if __name__ == "__main__":
Brett Cannon7822e122013-06-14 23:04:02 -0400363 unittest.main()