blob: 6ec105c922339c59b33686c0534d0ae34a5acd6b [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
42 def recreation_check(self, metadata):
43 """Check that compileall recreates bytecode when the new metadata is
44 used."""
45 if not hasattr(os, 'stat'):
46 return
47 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.
60 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
61
62 def test_magic_number(self):
63 # Test a change in mtime leads to a new .pyc.
64 self.recreation_check(b'\0\0\0\0')
65
Matthias Klosec33b9022010-03-16 00:36:26 +000066 def test_compile_files(self):
67 # Test compiling a single file, and complete directory
68 for fn in (self.bc_path, self.bc_path2):
69 try:
70 os.unlink(fn)
71 except:
72 pass
73 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000074 self.assertTrue(os.path.isfile(self.bc_path) and
75 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000076 os.unlink(self.bc_path)
77 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000078 self.assertTrue(os.path.isfile(self.bc_path) and
79 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000080 os.unlink(self.bc_path)
81 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000082
Barry Warsawc8a99de2010-04-29 18:43:10 +000083 def test_no_pycache_in_non_package(self):
84 # Bug 8563 reported that __pycache__ directories got created by
85 # compile_file() for non-.py files.
86 data_dir = os.path.join(self.directory, 'data')
87 data_file = os.path.join(data_dir, 'file')
88 os.mkdir(data_dir)
89 # touch data/file
90 with open(data_file, 'w'):
91 pass
92 compileall.compile_file(data_file)
93 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
94
Georg Brandl8334fd92010-12-04 10:26:46 +000095 def test_optimize(self):
96 # make sure compiling with different optimization settings than the
97 # interpreter's creates the correct file names
98 optimize = 1 if __debug__ else 0
99 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
100 cached = imp.cache_from_source(self.source_path,
101 debug_override=not optimize)
102 self.assertTrue(os.path.isfile(cached))
Georg Brandl45438462011-02-07 12:36:54 +0000103 cached2 = imp.cache_from_source(self.source_path2,
104 debug_override=not optimize)
105 self.assertTrue(os.path.isfile(cached2))
106 cached3 = imp.cache_from_source(self.source_path3,
107 debug_override=not optimize)
108 self.assertTrue(os.path.isfile(cached3))
Georg Brandl8334fd92010-12-04 10:26:46 +0000109
Barry Warsaw28a691b2010-04-17 00:19:56 +0000110
Martin v. Löwis4b003072010-03-16 13:19:21 +0000111class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112 """Issue 6716: compileall should escape source code when printing errors
113 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000114
115 def setUp(self):
116 self.directory = tempfile.mkdtemp()
117 self.source_path = os.path.join(self.directory, '_test.py')
118 with open(self.source_path, 'w', encoding='utf-8') as file:
119 file.write('# -*- coding: utf-8 -*-\n')
120 file.write('print u"\u20ac"\n')
121
122 def tearDown(self):
123 shutil.rmtree(self.directory)
124
125 def test_error(self):
126 try:
127 orig_stdout = sys.stdout
128 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
129 compileall.compile_dir(self.directory)
130 finally:
131 sys.stdout = orig_stdout
132
Barry Warsawc8a99de2010-04-29 18:43:10 +0000133
Barry Warsaw28a691b2010-04-17 00:19:56 +0000134class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000135 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136
R. David Murray5317e9c2010-12-16 19:08:51 +0000137 def assertRunOK(self, *args, **env_vars):
138 rc, out, err = script_helper.assert_python_ok(
R. David Murraye0436bc2010-12-21 18:24:33 +0000139 '-S', '-m', 'compileall', *args, **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000140 self.assertEqual(b'', err)
141 return out
142
R. David Murray5317e9c2010-12-16 19:08:51 +0000143 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000144 rc, out, err = script_helper.assert_python_failure(
R. David Murraye0436bc2010-12-21 18:24:33 +0000145 '-S', '-m', 'compileall', *args, **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000146 return rc, out, err
147
148 def assertCompiled(self, fn):
149 self.assertTrue(os.path.exists(imp.cache_from_source(fn)))
150
151 def assertNotCompiled(self, fn):
152 self.assertFalse(os.path.exists(imp.cache_from_source(fn)))
153
Barry Warsaw28a691b2010-04-17 00:19:56 +0000154 def setUp(self):
155 self.addCleanup(self._cleanup)
156 self.directory = tempfile.mkdtemp()
157 self.pkgdir = os.path.join(self.directory, 'foo')
158 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000159 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
160 # Create the __init__.py and a package module.
161 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
162 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000163
164 def _cleanup(self):
165 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000166
167 def test_no_args_compiles_path(self):
168 # Note that -l is implied for the no args case.
169 bazfn = script_helper.make_script(self.directory, 'baz', '')
170 self.assertRunOK(PYTHONPATH=self.directory)
171 self.assertCompiled(bazfn)
172 self.assertNotCompiled(self.initfn)
173 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000174
Georg Brandl1463a3f2010-10-14 07:42:27 +0000175 # Ensure that the default behavior of compileall's CLI is to create
176 # PEP 3147 pyc/pyo files.
177 for name, ext, switch in [
178 ('normal', 'pyc', []),
179 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000180 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000181 ]:
182 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000183 script_helper.assert_python_ok(*(switch +
184 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000185 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000186 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000187 expected = sorted(base.format(imp.get_tag(), ext) for base in
188 ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000189 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000190 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000191 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
192 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000193 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000194
195 def test_legacy_paths(self):
196 # Ensure that with the proper switch, compileall leaves legacy
197 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000198 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000199 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000200 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000201 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000202 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
203
Barry Warsawc04317f2010-04-26 15:59:03 +0000204 def test_multiple_runs(self):
205 # Bug 8527 reported that multiple calls produced empty
206 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000207 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000208 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000209 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
210 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000211 self.assertFalse(os.path.exists(cachecachedir))
212 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000213 self.assertRunOK('-q', self.pkgdir)
214 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000215 self.assertFalse(os.path.exists(cachecachedir))
216
R. David Murray650f1472010-11-20 21:18:51 +0000217 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000218 self.assertRunOK('-q', self.pkgdir)
219 pycpath = imp.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000220 # set atime/mtime backward to avoid file timestamp resolution issues
221 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000222 mtime = os.stat(pycpath).st_mtime
223 # without force, no recompilation
224 self.assertRunOK('-q', self.pkgdir)
225 mtime2 = os.stat(pycpath).st_mtime
226 self.assertEqual(mtime, mtime2)
227 # now force it.
228 self.assertRunOK('-q', '-f', self.pkgdir)
229 mtime2 = os.stat(pycpath).st_mtime
230 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000231
R. David Murray95333e32010-12-14 22:32:50 +0000232 def test_recursion_control(self):
233 subpackage = os.path.join(self.pkgdir, 'spam')
234 os.mkdir(subpackage)
235 subinitfn = script_helper.make_script(subpackage, '__init__', '')
236 hamfn = script_helper.make_script(subpackage, 'ham', '')
237 self.assertRunOK('-q', '-l', self.pkgdir)
238 self.assertNotCompiled(subinitfn)
239 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
240 self.assertRunOK('-q', self.pkgdir)
241 self.assertCompiled(subinitfn)
242 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000243
244 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000245 noisy = self.assertRunOK(self.pkgdir)
246 quiet = self.assertRunOK('-q', self.pkgdir)
247 self.assertNotEqual(b'', noisy)
248 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000249
250 def test_regexp(self):
R David Murrayee1a7cb2011-07-01 14:55:43 -0400251 self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000252 self.assertNotCompiled(self.barfn)
253 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000254
R. David Murray95333e32010-12-14 22:32:50 +0000255 def test_multiple_dirs(self):
256 pkgdir2 = os.path.join(self.directory, 'foo2')
257 os.mkdir(pkgdir2)
258 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
259 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
260 self.assertRunOK('-q', self.pkgdir, pkgdir2)
261 self.assertCompiled(self.initfn)
262 self.assertCompiled(self.barfn)
263 self.assertCompiled(init2fn)
264 self.assertCompiled(bar2fn)
265
266 def test_d_takes_exactly_one_dir(self):
267 rc, out, err = self.assertRunNotOK('-d', 'foo')
268 self.assertEqual(out, b'')
269 self.assertRegex(err, b'-d')
270 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
271 self.assertEqual(out, b'')
272 self.assertRegex(err, b'-d')
273
274 def test_d_compile_error(self):
275 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
276 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
277 self.assertRegex(out, b'File "dinsdale')
278
279 def test_d_runtime_error(self):
280 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
281 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
282 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
283 pyc = imp.cache_from_source(bazfn)
284 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
285 os.remove(bazfn)
286 rc, out, err = script_helper.assert_python_failure(fn)
287 self.assertRegex(err, b'File "dinsdale')
288
289 def test_include_bad_file(self):
290 rc, out, err = self.assertRunNotOK(
291 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
292 self.assertRegex(out, b'rror.*nosuchfile')
293 self.assertNotRegex(err, b'Traceback')
294 self.assertFalse(os.path.exists(imp.cache_from_source(
295 self.pkgdir_cachedir)))
296
297 def test_include_file_with_arg(self):
298 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
299 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
300 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
301 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
302 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
303 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
304 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
305 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
306 self.assertCompiled(f1)
307 self.assertCompiled(f2)
308 self.assertNotCompiled(f3)
309 self.assertCompiled(f4)
310
311 def test_include_file_no_arg(self):
312 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
313 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
314 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
315 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
316 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
317 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
318 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
319 self.assertNotCompiled(f1)
320 self.assertCompiled(f2)
321 self.assertNotCompiled(f3)
322 self.assertNotCompiled(f4)
323
324 def test_include_on_stdin(self):
325 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
326 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
327 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
328 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
329 p = script_helper.spawn_python('-m', 'compileall', '-i', '-')
330 p.stdin.write((f3+os.linesep).encode('ascii'))
331 script_helper.kill_python(p)
332 self.assertNotCompiled(f1)
333 self.assertNotCompiled(f2)
334 self.assertCompiled(f3)
335 self.assertNotCompiled(f4)
336
337 def test_compiles_as_much_as_possible(self):
338 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
339 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
340 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000341 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000342 self.assertNotCompiled(bingfn)
343 self.assertCompiled(self.initfn)
344 self.assertCompiled(self.barfn)
345
R. David Murray5317e9c2010-12-16 19:08:51 +0000346 def test_invalid_arg_produces_message(self):
347 out = self.assertRunOK('badfilename')
Victor Stinner53071262011-05-11 00:36:28 +0200348 self.assertRegex(out, b"Can't list 'badfilename'")
R. David Murray650f1472010-11-20 21:18:51 +0000349
Barry Warsaw28a691b2010-04-17 00:19:56 +0000350
Brett Cannonbefb14f2009-02-10 02:10:16 +0000351def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000352 support.run_unittest(
353 CommandLineTests,
354 CompileallTests,
355 EncodingTest,
356 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000357
358
359if __name__ == "__main__":
360 test_main()