blob: cd08a8ef96313f0cbd262304ee0b5948e920a319 [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 Murray95333e32010-12-14 22:32:50 +0000127 def assertRunOK(self, *args):
128 rc, out, err = script_helper.assert_python_ok('-m', 'compileall', *args)
129 self.assertEqual(b'', err)
130 return out
131
132 def assertRunNotOK(self, *args):
133 rc, out, err = script_helper.assert_python_failure(
134 '-m', 'compileall', *args)
135 return rc, out, err
136
137 def assertCompiled(self, fn):
138 self.assertTrue(os.path.exists(imp.cache_from_source(fn)))
139
140 def assertNotCompiled(self, fn):
141 self.assertFalse(os.path.exists(imp.cache_from_source(fn)))
142
Barry Warsaw28a691b2010-04-17 00:19:56 +0000143 def setUp(self):
144 self.addCleanup(self._cleanup)
145 self.directory = tempfile.mkdtemp()
146 self.pkgdir = os.path.join(self.directory, 'foo')
147 os.mkdir(self.pkgdir)
R. David Murray95333e32010-12-14 22:32:50 +0000148 self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
149 # Create the __init__.py and a package module.
150 self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
151 self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000152 sys.path.insert(0, self.directory)
153
154 def _cleanup(self):
155 support.rmtree(self.directory)
156 assert sys.path[0] == self.directory, 'Missing path'
157 del sys.path[0]
158
Georg Brandl1463a3f2010-10-14 07:42:27 +0000159 # Ensure that the default behavior of compileall's CLI is to create
160 # PEP 3147 pyc/pyo files.
161 for name, ext, switch in [
162 ('normal', 'pyc', []),
163 ('optimize', 'pyo', ['-O']),
Éric Araujo31717e82010-11-26 00:39:59 +0000164 ('doubleoptimize', 'pyo', ['-OO']),
Georg Brandl1463a3f2010-10-14 07:42:27 +0000165 ]:
166 def f(self, ext=ext, switch=switch):
R. David Murray95333e32010-12-14 22:32:50 +0000167 script_helper.assert_python_ok(*(switch +
168 ['-m', 'compileall', '-q', self.pkgdir]))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000169 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000170 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000171 expected = sorted(base.format(imp.get_tag(), ext) for base in
172 ('__init__.{}.{}', 'bar.{}.{}'))
R. David Murray95333e32010-12-14 22:32:50 +0000173 self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
Georg Brandl1463a3f2010-10-14 07:42:27 +0000174 # Make sure there are no .pyc files in the source directory.
R. David Murray95333e32010-12-14 22:32:50 +0000175 self.assertFalse([fn for fn in os.listdir(self.pkgdir)
176 if fn.endswith(ext)])
Georg Brandl1463a3f2010-10-14 07:42:27 +0000177 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000178
179 def test_legacy_paths(self):
180 # Ensure that with the proper switch, compileall leaves legacy
181 # pyc/pyo files, and no __pycache__ directory.
R. David Murray95333e32010-12-14 22:32:50 +0000182 self.assertRunOK('-b', '-q', self.pkgdir)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000183 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000184 self.assertFalse(os.path.exists(self.pkgdir_cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000185 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000186 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
187
Barry Warsawc04317f2010-04-26 15:59:03 +0000188 def test_multiple_runs(self):
189 # Bug 8527 reported that multiple calls produced empty
190 # __pycache__/__pycache__ directories.
R. David Murray95333e32010-12-14 22:32:50 +0000191 self.assertRunOK('-q', self.pkgdir)
Barry Warsawc04317f2010-04-26 15:59:03 +0000192 # Verify the __pycache__ directory contents.
R. David Murray95333e32010-12-14 22:32:50 +0000193 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
194 cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
Barry Warsawc04317f2010-04-26 15:59:03 +0000195 self.assertFalse(os.path.exists(cachecachedir))
196 # Call compileall again.
R. David Murray95333e32010-12-14 22:32:50 +0000197 self.assertRunOK('-q', self.pkgdir)
198 self.assertTrue(os.path.exists(self.pkgdir_cachedir))
Barry Warsawc04317f2010-04-26 15:59:03 +0000199 self.assertFalse(os.path.exists(cachecachedir))
200
R. David Murray650f1472010-11-20 21:18:51 +0000201 def test_force(self):
R. David Murray95333e32010-12-14 22:32:50 +0000202 self.assertRunOK('-q', self.pkgdir)
203 pycpath = imp.cache_from_source(self.barfn)
R. David Murray650f1472010-11-20 21:18:51 +0000204 # set atime/mtime backward to avoid file timestamp resolution issues
205 os.utime(pycpath, (time.time()-60,)*2)
R. David Murray95333e32010-12-14 22:32:50 +0000206 mtime = os.stat(pycpath).st_mtime
207 # without force, no recompilation
208 self.assertRunOK('-q', self.pkgdir)
209 mtime2 = os.stat(pycpath).st_mtime
210 self.assertEqual(mtime, mtime2)
211 # now force it.
212 self.assertRunOK('-q', '-f', self.pkgdir)
213 mtime2 = os.stat(pycpath).st_mtime
214 self.assertNotEqual(mtime, mtime2)
R. David Murray650f1472010-11-20 21:18:51 +0000215
R. David Murray95333e32010-12-14 22:32:50 +0000216 def test_recursion_control(self):
217 subpackage = os.path.join(self.pkgdir, 'spam')
218 os.mkdir(subpackage)
219 subinitfn = script_helper.make_script(subpackage, '__init__', '')
220 hamfn = script_helper.make_script(subpackage, 'ham', '')
221 self.assertRunOK('-q', '-l', self.pkgdir)
222 self.assertNotCompiled(subinitfn)
223 self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
224 self.assertRunOK('-q', self.pkgdir)
225 self.assertCompiled(subinitfn)
226 self.assertCompiled(hamfn)
R. David Murray650f1472010-11-20 21:18:51 +0000227
228 def test_quiet(self):
R. David Murray95333e32010-12-14 22:32:50 +0000229 noisy = self.assertRunOK(self.pkgdir)
230 quiet = self.assertRunOK('-q', self.pkgdir)
231 self.assertNotEqual(b'', noisy)
232 self.assertEqual(b'', quiet)
R. David Murray650f1472010-11-20 21:18:51 +0000233
234 def test_regexp(self):
R. David Murray95333e32010-12-14 22:32:50 +0000235 self.assertRunOK('-q', '-x', 'ba.*', self.pkgdir)
236 self.assertNotCompiled(self.barfn)
237 self.assertCompiled(self.initfn)
R. David Murray650f1472010-11-20 21:18:51 +0000238
R. David Murray95333e32010-12-14 22:32:50 +0000239 def test_multiple_dirs(self):
240 pkgdir2 = os.path.join(self.directory, 'foo2')
241 os.mkdir(pkgdir2)
242 init2fn = script_helper.make_script(pkgdir2, '__init__', '')
243 bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
244 self.assertRunOK('-q', self.pkgdir, pkgdir2)
245 self.assertCompiled(self.initfn)
246 self.assertCompiled(self.barfn)
247 self.assertCompiled(init2fn)
248 self.assertCompiled(bar2fn)
249
250 def test_d_takes_exactly_one_dir(self):
251 rc, out, err = self.assertRunNotOK('-d', 'foo')
252 self.assertEqual(out, b'')
253 self.assertRegex(err, b'-d')
254 rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
255 self.assertEqual(out, b'')
256 self.assertRegex(err, b'-d')
257
258 def test_d_compile_error(self):
259 script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
260 rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
261 self.assertRegex(out, b'File "dinsdale')
262
263 def test_d_runtime_error(self):
264 bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
265 self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
266 fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
267 pyc = imp.cache_from_source(bazfn)
268 os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
269 os.remove(bazfn)
270 rc, out, err = script_helper.assert_python_failure(fn)
271 self.assertRegex(err, b'File "dinsdale')
272
273 def test_include_bad_file(self):
274 rc, out, err = self.assertRunNotOK(
275 '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
276 self.assertRegex(out, b'rror.*nosuchfile')
277 self.assertNotRegex(err, b'Traceback')
278 self.assertFalse(os.path.exists(imp.cache_from_source(
279 self.pkgdir_cachedir)))
280
281 def test_include_file_with_arg(self):
282 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
283 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
284 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
285 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
286 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
287 l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
288 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
289 self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
290 self.assertCompiled(f1)
291 self.assertCompiled(f2)
292 self.assertNotCompiled(f3)
293 self.assertCompiled(f4)
294
295 def test_include_file_no_arg(self):
296 f1 = script_helper.make_script(self.pkgdir, 'f1', '')
297 f2 = script_helper.make_script(self.pkgdir, 'f2', '')
298 f3 = script_helper.make_script(self.pkgdir, 'f3', '')
299 f4 = script_helper.make_script(self.pkgdir, 'f4', '')
300 with open(os.path.join(self.directory, 'l1'), 'w') as l1:
301 l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
302 self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
303 self.assertNotCompiled(f1)
304 self.assertCompiled(f2)
305 self.assertNotCompiled(f3)
306 self.assertNotCompiled(f4)
307
308 def test_include_on_stdin(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 p = script_helper.spawn_python('-m', 'compileall', '-i', '-')
314 p.stdin.write((f3+os.linesep).encode('ascii'))
315 script_helper.kill_python(p)
316 self.assertNotCompiled(f1)
317 self.assertNotCompiled(f2)
318 self.assertCompiled(f3)
319 self.assertNotCompiled(f4)
320
321 def test_compiles_as_much_as_possible(self):
322 bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
323 rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
324 bingfn, self.barfn)
325 self.assertRegex(b'rror', err)
326 self.assertNotCompiled(bingfn)
327 self.assertCompiled(self.initfn)
328 self.assertCompiled(self.barfn)
329
R. David Murray650f1472010-11-20 21:18:51 +0000330
Barry Warsaw28a691b2010-04-17 00:19:56 +0000331
Brett Cannonbefb14f2009-02-10 02:10:16 +0000332def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000333 support.run_unittest(
334 CommandLineTests,
335 CompileallTests,
336 EncodingTest,
337 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000338
339
340if __name__ == "__main__":
341 test_main()