blob: 295dc400671e1ad54423ddf08d3c06ab49b27777 [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)
Brett Cannonbefb14f2009-02-10 02:10:16 +000027
28 def tearDown(self):
29 shutil.rmtree(self.directory)
30
31 def data(self):
32 with open(self.bc_path, 'rb') as file:
33 data = file.read(8)
34 mtime = int(os.stat(self.source_path).st_mtime)
35 compare = struct.pack('<4sl', imp.get_magic(), mtime)
36 return data, compare
37
38 def recreation_check(self, metadata):
39 """Check that compileall recreates bytecode when the new metadata is
40 used."""
41 if not hasattr(os, 'stat'):
42 return
43 py_compile.compile(self.source_path)
44 self.assertEqual(*self.data())
45 with open(self.bc_path, 'rb') as file:
46 bc = file.read()[len(metadata):]
47 with open(self.bc_path, 'wb') as file:
48 file.write(metadata)
49 file.write(bc)
50 self.assertNotEqual(*self.data())
51 compileall.compile_dir(self.directory, force=False, quiet=True)
52 self.assertTrue(*self.data())
53
54 def test_mtime(self):
55 # Test a change in mtime leads to a new .pyc.
56 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
57
58 def test_magic_number(self):
59 # Test a change in mtime leads to a new .pyc.
60 self.recreation_check(b'\0\0\0\0')
61
Matthias Klosec33b9022010-03-16 00:36:26 +000062 def test_compile_files(self):
63 # Test compiling a single file, and complete directory
64 for fn in (self.bc_path, self.bc_path2):
65 try:
66 os.unlink(fn)
67 except:
68 pass
69 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 self.assertTrue(os.path.isfile(self.bc_path) and
71 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000072 os.unlink(self.bc_path)
73 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000074 self.assertTrue(os.path.isfile(self.bc_path) and
75 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000076 os.unlink(self.bc_path)
77 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000078
Barry Warsawc8a99de2010-04-29 18:43:10 +000079 def test_no_pycache_in_non_package(self):
80 # Bug 8563 reported that __pycache__ directories got created by
81 # compile_file() for non-.py files.
82 data_dir = os.path.join(self.directory, 'data')
83 data_file = os.path.join(data_dir, 'file')
84 os.mkdir(data_dir)
85 # touch data/file
86 with open(data_file, 'w'):
87 pass
88 compileall.compile_file(data_file)
89 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
90
Georg Brandl8334fd92010-12-04 10:26:46 +000091 def test_optimize(self):
92 # make sure compiling with different optimization settings than the
93 # interpreter's creates the correct file names
94 optimize = 1 if __debug__ else 0
95 compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
96 cached = imp.cache_from_source(self.source_path,
97 debug_override=not optimize)
98 self.assertTrue(os.path.isfile(cached))
99
Barry Warsaw28a691b2010-04-17 00:19:56 +0000100
Martin v. Löwis4b003072010-03-16 13:19:21 +0000101class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000102 """Issue 6716: compileall should escape source code when printing errors
103 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +0000104
105 def setUp(self):
106 self.directory = tempfile.mkdtemp()
107 self.source_path = os.path.join(self.directory, '_test.py')
108 with open(self.source_path, 'w', encoding='utf-8') as file:
109 file.write('# -*- coding: utf-8 -*-\n')
110 file.write('print u"\u20ac"\n')
111
112 def tearDown(self):
113 shutil.rmtree(self.directory)
114
115 def test_error(self):
116 try:
117 orig_stdout = sys.stdout
118 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
119 compileall.compile_dir(self.directory)
120 finally:
121 sys.stdout = orig_stdout
122
Barry Warsawc8a99de2010-04-29 18:43:10 +0000123
Barry Warsaw28a691b2010-04-17 00:19:56 +0000124class CommandLineTests(unittest.TestCase):
R. David Murray650f1472010-11-20 21:18:51 +0000125 """Test compileall's CLI."""
Barry Warsaw28a691b2010-04-17 00:19:56 +0000126
R. David Murray5317e9c2010-12-16 19:08:51 +0000127 def assertRunOK(self, *args, **env_vars):
128 rc, out, err = script_helper.assert_python_ok(
R. David Murraye0436bc2010-12-21 18:24:33 +0000129 '-S', '-m', 'compileall', *args, **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000130 self.assertEqual(b'', err)
131 return out
132
R. David Murray5317e9c2010-12-16 19:08:51 +0000133 def assertRunNotOK(self, *args, **env_vars):
R. David Murray95333e32010-12-14 22:32:50 +0000134 rc, out, err = script_helper.assert_python_failure(
R. David Murraye0436bc2010-12-21 18:24:33 +0000135 '-S', '-m', 'compileall', *args, **env_vars)
R. David Murray95333e32010-12-14 22:32:50 +0000136 return rc, out, err
137
138 def assertCompiled(self, fn):
139 self.assertTrue(os.path.exists(imp.cache_from_source(fn)))
140
141 def assertNotCompiled(self, fn):
142 self.assertFalse(os.path.exists(imp.cache_from_source(fn)))
143
Barry Warsaw28a691b2010-04-17 00:19:56 +0000144 def setUp(self):
145 self.addCleanup(self._cleanup)
146 self.directory = tempfile.mkdtemp()
147 self.pkgdir = os.path.join(self.directory, 'foo')
148 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000149 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
150 # Create the __init__.py and a package module.
151 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
152 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000153
154 def _cleanup(self):
155 support.rmtree(self.directory)
R. David Murray5317e9c2010-12-16 19:08:51 +0000156
157 def test_no_args_compiles_path(self):
158 # Note that -l is implied for the no args case.
159 bazfn = script_helper.make_script(self.directory, 'baz', '')
160 self.assertRunOK(PYTHONPATH=self.directory)
161 self.assertCompiled(bazfn)
162 self.assertNotCompiled(self.initfn)
163 self.assertNotCompiled(self.barfn)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000164
Georg Brandl1463a3f2010-10-14 07:42:27 +0000165 # Ensure that the default behavior of compileall's CLI is to create
166 # PEP 3147 pyc/pyo files.
167 for name, ext, switch in [
168 ('normal', 'pyc', []),
169 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000170 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000171 ]:
172 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000173 script_helper.assert_python_ok(*(switch +
174 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000175 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000176 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000177 expected = sorted(base.format(imp.get_tag(), ext) for base in
178 ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000179 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000180 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000181 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
182 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000183 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000184
185 def test_legacy_paths(self):
186 # Ensure that with the proper switch, compileall leaves legacy
187 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000188 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000189 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000190 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000191 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000192 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
193
Barry Warsawc04317f2010-04-26 15:59:03 +0000194 def test_multiple_runs(self):
195 # Bug 8527 reported that multiple calls produced empty
196 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000197 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000198 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000199 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
200 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000201 self.assertFalse(os.path.exists(cachecachedir))
202 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000203 self.assertRunOK('-q', self.pkgdir)
204 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000205 self.assertFalse(os.path.exists(cachecachedir))
206
R. David Murray650f1472010-11-20 21:18:51 +0000207 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000208 self.assertRunOK('-q', self.pkgdir)
209 pycpath = imp.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000210 # set atime/mtime backward to avoid file timestamp resolution issues
211 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000212 mtime = os.stat(pycpath).st_mtime
213 # without force, no recompilation
214 self.assertRunOK('-q', self.pkgdir)
215 mtime2 = os.stat(pycpath).st_mtime
216 self.assertEqual(mtime, mtime2)
217 # now force it.
218 self.assertRunOK('-q', '-f', self.pkgdir)
219 mtime2 = os.stat(pycpath).st_mtime
220 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000221
R. David Murray95333e32010-12-14 22:32:50 +0000222 def test_recursion_control(self):
223 subpackage = os.path.join(self.pkgdir, 'spam')
224 os.mkdir(subpackage)
225 subinitfn = script_helper.make_script(subpackage, '__init__', '')
226 hamfn = script_helper.make_script(subpackage, 'ham', '')
227 self.assertRunOK('-q', '-l', self.pkgdir)
228 self.assertNotCompiled(subinitfn)
229 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
230 self.assertRunOK('-q', self.pkgdir)
231 self.assertCompiled(subinitfn)
232 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000233
234 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000235 noisy = self.assertRunOK(self.pkgdir)
236 quiet = self.assertRunOK('-q', self.pkgdir)
237 self.assertNotEqual(b'', noisy)
238 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000239
240 def test_regexp(self):
R. David Murray95333e32010-12-14 22:32:50 +0000241 self.assertRunOK('-q', '-x', 'ba.*', self.pkgdir)
242 self.assertNotCompiled(self.barfn)
243 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000244
R. David Murray95333e32010-12-14 22:32:50 +0000245 def test_multiple_dirs(self):
246 pkgdir2 = os.path.join(self.directory, 'foo2')
247 os.mkdir(pkgdir2)
248 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
249 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
250 self.assertRunOK('-q', self.pkgdir, pkgdir2)
251 self.assertCompiled(self.initfn)
252 self.assertCompiled(self.barfn)
253 self.assertCompiled(init2fn)
254 self.assertCompiled(bar2fn)
255
256 def test_d_takes_exactly_one_dir(self):
257 rc, out, err = self.assertRunNotOK('-d', 'foo')
258 self.assertEqual(out, b'')
259 self.assertRegex(err, b'-d')
260 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
261 self.assertEqual(out, b'')
262 self.assertRegex(err, b'-d')
263
264 def test_d_compile_error(self):
265 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
266 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
267 self.assertRegex(out, b'File "dinsdale')
268
269 def test_d_runtime_error(self):
270 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
271 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
272 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
273 pyc = imp.cache_from_source(bazfn)
274 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
275 os.remove(bazfn)
276 rc, out, err = script_helper.assert_python_failure(fn)
277 self.assertRegex(err, b'File "dinsdale')
278
279 def test_include_bad_file(self):
280 rc, out, err = self.assertRunNotOK(
281 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
282 self.assertRegex(out, b'rror.*nosuchfile')
283 self.assertNotRegex(err, b'Traceback')
284 self.assertFalse(os.path.exists(imp.cache_from_source(
285 self.pkgdir_cachedir)))
286
287 def test_include_file_with_arg(self):
288 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
289 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
290 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
291 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
292 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
293 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
294 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
295 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
296 self.assertCompiled(f1)
297 self.assertCompiled(f2)
298 self.assertNotCompiled(f3)
299 self.assertCompiled(f4)
300
301 def test_include_file_no_arg(self):
302 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
303 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
304 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
305 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
306 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
307 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
308 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
309 self.assertNotCompiled(f1)
310 self.assertCompiled(f2)
311 self.assertNotCompiled(f3)
312 self.assertNotCompiled(f4)
313
314 def test_include_on_stdin(self):
315 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
316 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
317 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
318 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
319 p = script_helper.spawn_python('-m', 'compileall', '-i', '-')
320 p.stdin.write((f3+os.linesep).encode('ascii'))
321 script_helper.kill_python(p)
322 self.assertNotCompiled(f1)
323 self.assertNotCompiled(f2)
324 self.assertCompiled(f3)
325 self.assertNotCompiled(f4)
326
327 def test_compiles_as_much_as_possible(self):
328 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
329 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
330 bingfn, self.barfn)
R. David Murray5317e9c2010-12-16 19:08:51 +0000331 self.assertRegex(out, b'rror')
R. David Murray95333e32010-12-14 22:32:50 +0000332 self.assertNotCompiled(bingfn)
333 self.assertCompiled(self.initfn)
334 self.assertCompiled(self.barfn)
335
R. David Murray5317e9c2010-12-16 19:08:51 +0000336 def test_invalid_arg_produces_message(self):
337 out = self.assertRunOK('badfilename')
338 self.assertRegex(out, b"Can't list badfilename")
R. David Murray650f1472010-11-20 21:18:51 +0000339
Barry Warsaw28a691b2010-04-17 00:19:56 +0000340
Brett Cannonbefb14f2009-02-10 02:10:16 +0000341def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000342 support.run_unittest(
343 CommandLineTests,
344 CompileallTests,
345 EncodingTest,
346 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000347
348
349if __name__ == "__main__":
350 test_main()