blob: 1f8df381dc86b0e5830a6e3be180198ab2ef30c7 [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
Brett Cannonbefb14f2009-02-10 02:10:16 +000010import unittest
Martin v. Löwis4b003072010-03-16 13:19:21 +000011import io
Brett Cannonbefb14f2009-02-10 02:10:16 +000012
Barry Warsaw28a691b2010-04-17 00:19:56 +000013from test import support
Brett Cannonbefb14f2009-02-10 02:10:16 +000014
15class CompileallTests(unittest.TestCase):
16
17 def setUp(self):
18 self.directory = tempfile.mkdtemp()
19 self.source_path = os.path.join(self.directory, '_test.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000020 self.bc_path = imp.cache_from_source(self.source_path)
Brett Cannonbefb14f2009-02-10 02:10:16 +000021 with open(self.source_path, 'w') as file:
22 file.write('x = 123\n')
Matthias Klosec33b9022010-03-16 00:36:26 +000023 self.source_path2 = os.path.join(self.directory, '_test2.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000024 self.bc_path2 = imp.cache_from_source(self.source_path2)
Matthias Klosec33b9022010-03-16 00:36:26 +000025 shutil.copyfile(self.source_path, self.source_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000026
27 def tearDown(self):
28 shutil.rmtree(self.directory)
29
30 def data(self):
31 with open(self.bc_path, 'rb') as file:
32 data = file.read(8)
33 mtime = int(os.stat(self.source_path).st_mtime)
34 compare = struct.pack('<4sl', imp.get_magic(), mtime)
35 return data, compare
36
37 def recreation_check(self, metadata):
38 """Check that compileall recreates bytecode when the new metadata is
39 used."""
40 if not hasattr(os, 'stat'):
41 return
42 py_compile.compile(self.source_path)
43 self.assertEqual(*self.data())
44 with open(self.bc_path, 'rb') as file:
45 bc = file.read()[len(metadata):]
46 with open(self.bc_path, 'wb') as file:
47 file.write(metadata)
48 file.write(bc)
49 self.assertNotEqual(*self.data())
50 compileall.compile_dir(self.directory, force=False, quiet=True)
51 self.assertTrue(*self.data())
52
53 def test_mtime(self):
54 # Test a change in mtime leads to a new .pyc.
55 self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1))
56
57 def test_magic_number(self):
58 # Test a change in mtime leads to a new .pyc.
59 self.recreation_check(b'\0\0\0\0')
60
Matthias Klosec33b9022010-03-16 00:36:26 +000061 def test_compile_files(self):
62 # Test compiling a single file, and complete directory
63 for fn in (self.bc_path, self.bc_path2):
64 try:
65 os.unlink(fn)
66 except:
67 pass
68 compileall.compile_file(self.source_path, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000069 self.assertTrue(os.path.isfile(self.bc_path) and
70 not os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000071 os.unlink(self.bc_path)
72 compileall.compile_dir(self.directory, force=False, quiet=True)
Barry Warsaw28a691b2010-04-17 00:19:56 +000073 self.assertTrue(os.path.isfile(self.bc_path) and
74 os.path.isfile(self.bc_path2))
Matthias Klosec33b9022010-03-16 00:36:26 +000075 os.unlink(self.bc_path)
76 os.unlink(self.bc_path2)
Brett Cannonbefb14f2009-02-10 02:10:16 +000077
Barry Warsawc8a99de2010-04-29 18:43:10 +000078 def test_no_pycache_in_non_package(self):
79 # Bug 8563 reported that __pycache__ directories got created by
80 # compile_file() for non-.py files.
81 data_dir = os.path.join(self.directory, 'data')
82 data_file = os.path.join(data_dir, 'file')
83 os.mkdir(data_dir)
84 # touch data/file
85 with open(data_file, 'w'):
86 pass
87 compileall.compile_file(data_file)
88 self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
89
Barry Warsaw28a691b2010-04-17 00:19:56 +000090
Martin v. Löwis4b003072010-03-16 13:19:21 +000091class EncodingTest(unittest.TestCase):
Barry Warsaw28a691b2010-04-17 00:19:56 +000092 """Issue 6716: compileall should escape source code when printing errors
93 to stdout."""
Martin v. Löwis4b003072010-03-16 13:19:21 +000094
95 def setUp(self):
96 self.directory = tempfile.mkdtemp()
97 self.source_path = os.path.join(self.directory, '_test.py')
98 with open(self.source_path, 'w', encoding='utf-8') as file:
99 file.write('# -*- coding: utf-8 -*-\n')
100 file.write('print u"\u20ac"\n')
101
102 def tearDown(self):
103 shutil.rmtree(self.directory)
104
105 def test_error(self):
106 try:
107 orig_stdout = sys.stdout
108 sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii')
109 compileall.compile_dir(self.directory)
110 finally:
111 sys.stdout = orig_stdout
112
Barry Warsawc8a99de2010-04-29 18:43:10 +0000113
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114class CommandLineTests(unittest.TestCase):
115 """Test some aspects of compileall's CLI."""
116
117 def setUp(self):
118 self.addCleanup(self._cleanup)
119 self.directory = tempfile.mkdtemp()
120 self.pkgdir = os.path.join(self.directory, 'foo')
121 os.mkdir(self.pkgdir)
122 # Touch the __init__.py and a package module.
123 with open(os.path.join(self.pkgdir, '__init__.py'), 'w'):
124 pass
125 with open(os.path.join(self.pkgdir, 'bar.py'), 'w'):
126 pass
127 sys.path.insert(0, self.directory)
128
129 def _cleanup(self):
130 support.rmtree(self.directory)
131 assert sys.path[0] == self.directory, 'Missing path'
132 del sys.path[0]
133
Georg Brandl1463a3f2010-10-14 07:42:27 +0000134 # Ensure that the default behavior of compileall's CLI is to create
135 # PEP 3147 pyc/pyo files.
136 for name, ext, switch in [
137 ('normal', 'pyc', []),
138 ('optimize', 'pyo', ['-O']),
139 ('doubleoptimize', 'pyo', ['-OO'])
140 ]:
141 def f(self, ext=ext, switch=switch):
142 retcode = subprocess.call(
143 [sys.executable] + switch +
144 ['-m', 'compileall', '-q', self.pkgdir])
145 self.assertEqual(retcode, 0)
146 # Verify the __pycache__ directory contents.
147 cachedir = os.path.join(self.pkgdir, '__pycache__')
148 self.assertTrue(os.path.exists(cachedir))
149 expected = sorted(base.format(imp.get_tag(), ext) for base in
150 ('__init__.{}.{}', 'bar.{}.{}'))
151 self.assertEqual(sorted(os.listdir(cachedir)), expected)
152 # Make sure there are no .pyc files in the source directory.
153 self.assertFalse([pyc_file for pyc_file in os.listdir(self.pkgdir)
154 if pyc_file.endswith(ext)])
155 locals()['test_pep3147_paths_' + name] = f
Barry Warsaw28a691b2010-04-17 00:19:56 +0000156
157 def test_legacy_paths(self):
158 # Ensure that with the proper switch, compileall leaves legacy
159 # pyc/pyo files, and no __pycache__ directory.
160 retcode = subprocess.call(
161 (sys.executable, '-m', 'compileall', '-b', '-q', self.pkgdir))
162 self.assertEqual(retcode, 0)
163 # Verify the __pycache__ directory contents.
164 cachedir = os.path.join(self.pkgdir, '__pycache__')
165 self.assertFalse(os.path.exists(cachedir))
Georg Brandl1463a3f2010-10-14 07:42:27 +0000166 expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
Barry Warsaw28a691b2010-04-17 00:19:56 +0000167 self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
168
Barry Warsawc04317f2010-04-26 15:59:03 +0000169 def test_multiple_runs(self):
170 # Bug 8527 reported that multiple calls produced empty
171 # __pycache__/__pycache__ directories.
172 retcode = subprocess.call(
173 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
174 self.assertEqual(retcode, 0)
175 # Verify the __pycache__ directory contents.
176 cachedir = os.path.join(self.pkgdir, '__pycache__')
177 self.assertTrue(os.path.exists(cachedir))
178 cachecachedir = os.path.join(cachedir, '__pycache__')
179 self.assertFalse(os.path.exists(cachecachedir))
180 # Call compileall again.
181 retcode = subprocess.call(
182 (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
183 self.assertEqual(retcode, 0)
184 self.assertTrue(os.path.exists(cachedir))
185 self.assertFalse(os.path.exists(cachecachedir))
186
Barry Warsaw28a691b2010-04-17 00:19:56 +0000187
Brett Cannonbefb14f2009-02-10 02:10:16 +0000188def test_main():
Barry Warsaw28a691b2010-04-17 00:19:56 +0000189 support.run_unittest(
190 CommandLineTests,
191 CompileallTests,
192 EncodingTest,
193 )
Brett Cannonbefb14f2009-02-10 02:10:16 +0000194
195
196if __name__ == "__main__":
197 test_main()