blob: 0505c521d1c4857b08ab7325ba05543730c9ada7 [file] [log] [blame]
Martin v. Löwis4b003072010-03-16 13:19:21 +00001import sys
Brett Cannonbefb14f2009-02-10 02:10:16 +00002import compileall
3import imp
4import os
5import py_compile
6import shutil
7import struct
Barry Warsaw28a691b2010-04-17 00:19:56 +00008import subprocess
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
R. David Murray95333e32010-12-14 22:32:50 +000014from test import support, script_helper
Brett Cannonbefb14f2009-02-10 02:10:16 +000015
16class CompileallTests(unittest.TestCase):
17
18 def setUp(self):
19 self.directory = tempfile.mkdtemp()
20 self.source_path = os.path.join(self.directory, '_test.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000021 self.bc_path = imp.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000022 with open(self.source_path, 'w') as file:
23 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000024 self.source_path2 = os.path.join(self.directory, '_test2.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000025 self.bc_path2 = imp.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000026 shutil.copyfile(self.source_path, self.source_path2)
Georg Brandl45438462011-02-07 12:36:54 +000027 self.subdirectory = os.path.join(self.directory, '_subdir')
28 os.mkdir(self.subdirectory)
29 self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
30 shutil.copyfile(self.source_path, self.source_path3)
Brett Cannonbefb14f2009-02-10 02:10:16 +000031
32 def tearDown(self):
33 shutil.rmtree(self.directory)
34
35 def data(self):
36 with open(self.bc_path, 'rb') as file:
37 data = file.read(8)
38 mtime = int(os.stat(self.source_path).st_mtime)
39 compare = struct.pack('<4sl', imp.get_magic(), mtime)
40 return data, compare
41
Serhiy Storchaka79080682013-11-03 21:31:18 +020042 @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
Brett Cannonbefb14f2009-02-10 02:10:16 +000043 def recreation_check(self, metadata):
44 """Check that compileall recreates bytecode when the new metadata is
45 used."""
Brett Cannonbefb14f2009-02-10 02:10:16 +000046 py_compile.compile(self.source_path)
47 self.assertEqual(*self.data())
48 with open(self.bc_path, 'rb') as file:
49 bc = file.read()[len(metadata):]
50 with open(self.bc_path, 'wb') as file:
51 file.write(metadata)
52 file.write(bc)
53 self.assertNotEqual(*self.data())
54 compileall.compile_dir(self.directory, force=False, quiet=True)
55 self.assertTrue(*self.data())
56
57 def test_mtime(self):
58 # Test a change in mtime leads to a new .pyc.
59 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
60
61 def test_magic_number(self):
62 # Test a change in mtime leads to a new .pyc.
63 self.recreation_check(b'\0\0\0\0')
64
Matthias Klosec33b9022010-03-16 00:36:26 +000065 def test_compile_files(self):
66 # Test compiling a single file, and complete directory
67 for fn in (self.bc_path, self.bc_path2):
68 try:
69 os.unlink(fn)
70 except:
71 pass
72 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000073 self.assertTrue(os.path.isfile(self.bc_path) and
74 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000075 os.unlink(self.bc_path)
76 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000077 self.assertTrue(os.path.isfile(self.bc_path) and
78 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000079 os.unlink(self.bc_path)
80 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000081
Barry Warsawc8a99de2010-04-29 18:43:10 +000082 def test_no_pycache_in_non_package(self):
83 # Bug 8563 reported that __pycache__ directories got created by
84 # compile_file() for non-.py files.
85 data_dir = os.path.join(self.directory, 'data')
86 data_file = os.path.join(data_dir, 'file')
87 os.mkdir(data_dir)
88 # touch data/file
89 with open(data_file, 'w'):
90 pass
91 compileall.compile_file(data_file)
92 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
93
Georg Brandl8334fd92010-12-04 10:26:46 +000094 def test_optimize(self):
95 # make sure compiling with different optimization settings than the
96 # interpreter's creates the correct file names
97 optimize = 1 if __debug__ else 0
98 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
99 cached = imp.cache_from_source(self.source_path,
100 debug_override=not optimize)
101 self.assertTrue(os.path.isfile(cached))
Georg Brandl45438462011-02-07 12:36:54 +0000102 cached2 = imp.cache_from_source(self.source_path2,
103 debug_override=not optimize)
104 self.assertTrue(os.path.isfile(cached2))
105 cached3 = imp.cache_from_source(self.source_path3,
106 debug_override=not optimize)
107 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000108
Barry Warsaw28a691b2010-04-17 00:19:56 +0000109
Martin v. Löwis4b003072010-03-16 13:19:21 +0000110class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111 """Issue 6716: compileall should escape source code when printing errors
112 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000113
114 def setUp(self):
115 self.directory = tempfile.mkdtemp()
116 self.source_path = os.path.join(self.directory, '_test.py')
117 with open(self.source_path, 'w', encoding='utf-8') as file:
118 file.write('# -*- coding: utf-8 -*-\n')
119 file.write('print u"\u20ac"\n')
120
121 def tearDown(self):
122 shutil.rmtree(self.directory)
123
124 def test_error(self):
125 try:
126 orig_stdout = sys.stdout
127 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
128 compileall.compile_dir(self.directory)
129 finally:
130 sys.stdout = orig_stdout
131
Barry Warsawc8a99de2010-04-29 18:43:10 +0000132
Barry Warsaw28a691b2010-04-17 00:19:56 +0000133class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000134 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000135
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400136 def _get_run_args(self, args):
137 interp_args = ['-S']
138 if sys.flags.optimize:
139 interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
140 return interp_args + ['-m', 'compileall'] + list(args)
141
R. David Murray5317e9c2010-12-16 19:08:51 +0000142 def assertRunOK(self, *args, **env_vars):
143 rc, out, err = script_helper.assert_python_ok(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400144 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000145 self.assertEqual(b'', err)
146 return out
147
R. David Murray5317e9c2010-12-16 19:08:51 +0000148 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000149 rc, out, err = script_helper.assert_python_failure(
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400150 *self._get_run_args(args), **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000151 return rc, out, err
152
153 def assertCompiled(self, fn):
154 self.assertTrue(os.path.exists(imp.cache_from_source(fn)))
155
156 def assertNotCompiled(self, fn):
157 self.assertFalse(os.path.exists(imp.cache_from_source(fn)))
158
Barry Warsaw28a691b2010-04-17 00:19:56 +0000159 def setUp(self):
160 self.addCleanup(self._cleanup)
161 self.directory = tempfile.mkdtemp()
162 self.pkgdir = os.path.join(self.directory, 'foo')
163 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000164 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
165 # Create the __init__.py and a package module.
166 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
167 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000168
169 def _cleanup(self):
170 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000171
172 def test_no_args_compiles_path(self):
173 # Note that -l is implied for the no args case.
174 bazfn = script_helper.make_script(self.directory, 'baz', '')
175 self.assertRunOK(PYTHONPATH=self.directory)
176 self.assertCompiled(bazfn)
177 self.assertNotCompiled(self.initfn)
178 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000179
R David Murray8a1d1e62013-12-15 20:49:38 -0500180 def test_no_args_respects_force_flag(self):
181 bazfn = script_helper.make_script(self.directory, 'baz', '')
182 self.assertRunOK(PYTHONPATH=self.directory)
183 pycpath = imp.cache_from_source(bazfn)
184 # Set atime/mtime backward to avoid file timestamp resolution issues
185 os.utime(pycpath, (time.time()-60,)*2)
186 mtime = os.stat(pycpath).st_mtime
187 # Without force, no recompilation
188 self.assertRunOK(PYTHONPATH=self.directory)
189 mtime2 = os.stat(pycpath).st_mtime
190 self.assertEqual(mtime, mtime2)
191 # Now force it.
192 self.assertRunOK('-f', PYTHONPATH=self.directory)
193 mtime2 = os.stat(pycpath).st_mtime
194 self.assertNotEqual(mtime, mtime2)
195
196 def test_no_args_respects_quiet_flag(self):
197 script_helper.make_script(self.directory, 'baz', '')
198 noisy = self.assertRunOK(PYTHONPATH=self.directory)
199 self.assertIn(b'Listing ', noisy)
200 quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)
201 self.assertNotIn(b'Listing ', quiet)
202
Georg Brandl1463a3f2010-10-14 07:42:27 +0000203 # Ensure that the default behavior of compileall's CLI is to create
204 # PEP 3147 pyc/pyo files.
205 for name, ext, switch in [
206 ('normal', 'pyc', []),
207 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000208 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000209 ]:
210 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000211 script_helper.assert_python_ok(*(switch +
212 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000213 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000214 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000215 expected = sorted(base.format(imp.get_tag(), ext) for base in
216 ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000217 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000218 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000219 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
220 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000221 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000222
223 def test_legacy_paths(self):
224 # Ensure that with the proper switch, compileall leaves legacy
225 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000226 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000227 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000228 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400229 opt = 'c' if __debug__ else 'o'
230 expected = sorted(['__init__.py', '__init__.py' + opt, 'bar.py',
231 'bar.py' + opt])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000232 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
233
Barry Warsawc04317f2010-04-26 15:59:03 +0000234 def test_multiple_runs(self):
235 # Bug 8527 reported that multiple calls produced empty
236 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000237 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000238 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000239 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
240 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000241 self.assertFalse(os.path.exists(cachecachedir))
242 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000243 self.assertRunOK('-q', self.pkgdir)
244 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000245 self.assertFalse(os.path.exists(cachecachedir))
246
R. David Murray650f1472010-11-20 21:18:51 +0000247 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000248 self.assertRunOK('-q', self.pkgdir)
249 pycpath = imp.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000250 # set atime/mtime backward to avoid file timestamp resolution issues
251 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000252 mtime = os.stat(pycpath).st_mtime
253 # without force, no recompilation
254 self.assertRunOK('-q', self.pkgdir)
255 mtime2 = os.stat(pycpath).st_mtime
256 self.assertEqual(mtime, mtime2)
257 # now force it.
258 self.assertRunOK('-q', '-f', self.pkgdir)
259 mtime2 = os.stat(pycpath).st_mtime
260 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000261
R. David Murray95333e32010-12-14 22:32:50 +0000262 def test_recursion_control(self):
263 subpackage = os.path.join(self.pkgdir, 'spam')
264 os.mkdir(subpackage)
265 subinitfn = script_helper.make_script(subpackage, '__init__', '')
266 hamfn = script_helper.make_script(subpackage, 'ham', '')
267 self.assertRunOK('-q', '-l', self.pkgdir)
268 self.assertNotCompiled(subinitfn)
269 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
270 self.assertRunOK('-q', self.pkgdir)
271 self.assertCompiled(subinitfn)
272 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000273
274 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000275 noisy = self.assertRunOK(self.pkgdir)
276 quiet = self.assertRunOK('-q', self.pkgdir)
277 self.assertNotEqual(b'', noisy)
278 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000279
280 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400281 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000282 self.assertNotCompiled(self.barfn)
283 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000284
R. David Murray95333e32010-12-14 22:32:50 +0000285 def test_multiple_dirs(self):
286 pkgdir2 = os.path.join(self.directory, 'foo2')
287 os.mkdir(pkgdir2)
288 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
289 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
290 self.assertRunOK('-q', self.pkgdir, pkgdir2)
291 self.assertCompiled(self.initfn)
292 self.assertCompiled(self.barfn)
293 self.assertCompiled(init2fn)
294 self.assertCompiled(bar2fn)
295
296 def test_d_takes_exactly_one_dir(self):
297 rc, out, err = self.assertRunNotOK('-d', 'foo')
298 self.assertEqual(out, b'')
299 self.assertRegex(err, b'-d')
300 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
301 self.assertEqual(out, b'')
302 self.assertRegex(err, b'-d')
303
304 def test_d_compile_error(self):
305 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
306 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
307 self.assertRegex(out, b'File "dinsdale')
308
309 def test_d_runtime_error(self):
310 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
311 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
312 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
313 pyc = imp.cache_from_source(bazfn)
314 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
315 os.remove(bazfn)
316 rc, out, err = script_helper.assert_python_failure(fn)
317 self.assertRegex(err, b'File "dinsdale')
318
319 def test_include_bad_file(self):
320 rc, out, err = self.assertRunNotOK(
321 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
322 self.assertRegex(out, b'rror.*nosuchfile')
323 self.assertNotRegex(err, b'Traceback')
324 self.assertFalse(os.path.exists(imp.cache_from_source(
325 self.pkgdir_cachedir)))
326
327 def test_include_file_with_arg(self):
328 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
329 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
330 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
331 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
332 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
333 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
334 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
335 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
336 self.assertCompiled(f1)
337 self.assertCompiled(f2)
338 self.assertNotCompiled(f3)
339 self.assertCompiled(f4)
340
341 def test_include_file_no_arg(self):
342 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
343 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
344 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
345 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
346 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
347 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
348 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
349 self.assertNotCompiled(f1)
350 self.assertCompiled(f2)
351 self.assertNotCompiled(f3)
352 self.assertNotCompiled(f4)
353
354 def test_include_on_stdin(self):
355 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
356 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
357 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
358 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400359 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000360 p.stdin.write((f3+os.linesep).encode('ascii'))
361 script_helper.kill_python(p)
362 self.assertNotCompiled(f1)
363 self.assertNotCompiled(f2)
364 self.assertCompiled(f3)
365 self.assertNotCompiled(f4)
366
367 def test_compiles_as_much_as_possible(self):
368 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
369 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
370 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000371 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000372 self.assertNotCompiled(bingfn)
373 self.assertCompiled(self.initfn)
374 self.assertCompiled(self.barfn)
375
R. David Murray5317e9c2010-12-16 19:08:51 +0000376 def test_invalid_arg_produces_message(self):
377 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200378 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000379
Barry Warsaw28a691b2010-04-17 00:19:56 +0000380
Brett Cannonbefb14f2009-02-10 02:10:16 +0000381def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000382 support.run_unittest(
383 CommandLineTests,
384 CompileallTests,
385 EncodingTest,
386 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000387
388
389if __name__ == "__main__":
390 test_main()