blob: fddb538efb172208c2489cef715f584abda1ca4d [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
Georg Brandl1463a3f2010-10-14 07:42:27 +0000180 # Ensure that the default behavior of compileall's CLI is to create
181 # PEP 3147 pyc/pyo files.
182 for name, ext, switch in [
183 ('normal', 'pyc', []),
184 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000185 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000186 ]:
187 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000188 script_helper.assert_python_ok(*(switch +
189 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000190 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000191 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000192 expected = sorted(base.format(imp.get_tag(), ext) for base in
193 ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000194 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000195 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000196 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
197 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000198 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000199
200 def test_legacy_paths(self):
201 # Ensure that with the proper switch, compileall leaves legacy
202 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000203 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000204 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000205 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400206 opt = 'c' if __debug__ else 'o'
207 expected = sorted(['__init__.py', '__init__.py' + opt, 'bar.py',
208 'bar.py' + opt])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000209 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
210
Barry Warsawc04317f2010-04-26 15:59:03 +0000211 def test_multiple_runs(self):
212 # Bug 8527 reported that multiple calls produced empty
213 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000214 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000215 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000216 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
217 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000218 self.assertFalse(os.path.exists(cachecachedir))
219 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000220 self.assertRunOK('-q', self.pkgdir)
221 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000222 self.assertFalse(os.path.exists(cachecachedir))
223
R. David Murray650f1472010-11-20 21:18:51 +0000224 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000225 self.assertRunOK('-q', self.pkgdir)
226 pycpath = imp.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000227 # set atime/mtime backward to avoid file timestamp resolution issues
228 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000229 mtime = os.stat(pycpath).st_mtime
230 # without force, no recompilation
231 self.assertRunOK('-q', self.pkgdir)
232 mtime2 = os.stat(pycpath).st_mtime
233 self.assertEqual(mtime, mtime2)
234 # now force it.
235 self.assertRunOK('-q', '-f', self.pkgdir)
236 mtime2 = os.stat(pycpath).st_mtime
237 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000238
R. David Murray95333e32010-12-14 22:32:50 +0000239 def test_recursion_control(self):
240 subpackage = os.path.join(self.pkgdir, 'spam')
241 os.mkdir(subpackage)
242 subinitfn = script_helper.make_script(subpackage, '__init__', '')
243 hamfn = script_helper.make_script(subpackage, 'ham', '')
244 self.assertRunOK('-q', '-l', self.pkgdir)
245 self.assertNotCompiled(subinitfn)
246 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
247 self.assertRunOK('-q', self.pkgdir)
248 self.assertCompiled(subinitfn)
249 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000250
251 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000252 noisy = self.assertRunOK(self.pkgdir)
253 quiet = self.assertRunOK('-q', self.pkgdir)
254 self.assertNotEqual(b'', noisy)
255 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000256
257 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400258 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000259 self.assertNotCompiled(self.barfn)
260 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000261
R. David Murray95333e32010-12-14 22:32:50 +0000262 def test_multiple_dirs(self):
263 pkgdir2 = os.path.join(self.directory, 'foo2')
264 os.mkdir(pkgdir2)
265 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
266 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
267 self.assertRunOK('-q', self.pkgdir, pkgdir2)
268 self.assertCompiled(self.initfn)
269 self.assertCompiled(self.barfn)
270 self.assertCompiled(init2fn)
271 self.assertCompiled(bar2fn)
272
273 def test_d_takes_exactly_one_dir(self):
274 rc, out, err = self.assertRunNotOK('-d', 'foo')
275 self.assertEqual(out, b'')
276 self.assertRegex(err, b'-d')
277 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
278 self.assertEqual(out, b'')
279 self.assertRegex(err, b'-d')
280
281 def test_d_compile_error(self):
282 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
283 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
284 self.assertRegex(out, b'File "dinsdale')
285
286 def test_d_runtime_error(self):
287 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
288 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
289 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
290 pyc = imp.cache_from_source(bazfn)
291 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
292 os.remove(bazfn)
293 rc, out, err = script_helper.assert_python_failure(fn)
294 self.assertRegex(err, b'File "dinsdale')
295
296 def test_include_bad_file(self):
297 rc, out, err = self.assertRunNotOK(
298 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
299 self.assertRegex(out, b'rror.*nosuchfile')
300 self.assertNotRegex(err, b'Traceback')
301 self.assertFalse(os.path.exists(imp.cache_from_source(
302 self.pkgdir_cachedir)))
303
304 def test_include_file_with_arg(self):
305 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
306 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
307 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
308 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
309 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
310 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
311 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
312 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
313 self.assertCompiled(f1)
314 self.assertCompiled(f2)
315 self.assertNotCompiled(f3)
316 self.assertCompiled(f4)
317
318 def test_include_file_no_arg(self):
319 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
320 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
321 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
322 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
323 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
324 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
325 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
326 self.assertNotCompiled(f1)
327 self.assertCompiled(f2)
328 self.assertNotCompiled(f3)
329 self.assertNotCompiled(f4)
330
331 def test_include_on_stdin(self):
332 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
333 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
334 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
335 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
Benjamin Petersona820c7c2012-09-25 11:42:35 -0400336 p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
R. David Murray95333e32010-12-14 22:32:50 +0000337 p.stdin.write((f3+os.linesep).encode('ascii'))
338 script_helper.kill_python(p)
339 self.assertNotCompiled(f1)
340 self.assertNotCompiled(f2)
341 self.assertCompiled(f3)
342 self.assertNotCompiled(f4)
343
344 def test_compiles_as_much_as_possible(self):
345 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
346 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
347 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000348 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000349 self.assertNotCompiled(bingfn)
350 self.assertCompiled(self.initfn)
351 self.assertCompiled(self.barfn)
352
R. David Murray5317e9c2010-12-16 19:08:51 +0000353 def test_invalid_arg_produces_message(self):
354 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200355 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000356
Barry Warsaw28a691b2010-04-17 00:19:56 +0000357
Brett Cannonbefb14f2009-02-10 02:10:16 +0000358def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000359 support.run_unittest(
360 CommandLineTests,
361 CompileallTests,
362 EncodingTest,
363 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000364
365
366if __name__ == "__main__":
367 test_main()