Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 1 | import compileall |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 2 | import contextlib |
| 3 | import filecmp |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 4 | import importlib.util |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 5 | import io |
| 6 | import itertools |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 7 | import os |
Brett Cannon | 65ed750 | 2015-10-09 15:09:43 -0700 | [diff] [blame] | 8 | import pathlib |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 9 | import py_compile |
| 10 | import shutil |
| 11 | import struct |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 12 | import sys |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 13 | import tempfile |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 14 | import test.test_importlib.util |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 15 | import time |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 16 | import unittest |
| 17 | |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 18 | from unittest import mock, skipUnless |
Asheesh Laroia | bf2e7e5 | 2021-02-07 19:15:51 -0800 | [diff] [blame] | 19 | from concurrent.futures import ProcessPoolExecutor |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 20 | try: |
Asheesh Laroia | bf2e7e5 | 2021-02-07 19:15:51 -0800 | [diff] [blame] | 21 | # compileall relies on ProcessPoolExecutor if ProcessPoolExecutor exists |
| 22 | # and it can function. |
| 23 | from concurrent.futures.process import _check_system_limits |
| 24 | _check_system_limits() |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 25 | _have_multiprocessing = True |
Asheesh Laroia | bf2e7e5 | 2021-02-07 19:15:51 -0800 | [diff] [blame] | 26 | except NotImplementedError: |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 27 | _have_multiprocessing = False |
| 28 | |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 29 | from test import support |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 30 | from test.support import os_helper |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 31 | from test.support import script_helper |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 32 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 33 | from .test_py_compile import without_source_date_epoch |
| 34 | from .test_py_compile import SourceDateEpochTestMeta |
| 35 | |
| 36 | |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 37 | def get_pyc(script, opt): |
| 38 | if not opt: |
| 39 | # Replace None and 0 with '' |
| 40 | opt = '' |
| 41 | return importlib.util.cache_from_source(script, optimization=opt) |
| 42 | |
| 43 | |
| 44 | def get_pycs(script): |
| 45 | return [get_pyc(script, opt) for opt in (0, 1, 2)] |
| 46 | |
| 47 | |
| 48 | def is_hardlink(filename1, filename2): |
| 49 | """Returns True if two files have the same inode (hardlink)""" |
| 50 | inode1 = os.stat(filename1).st_ino |
| 51 | inode2 = os.stat(filename2).st_ino |
| 52 | return inode1 == inode2 |
| 53 | |
| 54 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 55 | class CompileallTestsBase: |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 56 | |
| 57 | def setUp(self): |
| 58 | self.directory = tempfile.mkdtemp() |
| 59 | self.source_path = os.path.join(self.directory, '_test.py') |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 60 | self.bc_path = importlib.util.cache_from_source(self.source_path) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 61 | with open(self.source_path, 'w') as file: |
| 62 | file.write('x = 123\n') |
Matthias Klose | c33b902 | 2010-03-16 00:36:26 +0000 | [diff] [blame] | 63 | self.source_path2 = os.path.join(self.directory, '_test2.py') |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 64 | self.bc_path2 = importlib.util.cache_from_source(self.source_path2) |
Matthias Klose | c33b902 | 2010-03-16 00:36:26 +0000 | [diff] [blame] | 65 | shutil.copyfile(self.source_path, self.source_path2) |
Georg Brandl | 4543846 | 2011-02-07 12:36:54 +0000 | [diff] [blame] | 66 | self.subdirectory = os.path.join(self.directory, '_subdir') |
| 67 | os.mkdir(self.subdirectory) |
| 68 | self.source_path3 = os.path.join(self.subdirectory, '_test3.py') |
| 69 | shutil.copyfile(self.source_path, self.source_path3) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 70 | |
| 71 | def tearDown(self): |
| 72 | shutil.rmtree(self.directory) |
| 73 | |
Brett Cannon | 1e3c3e9 | 2015-12-27 13:17:04 -0800 | [diff] [blame] | 74 | def add_bad_source_file(self): |
| 75 | self.bad_source_path = os.path.join(self.directory, '_test_bad.py') |
| 76 | with open(self.bad_source_path, 'w') as file: |
| 77 | file.write('x (\n') |
| 78 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 79 | def timestamp_metadata(self): |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 80 | with open(self.bc_path, 'rb') as file: |
Benjamin Peterson | 42aa93b | 2017-12-09 10:26:52 -0800 | [diff] [blame] | 81 | data = file.read(12) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 82 | mtime = int(os.stat(self.source_path).st_mtime) |
Benjamin Peterson | 42aa93b | 2017-12-09 10:26:52 -0800 | [diff] [blame] | 83 | compare = struct.pack('<4sll', importlib.util.MAGIC_NUMBER, 0, mtime) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 84 | return data, compare |
| 85 | |
| 86 | def recreation_check(self, metadata): |
| 87 | """Check that compileall recreates bytecode when the new metadata is |
| 88 | used.""" |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 89 | if os.environ.get('SOURCE_DATE_EPOCH'): |
| 90 | raise unittest.SkipTest('SOURCE_DATE_EPOCH is set') |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 91 | py_compile.compile(self.source_path) |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 92 | self.assertEqual(*self.timestamp_metadata()) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 93 | with open(self.bc_path, 'rb') as file: |
| 94 | bc = file.read()[len(metadata):] |
| 95 | with open(self.bc_path, 'wb') as file: |
| 96 | file.write(metadata) |
| 97 | file.write(bc) |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 98 | self.assertNotEqual(*self.timestamp_metadata()) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 99 | compileall.compile_dir(self.directory, force=False, quiet=True) |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 100 | self.assertTrue(*self.timestamp_metadata()) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 101 | |
| 102 | def test_mtime(self): |
| 103 | # Test a change in mtime leads to a new .pyc. |
Benjamin Peterson | 42aa93b | 2017-12-09 10:26:52 -0800 | [diff] [blame] | 104 | self.recreation_check(struct.pack('<4sll', importlib.util.MAGIC_NUMBER, |
| 105 | 0, 1)) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 106 | |
| 107 | def test_magic_number(self): |
| 108 | # Test a change in mtime leads to a new .pyc. |
| 109 | self.recreation_check(b'\0\0\0\0') |
| 110 | |
Matthias Klose | c33b902 | 2010-03-16 00:36:26 +0000 | [diff] [blame] | 111 | def test_compile_files(self): |
| 112 | # Test compiling a single file, and complete directory |
| 113 | for fn in (self.bc_path, self.bc_path2): |
| 114 | try: |
| 115 | os.unlink(fn) |
| 116 | except: |
| 117 | pass |
Brett Cannon | 1e3c3e9 | 2015-12-27 13:17:04 -0800 | [diff] [blame] | 118 | self.assertTrue(compileall.compile_file(self.source_path, |
| 119 | force=False, quiet=True)) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 120 | self.assertTrue(os.path.isfile(self.bc_path) and |
| 121 | not os.path.isfile(self.bc_path2)) |
Matthias Klose | c33b902 | 2010-03-16 00:36:26 +0000 | [diff] [blame] | 122 | os.unlink(self.bc_path) |
Brett Cannon | 1e3c3e9 | 2015-12-27 13:17:04 -0800 | [diff] [blame] | 123 | self.assertTrue(compileall.compile_dir(self.directory, force=False, |
| 124 | quiet=True)) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 125 | self.assertTrue(os.path.isfile(self.bc_path) and |
| 126 | os.path.isfile(self.bc_path2)) |
Matthias Klose | c33b902 | 2010-03-16 00:36:26 +0000 | [diff] [blame] | 127 | os.unlink(self.bc_path) |
| 128 | os.unlink(self.bc_path2) |
Brett Cannon | 1e3c3e9 | 2015-12-27 13:17:04 -0800 | [diff] [blame] | 129 | # Test against bad files |
| 130 | self.add_bad_source_file() |
| 131 | self.assertFalse(compileall.compile_file(self.bad_source_path, |
| 132 | force=False, quiet=2)) |
| 133 | self.assertFalse(compileall.compile_dir(self.directory, |
| 134 | force=False, quiet=2)) |
| 135 | |
Berker Peksag | 812a2b6 | 2016-10-01 00:54:18 +0300 | [diff] [blame] | 136 | def test_compile_file_pathlike(self): |
| 137 | self.assertFalse(os.path.isfile(self.bc_path)) |
| 138 | # we should also test the output |
| 139 | with support.captured_stdout() as stdout: |
| 140 | self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path))) |
Berker Peksag | d8e9713 | 2016-10-01 02:44:37 +0300 | [diff] [blame] | 141 | self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)') |
Berker Peksag | 812a2b6 | 2016-10-01 00:54:18 +0300 | [diff] [blame] | 142 | self.assertTrue(os.path.isfile(self.bc_path)) |
| 143 | |
| 144 | def test_compile_file_pathlike_ddir(self): |
| 145 | self.assertFalse(os.path.isfile(self.bc_path)) |
| 146 | self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path), |
| 147 | ddir=pathlib.Path('ddir_path'), |
| 148 | quiet=2)) |
| 149 | self.assertTrue(os.path.isfile(self.bc_path)) |
| 150 | |
Brett Cannon | 1e3c3e9 | 2015-12-27 13:17:04 -0800 | [diff] [blame] | 151 | def test_compile_path(self): |
Berker Peksag | 408b78c | 2016-09-28 17:38:53 +0300 | [diff] [blame] | 152 | with test.test_importlib.util.import_state(path=[self.directory]): |
| 153 | self.assertTrue(compileall.compile_path(quiet=2)) |
Brett Cannon | 1e3c3e9 | 2015-12-27 13:17:04 -0800 | [diff] [blame] | 154 | |
| 155 | with test.test_importlib.util.import_state(path=[self.directory]): |
| 156 | self.add_bad_source_file() |
| 157 | self.assertFalse(compileall.compile_path(skip_curdir=False, |
| 158 | force=True, quiet=2)) |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 159 | |
Barry Warsaw | c8a99de | 2010-04-29 18:43:10 +0000 | [diff] [blame] | 160 | def test_no_pycache_in_non_package(self): |
| 161 | # Bug 8563 reported that __pycache__ directories got created by |
| 162 | # compile_file() for non-.py files. |
| 163 | data_dir = os.path.join(self.directory, 'data') |
| 164 | data_file = os.path.join(data_dir, 'file') |
| 165 | os.mkdir(data_dir) |
| 166 | # touch data/file |
| 167 | with open(data_file, 'w'): |
| 168 | pass |
| 169 | compileall.compile_file(data_file) |
| 170 | self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__'))) |
| 171 | |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 172 | def test_optimize(self): |
| 173 | # make sure compiling with different optimization settings than the |
| 174 | # interpreter's creates the correct file names |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 175 | optimize, opt = (1, 1) if __debug__ else (0, '') |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 176 | compileall.compile_dir(self.directory, quiet=True, optimize=optimize) |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 177 | cached = importlib.util.cache_from_source(self.source_path, |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 178 | optimization=opt) |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 179 | self.assertTrue(os.path.isfile(cached)) |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 180 | cached2 = importlib.util.cache_from_source(self.source_path2, |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 181 | optimization=opt) |
Georg Brandl | 4543846 | 2011-02-07 12:36:54 +0000 | [diff] [blame] | 182 | self.assertTrue(os.path.isfile(cached2)) |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 183 | cached3 = importlib.util.cache_from_source(self.source_path3, |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 184 | optimization=opt) |
Georg Brandl | 4543846 | 2011-02-07 12:36:54 +0000 | [diff] [blame] | 185 | self.assertTrue(os.path.isfile(cached3)) |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 186 | |
Berker Peksag | 812a2b6 | 2016-10-01 00:54:18 +0300 | [diff] [blame] | 187 | def test_compile_dir_pathlike(self): |
| 188 | self.assertFalse(os.path.isfile(self.bc_path)) |
| 189 | with support.captured_stdout() as stdout: |
| 190 | compileall.compile_dir(pathlib.Path(self.directory)) |
Berker Peksag | d8e9713 | 2016-10-01 02:44:37 +0300 | [diff] [blame] | 191 | line = stdout.getvalue().splitlines()[0] |
| 192 | self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)') |
Berker Peksag | 812a2b6 | 2016-10-01 00:54:18 +0300 | [diff] [blame] | 193 | self.assertTrue(os.path.isfile(self.bc_path)) |
| 194 | |
Asheesh Laroia | bf2e7e5 | 2021-02-07 19:15:51 -0800 | [diff] [blame] | 195 | @skipUnless(_have_multiprocessing, "requires multiprocessing") |
Dustin Spicuzza | 1d817e4 | 2018-11-23 12:06:55 -0500 | [diff] [blame] | 196 | @mock.patch('concurrent.futures.ProcessPoolExecutor') |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 197 | def test_compile_pool_called(self, pool_mock): |
| 198 | compileall.compile_dir(self.directory, quiet=True, workers=5) |
| 199 | self.assertTrue(pool_mock.called) |
| 200 | |
| 201 | def test_compile_workers_non_positive(self): |
| 202 | with self.assertRaisesRegex(ValueError, |
| 203 | "workers must be greater or equal to 0"): |
| 204 | compileall.compile_dir(self.directory, workers=-1) |
| 205 | |
Asheesh Laroia | bf2e7e5 | 2021-02-07 19:15:51 -0800 | [diff] [blame] | 206 | @skipUnless(_have_multiprocessing, "requires multiprocessing") |
Dustin Spicuzza | 1d817e4 | 2018-11-23 12:06:55 -0500 | [diff] [blame] | 207 | @mock.patch('concurrent.futures.ProcessPoolExecutor') |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 208 | def test_compile_workers_cpu_count(self, pool_mock): |
| 209 | compileall.compile_dir(self.directory, quiet=True, workers=0) |
| 210 | self.assertEqual(pool_mock.call_args[1]['max_workers'], None) |
| 211 | |
Asheesh Laroia | bf2e7e5 | 2021-02-07 19:15:51 -0800 | [diff] [blame] | 212 | @skipUnless(_have_multiprocessing, "requires multiprocessing") |
Dustin Spicuzza | 1d817e4 | 2018-11-23 12:06:55 -0500 | [diff] [blame] | 213 | @mock.patch('concurrent.futures.ProcessPoolExecutor') |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 214 | @mock.patch('compileall.compile_file') |
| 215 | def test_compile_one_worker(self, compile_file_mock, pool_mock): |
| 216 | compileall.compile_dir(self.directory, quiet=True) |
| 217 | self.assertFalse(pool_mock.called) |
| 218 | self.assertTrue(compile_file_mock.called) |
| 219 | |
Dustin Spicuzza | 1d817e4 | 2018-11-23 12:06:55 -0500 | [diff] [blame] | 220 | @mock.patch('concurrent.futures.ProcessPoolExecutor', new=None) |
Berker Peksag | d86ef05 | 2015-04-22 09:39:19 +0300 | [diff] [blame] | 221 | @mock.patch('compileall.compile_file') |
| 222 | def test_compile_missing_multiprocessing(self, compile_file_mock): |
| 223 | compileall.compile_dir(self.directory, quiet=True, workers=5) |
| 224 | self.assertTrue(compile_file_mock.called) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 225 | |
Petr Viktorin | 4267c98 | 2019-09-26 11:53:51 +0200 | [diff] [blame] | 226 | def test_compile_dir_maxlevels(self): |
Victor Stinner | eb1dda2 | 2019-10-15 11:26:13 +0200 | [diff] [blame] | 227 | # Test the actual impact of maxlevels parameter |
| 228 | depth = 3 |
| 229 | path = self.directory |
| 230 | for i in range(1, depth + 1): |
| 231 | path = os.path.join(path, f"dir_{i}") |
| 232 | source = os.path.join(path, 'script.py') |
| 233 | os.mkdir(path) |
| 234 | shutil.copyfile(self.source_path, source) |
| 235 | pyc_filename = importlib.util.cache_from_source(source) |
| 236 | |
| 237 | compileall.compile_dir(self.directory, quiet=True, maxlevels=depth - 1) |
| 238 | self.assertFalse(os.path.isfile(pyc_filename)) |
| 239 | |
| 240 | compileall.compile_dir(self.directory, quiet=True, maxlevels=depth) |
| 241 | self.assertTrue(os.path.isfile(pyc_filename)) |
Lumír 'Frenzy' Balhar | 8e7bb99 | 2019-09-26 08:28:26 +0200 | [diff] [blame] | 242 | |
Gregory P. Smith | 0267335 | 2020-02-28 17:28:37 -0800 | [diff] [blame] | 243 | def _test_ddir_only(self, *, ddir, parallel=True): |
| 244 | """Recursive compile_dir ddir must contain package paths; bpo39769.""" |
| 245 | fullpath = ["test", "foo"] |
| 246 | path = self.directory |
| 247 | mods = [] |
| 248 | for subdir in fullpath: |
| 249 | path = os.path.join(path, subdir) |
| 250 | os.mkdir(path) |
| 251 | script_helper.make_script(path, "__init__", "") |
| 252 | mods.append(script_helper.make_script(path, "mod", |
| 253 | "def fn(): 1/0\nfn()\n")) |
| 254 | compileall.compile_dir( |
| 255 | self.directory, quiet=True, ddir=ddir, |
| 256 | workers=2 if parallel else 1) |
| 257 | self.assertTrue(mods) |
| 258 | for mod in mods: |
| 259 | self.assertTrue(mod.startswith(self.directory), mod) |
| 260 | modcode = importlib.util.cache_from_source(mod) |
| 261 | modpath = mod[len(self.directory+os.sep):] |
| 262 | _, _, err = script_helper.assert_python_failure(modcode) |
| 263 | expected_in = os.path.join(ddir, modpath) |
| 264 | mod_code_obj = test.test_importlib.util.get_code_from_pyc(modcode) |
| 265 | self.assertEqual(mod_code_obj.co_filename, expected_in) |
| 266 | self.assertIn(f'"{expected_in}"', os.fsdecode(err)) |
| 267 | |
| 268 | def test_ddir_only_one_worker(self): |
| 269 | """Recursive compile_dir ddir= contains package paths; bpo39769.""" |
| 270 | return self._test_ddir_only(ddir="<a prefix>", parallel=False) |
| 271 | |
| 272 | def test_ddir_multiple_workers(self): |
| 273 | """Recursive compile_dir ddir= contains package paths; bpo39769.""" |
| 274 | return self._test_ddir_only(ddir="<a prefix>", parallel=True) |
| 275 | |
| 276 | def test_ddir_empty_only_one_worker(self): |
| 277 | """Recursive compile_dir ddir='' contains package paths; bpo39769.""" |
| 278 | return self._test_ddir_only(ddir="", parallel=False) |
| 279 | |
| 280 | def test_ddir_empty_multiple_workers(self): |
| 281 | """Recursive compile_dir ddir='' contains package paths; bpo39769.""" |
| 282 | return self._test_ddir_only(ddir="", parallel=True) |
| 283 | |
Lumír 'Frenzy' Balhar | 8e7bb99 | 2019-09-26 08:28:26 +0200 | [diff] [blame] | 284 | def test_strip_only(self): |
| 285 | fullpath = ["test", "build", "real", "path"] |
| 286 | path = os.path.join(self.directory, *fullpath) |
| 287 | os.makedirs(path) |
| 288 | script = script_helper.make_script(path, "test", "1 / 0") |
| 289 | bc = importlib.util.cache_from_source(script) |
| 290 | stripdir = os.path.join(self.directory, *fullpath[:2]) |
| 291 | compileall.compile_dir(path, quiet=True, stripdir=stripdir) |
| 292 | rc, out, err = script_helper.assert_python_failure(bc) |
| 293 | expected_in = os.path.join(*fullpath[2:]) |
| 294 | self.assertIn( |
| 295 | expected_in, |
| 296 | str(err, encoding=sys.getdefaultencoding()) |
| 297 | ) |
| 298 | self.assertNotIn( |
| 299 | stripdir, |
| 300 | str(err, encoding=sys.getdefaultencoding()) |
| 301 | ) |
| 302 | |
| 303 | def test_prepend_only(self): |
| 304 | fullpath = ["test", "build", "real", "path"] |
| 305 | path = os.path.join(self.directory, *fullpath) |
| 306 | os.makedirs(path) |
| 307 | script = script_helper.make_script(path, "test", "1 / 0") |
| 308 | bc = importlib.util.cache_from_source(script) |
| 309 | prependdir = "/foo" |
| 310 | compileall.compile_dir(path, quiet=True, prependdir=prependdir) |
| 311 | rc, out, err = script_helper.assert_python_failure(bc) |
| 312 | expected_in = os.path.join(prependdir, self.directory, *fullpath) |
| 313 | self.assertIn( |
| 314 | expected_in, |
| 315 | str(err, encoding=sys.getdefaultencoding()) |
| 316 | ) |
| 317 | |
| 318 | def test_strip_and_prepend(self): |
| 319 | fullpath = ["test", "build", "real", "path"] |
| 320 | path = os.path.join(self.directory, *fullpath) |
| 321 | os.makedirs(path) |
| 322 | script = script_helper.make_script(path, "test", "1 / 0") |
| 323 | bc = importlib.util.cache_from_source(script) |
| 324 | stripdir = os.path.join(self.directory, *fullpath[:2]) |
| 325 | prependdir = "/foo" |
| 326 | compileall.compile_dir(path, quiet=True, |
| 327 | stripdir=stripdir, prependdir=prependdir) |
| 328 | rc, out, err = script_helper.assert_python_failure(bc) |
| 329 | expected_in = os.path.join(prependdir, *fullpath[2:]) |
| 330 | self.assertIn( |
| 331 | expected_in, |
| 332 | str(err, encoding=sys.getdefaultencoding()) |
| 333 | ) |
| 334 | self.assertNotIn( |
| 335 | stripdir, |
| 336 | str(err, encoding=sys.getdefaultencoding()) |
| 337 | ) |
| 338 | |
| 339 | def test_strip_prepend_and_ddir(self): |
| 340 | fullpath = ["test", "build", "real", "path", "ddir"] |
| 341 | path = os.path.join(self.directory, *fullpath) |
| 342 | os.makedirs(path) |
| 343 | script_helper.make_script(path, "test", "1 / 0") |
| 344 | with self.assertRaises(ValueError): |
| 345 | compileall.compile_dir(path, quiet=True, ddir="/bar", |
| 346 | stripdir="/foo", prependdir="/bar") |
| 347 | |
| 348 | def test_multiple_optimization_levels(self): |
| 349 | script = script_helper.make_script(self.directory, |
| 350 | "test_optimization", |
| 351 | "a = 0") |
| 352 | bc = [] |
| 353 | for opt_level in "", 1, 2, 3: |
| 354 | bc.append(importlib.util.cache_from_source(script, |
| 355 | optimization=opt_level)) |
| 356 | test_combinations = [[0, 1], [1, 2], [0, 2], [0, 1, 2]] |
| 357 | for opt_combination in test_combinations: |
| 358 | compileall.compile_file(script, quiet=True, |
| 359 | optimize=opt_combination) |
| 360 | for opt_level in opt_combination: |
| 361 | self.assertTrue(os.path.isfile(bc[opt_level])) |
| 362 | try: |
| 363 | os.unlink(bc[opt_level]) |
| 364 | except Exception: |
| 365 | pass |
| 366 | |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 367 | @os_helper.skip_unless_symlink |
Lumír 'Frenzy' Balhar | 8e7bb99 | 2019-09-26 08:28:26 +0200 | [diff] [blame] | 368 | def test_ignore_symlink_destination(self): |
| 369 | # Create folders for allowed files, symlinks and prohibited area |
| 370 | allowed_path = os.path.join(self.directory, "test", "dir", "allowed") |
| 371 | symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks") |
| 372 | prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited") |
| 373 | os.makedirs(allowed_path) |
| 374 | os.makedirs(symlinks_path) |
| 375 | os.makedirs(prohibited_path) |
| 376 | |
| 377 | # Create scripts and symlinks and remember their byte-compiled versions |
| 378 | allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0") |
| 379 | prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0") |
| 380 | allowed_symlink = os.path.join(symlinks_path, "test_allowed.py") |
| 381 | prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py") |
| 382 | os.symlink(allowed_script, allowed_symlink) |
| 383 | os.symlink(prohibited_script, prohibited_symlink) |
| 384 | allowed_bc = importlib.util.cache_from_source(allowed_symlink) |
| 385 | prohibited_bc = importlib.util.cache_from_source(prohibited_symlink) |
| 386 | |
| 387 | compileall.compile_dir(symlinks_path, quiet=True, limit_sl_dest=allowed_path) |
| 388 | |
| 389 | self.assertTrue(os.path.isfile(allowed_bc)) |
| 390 | self.assertFalse(os.path.isfile(prohibited_bc)) |
| 391 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 392 | |
| 393 | class CompileallTestsWithSourceEpoch(CompileallTestsBase, |
| 394 | unittest.TestCase, |
| 395 | metaclass=SourceDateEpochTestMeta, |
| 396 | source_date_epoch=True): |
| 397 | pass |
| 398 | |
| 399 | |
| 400 | class CompileallTestsWithoutSourceEpoch(CompileallTestsBase, |
| 401 | unittest.TestCase, |
| 402 | metaclass=SourceDateEpochTestMeta, |
| 403 | source_date_epoch=False): |
| 404 | pass |
| 405 | |
| 406 | |
Martin v. Löwis | 4b00307 | 2010-03-16 13:19:21 +0000 | [diff] [blame] | 407 | class EncodingTest(unittest.TestCase): |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 408 | """Issue 6716: compileall should escape source code when printing errors |
| 409 | to stdout.""" |
Martin v. Löwis | 4b00307 | 2010-03-16 13:19:21 +0000 | [diff] [blame] | 410 | |
| 411 | def setUp(self): |
| 412 | self.directory = tempfile.mkdtemp() |
| 413 | self.source_path = os.path.join(self.directory, '_test.py') |
| 414 | with open(self.source_path, 'w', encoding='utf-8') as file: |
| 415 | file.write('# -*- coding: utf-8 -*-\n') |
| 416 | file.write('print u"\u20ac"\n') |
| 417 | |
| 418 | def tearDown(self): |
| 419 | shutil.rmtree(self.directory) |
| 420 | |
| 421 | def test_error(self): |
| 422 | try: |
| 423 | orig_stdout = sys.stdout |
| 424 | sys.stdout = io.TextIOWrapper(io.BytesIO(),encoding='ascii') |
| 425 | compileall.compile_dir(self.directory) |
| 426 | finally: |
| 427 | sys.stdout = orig_stdout |
| 428 | |
Barry Warsaw | c8a99de | 2010-04-29 18:43:10 +0000 | [diff] [blame] | 429 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 430 | class CommandLineTestsBase: |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 431 | """Test compileall's CLI.""" |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 432 | |
Brett Cannon | 65ed750 | 2015-10-09 15:09:43 -0700 | [diff] [blame] | 433 | @classmethod |
| 434 | def setUpClass(cls): |
| 435 | for path in filter(os.path.isdir, sys.path): |
| 436 | directory_created = False |
| 437 | directory = pathlib.Path(path) / '__pycache__' |
| 438 | path = directory / 'test.try' |
| 439 | try: |
| 440 | if not directory.is_dir(): |
| 441 | directory.mkdir() |
| 442 | directory_created = True |
| 443 | with path.open('w') as file: |
| 444 | file.write('# for test_compileall') |
| 445 | except OSError: |
| 446 | sys_path_writable = False |
| 447 | break |
| 448 | finally: |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 449 | os_helper.unlink(str(path)) |
Brett Cannon | 65ed750 | 2015-10-09 15:09:43 -0700 | [diff] [blame] | 450 | if directory_created: |
| 451 | directory.rmdir() |
| 452 | else: |
| 453 | sys_path_writable = True |
| 454 | cls._sys_path_writable = sys_path_writable |
| 455 | |
| 456 | def _skip_if_sys_path_not_writable(self): |
| 457 | if not self._sys_path_writable: |
| 458 | raise unittest.SkipTest('not all entries on sys.path are writable') |
| 459 | |
Benjamin Peterson | a820c7c | 2012-09-25 11:42:35 -0400 | [diff] [blame] | 460 | def _get_run_args(self, args): |
Victor Stinner | 9def284 | 2016-01-18 12:15:08 +0100 | [diff] [blame] | 461 | return [*support.optim_args_from_interpreter_flags(), |
| 462 | '-S', '-m', 'compileall', |
| 463 | *args] |
Benjamin Peterson | a820c7c | 2012-09-25 11:42:35 -0400 | [diff] [blame] | 464 | |
R. David Murray | 5317e9c | 2010-12-16 19:08:51 +0000 | [diff] [blame] | 465 | def assertRunOK(self, *args, **env_vars): |
| 466 | rc, out, err = script_helper.assert_python_ok( |
Serhiy Storchaka | 700cfa8 | 2020-06-25 17:56:31 +0300 | [diff] [blame] | 467 | *self._get_run_args(args), **env_vars, |
| 468 | PYTHONIOENCODING='utf-8') |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 469 | self.assertEqual(b'', err) |
| 470 | return out |
| 471 | |
R. David Murray | 5317e9c | 2010-12-16 19:08:51 +0000 | [diff] [blame] | 472 | def assertRunNotOK(self, *args, **env_vars): |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 473 | rc, out, err = script_helper.assert_python_failure( |
Serhiy Storchaka | 700cfa8 | 2020-06-25 17:56:31 +0300 | [diff] [blame] | 474 | *self._get_run_args(args), **env_vars, |
| 475 | PYTHONIOENCODING='utf-8') |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 476 | return rc, out, err |
| 477 | |
| 478 | def assertCompiled(self, fn): |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 479 | path = importlib.util.cache_from_source(fn) |
| 480 | self.assertTrue(os.path.exists(path)) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 481 | |
| 482 | def assertNotCompiled(self, fn): |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 483 | path = importlib.util.cache_from_source(fn) |
| 484 | self.assertFalse(os.path.exists(path)) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 485 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 486 | def setUp(self): |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 487 | self.directory = tempfile.mkdtemp() |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 488 | self.addCleanup(os_helper.rmtree, self.directory) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 489 | self.pkgdir = os.path.join(self.directory, 'foo') |
| 490 | os.mkdir(self.pkgdir) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 491 | self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__') |
| 492 | # Create the __init__.py and a package module. |
| 493 | self.initfn = script_helper.make_script(self.pkgdir, '__init__', '') |
| 494 | self.barfn = script_helper.make_script(self.pkgdir, 'bar', '') |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 495 | |
R. David Murray | 5317e9c | 2010-12-16 19:08:51 +0000 | [diff] [blame] | 496 | def test_no_args_compiles_path(self): |
| 497 | # Note that -l is implied for the no args case. |
Brett Cannon | 65ed750 | 2015-10-09 15:09:43 -0700 | [diff] [blame] | 498 | self._skip_if_sys_path_not_writable() |
R. David Murray | 5317e9c | 2010-12-16 19:08:51 +0000 | [diff] [blame] | 499 | bazfn = script_helper.make_script(self.directory, 'baz', '') |
| 500 | self.assertRunOK(PYTHONPATH=self.directory) |
| 501 | self.assertCompiled(bazfn) |
| 502 | self.assertNotCompiled(self.initfn) |
| 503 | self.assertNotCompiled(self.barfn) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 504 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 505 | @without_source_date_epoch # timestamp invalidation test |
R David Murray | 8a1d1e6 | 2013-12-15 20:49:38 -0500 | [diff] [blame] | 506 | def test_no_args_respects_force_flag(self): |
Brett Cannon | 65ed750 | 2015-10-09 15:09:43 -0700 | [diff] [blame] | 507 | self._skip_if_sys_path_not_writable() |
R David Murray | 8a1d1e6 | 2013-12-15 20:49:38 -0500 | [diff] [blame] | 508 | bazfn = script_helper.make_script(self.directory, 'baz', '') |
| 509 | self.assertRunOK(PYTHONPATH=self.directory) |
R David Murray | 755d5ea | 2013-12-15 20:56:00 -0500 | [diff] [blame] | 510 | pycpath = importlib.util.cache_from_source(bazfn) |
R David Murray | 8a1d1e6 | 2013-12-15 20:49:38 -0500 | [diff] [blame] | 511 | # Set atime/mtime backward to avoid file timestamp resolution issues |
| 512 | os.utime(pycpath, (time.time()-60,)*2) |
| 513 | mtime = os.stat(pycpath).st_mtime |
| 514 | # Without force, no recompilation |
| 515 | self.assertRunOK(PYTHONPATH=self.directory) |
| 516 | mtime2 = os.stat(pycpath).st_mtime |
| 517 | self.assertEqual(mtime, mtime2) |
| 518 | # Now force it. |
| 519 | self.assertRunOK('-f', PYTHONPATH=self.directory) |
| 520 | mtime2 = os.stat(pycpath).st_mtime |
| 521 | self.assertNotEqual(mtime, mtime2) |
| 522 | |
| 523 | def test_no_args_respects_quiet_flag(self): |
Brett Cannon | 65ed750 | 2015-10-09 15:09:43 -0700 | [diff] [blame] | 524 | self._skip_if_sys_path_not_writable() |
R David Murray | 8a1d1e6 | 2013-12-15 20:49:38 -0500 | [diff] [blame] | 525 | script_helper.make_script(self.directory, 'baz', '') |
| 526 | noisy = self.assertRunOK(PYTHONPATH=self.directory) |
| 527 | self.assertIn(b'Listing ', noisy) |
| 528 | quiet = self.assertRunOK('-q', PYTHONPATH=self.directory) |
| 529 | self.assertNotIn(b'Listing ', quiet) |
| 530 | |
Georg Brandl | 1463a3f | 2010-10-14 07:42:27 +0000 | [diff] [blame] | 531 | # Ensure that the default behavior of compileall's CLI is to create |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 532 | # PEP 3147/PEP 488 pyc files. |
Georg Brandl | 1463a3f | 2010-10-14 07:42:27 +0000 | [diff] [blame] | 533 | for name, ext, switch in [ |
| 534 | ('normal', 'pyc', []), |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 535 | ('optimize', 'opt-1.pyc', ['-O']), |
| 536 | ('doubleoptimize', 'opt-2.pyc', ['-OO']), |
Georg Brandl | 1463a3f | 2010-10-14 07:42:27 +0000 | [diff] [blame] | 537 | ]: |
| 538 | def f(self, ext=ext, switch=switch): |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 539 | script_helper.assert_python_ok(*(switch + |
| 540 | ['-m', 'compileall', '-q', self.pkgdir])) |
Georg Brandl | 1463a3f | 2010-10-14 07:42:27 +0000 | [diff] [blame] | 541 | # Verify the __pycache__ directory contents. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 542 | self.assertTrue(os.path.exists(self.pkgdir_cachedir)) |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 543 | expected = sorted(base.format(sys.implementation.cache_tag, ext) |
| 544 | for base in ('__init__.{}.{}', 'bar.{}.{}')) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 545 | self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected) |
Georg Brandl | 1463a3f | 2010-10-14 07:42:27 +0000 | [diff] [blame] | 546 | # Make sure there are no .pyc files in the source directory. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 547 | self.assertFalse([fn for fn in os.listdir(self.pkgdir) |
| 548 | if fn.endswith(ext)]) |
Georg Brandl | 1463a3f | 2010-10-14 07:42:27 +0000 | [diff] [blame] | 549 | locals()['test_pep3147_paths_' + name] = f |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 550 | |
| 551 | def test_legacy_paths(self): |
| 552 | # Ensure that with the proper switch, compileall leaves legacy |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 553 | # pyc files, and no __pycache__ directory. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 554 | self.assertRunOK('-b', '-q', self.pkgdir) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 555 | # Verify the __pycache__ directory contents. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 556 | self.assertFalse(os.path.exists(self.pkgdir_cachedir)) |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 557 | expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', |
| 558 | 'bar.pyc']) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 559 | self.assertEqual(sorted(os.listdir(self.pkgdir)), expected) |
| 560 | |
Barry Warsaw | c04317f | 2010-04-26 15:59:03 +0000 | [diff] [blame] | 561 | def test_multiple_runs(self): |
| 562 | # Bug 8527 reported that multiple calls produced empty |
| 563 | # __pycache__/__pycache__ directories. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 564 | self.assertRunOK('-q', self.pkgdir) |
Barry Warsaw | c04317f | 2010-04-26 15:59:03 +0000 | [diff] [blame] | 565 | # Verify the __pycache__ directory contents. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 566 | self.assertTrue(os.path.exists(self.pkgdir_cachedir)) |
| 567 | cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__') |
Barry Warsaw | c04317f | 2010-04-26 15:59:03 +0000 | [diff] [blame] | 568 | self.assertFalse(os.path.exists(cachecachedir)) |
| 569 | # Call compileall again. |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 570 | self.assertRunOK('-q', self.pkgdir) |
| 571 | self.assertTrue(os.path.exists(self.pkgdir_cachedir)) |
Barry Warsaw | c04317f | 2010-04-26 15:59:03 +0000 | [diff] [blame] | 572 | self.assertFalse(os.path.exists(cachecachedir)) |
| 573 | |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 574 | @without_source_date_epoch # timestamp invalidation test |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 575 | def test_force(self): |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 576 | self.assertRunOK('-q', self.pkgdir) |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 577 | pycpath = importlib.util.cache_from_source(self.barfn) |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 578 | # set atime/mtime backward to avoid file timestamp resolution issues |
| 579 | os.utime(pycpath, (time.time()-60,)*2) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 580 | mtime = os.stat(pycpath).st_mtime |
| 581 | # without force, no recompilation |
| 582 | self.assertRunOK('-q', self.pkgdir) |
| 583 | mtime2 = os.stat(pycpath).st_mtime |
| 584 | self.assertEqual(mtime, mtime2) |
| 585 | # now force it. |
| 586 | self.assertRunOK('-q', '-f', self.pkgdir) |
| 587 | mtime2 = os.stat(pycpath).st_mtime |
| 588 | self.assertNotEqual(mtime, mtime2) |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 589 | |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 590 | def test_recursion_control(self): |
| 591 | subpackage = os.path.join(self.pkgdir, 'spam') |
| 592 | os.mkdir(subpackage) |
| 593 | subinitfn = script_helper.make_script(subpackage, '__init__', '') |
| 594 | hamfn = script_helper.make_script(subpackage, 'ham', '') |
| 595 | self.assertRunOK('-q', '-l', self.pkgdir) |
| 596 | self.assertNotCompiled(subinitfn) |
| 597 | self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__'))) |
| 598 | self.assertRunOK('-q', self.pkgdir) |
| 599 | self.assertCompiled(subinitfn) |
| 600 | self.assertCompiled(hamfn) |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 601 | |
Benjamin Peterson | 344ff4a | 2014-08-19 16:13:26 -0500 | [diff] [blame] | 602 | def test_recursion_limit(self): |
| 603 | subpackage = os.path.join(self.pkgdir, 'spam') |
| 604 | subpackage2 = os.path.join(subpackage, 'ham') |
| 605 | subpackage3 = os.path.join(subpackage2, 'eggs') |
| 606 | for pkg in (subpackage, subpackage2, subpackage3): |
| 607 | script_helper.make_pkg(pkg) |
| 608 | |
| 609 | subinitfn = os.path.join(subpackage, '__init__.py') |
| 610 | hamfn = script_helper.make_script(subpackage, 'ham', '') |
| 611 | spamfn = script_helper.make_script(subpackage2, 'spam', '') |
| 612 | eggfn = script_helper.make_script(subpackage3, 'egg', '') |
| 613 | |
| 614 | self.assertRunOK('-q', '-r 0', self.pkgdir) |
| 615 | self.assertNotCompiled(subinitfn) |
| 616 | self.assertFalse( |
| 617 | os.path.exists(os.path.join(subpackage, '__pycache__'))) |
| 618 | |
| 619 | self.assertRunOK('-q', '-r 1', self.pkgdir) |
| 620 | self.assertCompiled(subinitfn) |
| 621 | self.assertCompiled(hamfn) |
| 622 | self.assertNotCompiled(spamfn) |
| 623 | |
| 624 | self.assertRunOK('-q', '-r 2', self.pkgdir) |
| 625 | self.assertCompiled(subinitfn) |
| 626 | self.assertCompiled(hamfn) |
| 627 | self.assertCompiled(spamfn) |
| 628 | self.assertNotCompiled(eggfn) |
| 629 | |
| 630 | self.assertRunOK('-q', '-r 5', self.pkgdir) |
| 631 | self.assertCompiled(subinitfn) |
| 632 | self.assertCompiled(hamfn) |
| 633 | self.assertCompiled(spamfn) |
| 634 | self.assertCompiled(eggfn) |
| 635 | |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 636 | @os_helper.skip_unless_symlink |
Lumír 'Frenzy' Balhar | 8e7bb99 | 2019-09-26 08:28:26 +0200 | [diff] [blame] | 637 | def test_symlink_loop(self): |
| 638 | # Currently, compileall ignores symlinks to directories. |
| 639 | # If that limitation is ever lifted, it should protect against |
| 640 | # recursion in symlink loops. |
| 641 | pkg = os.path.join(self.pkgdir, 'spam') |
| 642 | script_helper.make_pkg(pkg) |
| 643 | os.symlink('.', os.path.join(pkg, 'evil')) |
| 644 | os.symlink('.', os.path.join(pkg, 'evil2')) |
| 645 | self.assertRunOK('-q', self.pkgdir) |
| 646 | self.assertCompiled(os.path.join( |
| 647 | self.pkgdir, 'spam', 'evil', 'evil2', '__init__.py' |
| 648 | )) |
| 649 | |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 650 | def test_quiet(self): |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 651 | noisy = self.assertRunOK(self.pkgdir) |
| 652 | quiet = self.assertRunOK('-q', self.pkgdir) |
| 653 | self.assertNotEqual(b'', noisy) |
| 654 | self.assertEqual(b'', quiet) |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 655 | |
Berker Peksag | 6554b86 | 2014-10-15 11:10:57 +0300 | [diff] [blame] | 656 | def test_silent(self): |
| 657 | script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax') |
| 658 | _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir) |
| 659 | _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir) |
| 660 | self.assertNotEqual(b'', quiet) |
| 661 | self.assertEqual(b'', silent) |
| 662 | |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 663 | def test_regexp(self): |
R David Murray | ee1a7cb | 2011-07-01 14:55:43 -0400 | [diff] [blame] | 664 | self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 665 | self.assertNotCompiled(self.barfn) |
| 666 | self.assertCompiled(self.initfn) |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 667 | |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 668 | def test_multiple_dirs(self): |
| 669 | pkgdir2 = os.path.join(self.directory, 'foo2') |
| 670 | os.mkdir(pkgdir2) |
| 671 | init2fn = script_helper.make_script(pkgdir2, '__init__', '') |
| 672 | bar2fn = script_helper.make_script(pkgdir2, 'bar2', '') |
| 673 | self.assertRunOK('-q', self.pkgdir, pkgdir2) |
| 674 | self.assertCompiled(self.initfn) |
| 675 | self.assertCompiled(self.barfn) |
| 676 | self.assertCompiled(init2fn) |
| 677 | self.assertCompiled(bar2fn) |
| 678 | |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 679 | def test_d_compile_error(self): |
| 680 | script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax') |
| 681 | rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir) |
| 682 | self.assertRegex(out, b'File "dinsdale') |
| 683 | |
| 684 | def test_d_runtime_error(self): |
| 685 | bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception') |
| 686 | self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir) |
| 687 | fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz') |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 688 | pyc = importlib.util.cache_from_source(bazfn) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 689 | os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc')) |
| 690 | os.remove(bazfn) |
Victor Stinner | e8785ff | 2013-10-12 14:44:01 +0200 | [diff] [blame] | 691 | rc, out, err = script_helper.assert_python_failure(fn, __isolated=False) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 692 | self.assertRegex(err, b'File "dinsdale') |
| 693 | |
| 694 | def test_include_bad_file(self): |
| 695 | rc, out, err = self.assertRunNotOK( |
| 696 | '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir) |
| 697 | self.assertRegex(out, b'rror.*nosuchfile') |
| 698 | self.assertNotRegex(err, b'Traceback') |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 699 | self.assertFalse(os.path.exists(importlib.util.cache_from_source( |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 700 | self.pkgdir_cachedir))) |
| 701 | |
| 702 | def test_include_file_with_arg(self): |
| 703 | f1 = script_helper.make_script(self.pkgdir, 'f1', '') |
| 704 | f2 = script_helper.make_script(self.pkgdir, 'f2', '') |
| 705 | f3 = script_helper.make_script(self.pkgdir, 'f3', '') |
| 706 | f4 = script_helper.make_script(self.pkgdir, 'f4', '') |
| 707 | with open(os.path.join(self.directory, 'l1'), 'w') as l1: |
| 708 | l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep) |
| 709 | l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep) |
| 710 | self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4) |
| 711 | self.assertCompiled(f1) |
| 712 | self.assertCompiled(f2) |
| 713 | self.assertNotCompiled(f3) |
| 714 | self.assertCompiled(f4) |
| 715 | |
| 716 | def test_include_file_no_arg(self): |
| 717 | f1 = script_helper.make_script(self.pkgdir, 'f1', '') |
| 718 | f2 = script_helper.make_script(self.pkgdir, 'f2', '') |
| 719 | f3 = script_helper.make_script(self.pkgdir, 'f3', '') |
| 720 | f4 = script_helper.make_script(self.pkgdir, 'f4', '') |
| 721 | with open(os.path.join(self.directory, 'l1'), 'w') as l1: |
| 722 | l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep) |
| 723 | self.assertRunOK('-i', os.path.join(self.directory, 'l1')) |
| 724 | self.assertNotCompiled(f1) |
| 725 | self.assertCompiled(f2) |
| 726 | self.assertNotCompiled(f3) |
| 727 | self.assertNotCompiled(f4) |
| 728 | |
| 729 | def test_include_on_stdin(self): |
| 730 | f1 = script_helper.make_script(self.pkgdir, 'f1', '') |
| 731 | f2 = script_helper.make_script(self.pkgdir, 'f2', '') |
| 732 | f3 = script_helper.make_script(self.pkgdir, 'f3', '') |
| 733 | f4 = script_helper.make_script(self.pkgdir, 'f4', '') |
Benjamin Peterson | a820c7c | 2012-09-25 11:42:35 -0400 | [diff] [blame] | 734 | p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-'])) |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 735 | p.stdin.write((f3+os.linesep).encode('ascii')) |
| 736 | script_helper.kill_python(p) |
| 737 | self.assertNotCompiled(f1) |
| 738 | self.assertNotCompiled(f2) |
| 739 | self.assertCompiled(f3) |
| 740 | self.assertNotCompiled(f4) |
| 741 | |
| 742 | def test_compiles_as_much_as_possible(self): |
| 743 | bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error') |
| 744 | rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn, |
| 745 | bingfn, self.barfn) |
R. David Murray | 5317e9c | 2010-12-16 19:08:51 +0000 | [diff] [blame] | 746 | self.assertRegex(out, b'rror') |
R. David Murray | 95333e3 | 2010-12-14 22:32:50 +0000 | [diff] [blame] | 747 | self.assertNotCompiled(bingfn) |
| 748 | self.assertCompiled(self.initfn) |
| 749 | self.assertCompiled(self.barfn) |
| 750 | |
R. David Murray | 5317e9c | 2010-12-16 19:08:51 +0000 | [diff] [blame] | 751 | def test_invalid_arg_produces_message(self): |
| 752 | out = self.assertRunOK('badfilename') |
Victor Stinner | 5307126 | 2011-05-11 00:36:28 +0200 | [diff] [blame] | 753 | self.assertRegex(out, b"Can't list 'badfilename'") |
R. David Murray | 650f147 | 2010-11-20 21:18:51 +0000 | [diff] [blame] | 754 | |
Benjamin Peterson | 42aa93b | 2017-12-09 10:26:52 -0800 | [diff] [blame] | 755 | def test_pyc_invalidation_mode(self): |
| 756 | script_helper.make_script(self.pkgdir, 'f1', '') |
| 757 | pyc = importlib.util.cache_from_source( |
| 758 | os.path.join(self.pkgdir, 'f1.py')) |
| 759 | self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir) |
| 760 | with open(pyc, 'rb') as fp: |
| 761 | data = fp.read() |
| 762 | self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11) |
| 763 | self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir) |
| 764 | with open(pyc, 'rb') as fp: |
| 765 | data = fp.read() |
| 766 | self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01) |
| 767 | |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 768 | @skipUnless(_have_multiprocessing, "requires multiprocessing") |
| 769 | def test_workers(self): |
| 770 | bar2fn = script_helper.make_script(self.directory, 'bar2', '') |
| 771 | files = [] |
| 772 | for suffix in range(5): |
| 773 | pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix)) |
| 774 | os.mkdir(pkgdir) |
| 775 | fn = script_helper.make_script(pkgdir, '__init__', '') |
| 776 | files.append(script_helper.make_script(pkgdir, 'bar2', '')) |
| 777 | |
| 778 | self.assertRunOK(self.directory, '-j', '0') |
| 779 | self.assertCompiled(bar2fn) |
| 780 | for file in files: |
| 781 | self.assertCompiled(file) |
| 782 | |
| 783 | @mock.patch('compileall.compile_dir') |
| 784 | def test_workers_available_cores(self, compile_dir): |
| 785 | with mock.patch("sys.argv", |
| 786 | new=[sys.executable, self.directory, "-j0"]): |
| 787 | compileall.main() |
| 788 | self.assertTrue(compile_dir.called) |
Antoine Pitrou | 1a2dd82 | 2019-05-15 23:45:18 +0200 | [diff] [blame] | 789 | self.assertEqual(compile_dir.call_args[-1]['workers'], 0) |
Brett Cannon | f1a8df0 | 2014-09-12 10:39:48 -0400 | [diff] [blame] | 790 | |
Lumír 'Frenzy' Balhar | 8e7bb99 | 2019-09-26 08:28:26 +0200 | [diff] [blame] | 791 | def test_strip_and_prepend(self): |
| 792 | fullpath = ["test", "build", "real", "path"] |
| 793 | path = os.path.join(self.directory, *fullpath) |
| 794 | os.makedirs(path) |
| 795 | script = script_helper.make_script(path, "test", "1 / 0") |
| 796 | bc = importlib.util.cache_from_source(script) |
| 797 | stripdir = os.path.join(self.directory, *fullpath[:2]) |
| 798 | prependdir = "/foo" |
| 799 | self.assertRunOK("-s", stripdir, "-p", prependdir, path) |
| 800 | rc, out, err = script_helper.assert_python_failure(bc) |
| 801 | expected_in = os.path.join(prependdir, *fullpath[2:]) |
| 802 | self.assertIn( |
| 803 | expected_in, |
| 804 | str(err, encoding=sys.getdefaultencoding()) |
| 805 | ) |
| 806 | self.assertNotIn( |
| 807 | stripdir, |
| 808 | str(err, encoding=sys.getdefaultencoding()) |
| 809 | ) |
| 810 | |
| 811 | def test_multiple_optimization_levels(self): |
| 812 | path = os.path.join(self.directory, "optimizations") |
| 813 | os.makedirs(path) |
| 814 | script = script_helper.make_script(path, |
| 815 | "test_optimization", |
| 816 | "a = 0") |
| 817 | bc = [] |
| 818 | for opt_level in "", 1, 2, 3: |
| 819 | bc.append(importlib.util.cache_from_source(script, |
| 820 | optimization=opt_level)) |
| 821 | test_combinations = [["0", "1"], |
| 822 | ["1", "2"], |
| 823 | ["0", "2"], |
| 824 | ["0", "1", "2"]] |
| 825 | for opt_combination in test_combinations: |
| 826 | self.assertRunOK(path, *("-o" + str(n) for n in opt_combination)) |
| 827 | for opt_level in opt_combination: |
| 828 | self.assertTrue(os.path.isfile(bc[int(opt_level)])) |
| 829 | try: |
| 830 | os.unlink(bc[opt_level]) |
| 831 | except Exception: |
| 832 | pass |
| 833 | |
Hai Shi | 883bc63 | 2020-07-06 17:12:49 +0800 | [diff] [blame] | 834 | @os_helper.skip_unless_symlink |
Lumír 'Frenzy' Balhar | 8e7bb99 | 2019-09-26 08:28:26 +0200 | [diff] [blame] | 835 | def test_ignore_symlink_destination(self): |
| 836 | # Create folders for allowed files, symlinks and prohibited area |
| 837 | allowed_path = os.path.join(self.directory, "test", "dir", "allowed") |
| 838 | symlinks_path = os.path.join(self.directory, "test", "dir", "symlinks") |
| 839 | prohibited_path = os.path.join(self.directory, "test", "dir", "prohibited") |
| 840 | os.makedirs(allowed_path) |
| 841 | os.makedirs(symlinks_path) |
| 842 | os.makedirs(prohibited_path) |
| 843 | |
| 844 | # Create scripts and symlinks and remember their byte-compiled versions |
| 845 | allowed_script = script_helper.make_script(allowed_path, "test_allowed", "a = 0") |
| 846 | prohibited_script = script_helper.make_script(prohibited_path, "test_prohibited", "a = 0") |
| 847 | allowed_symlink = os.path.join(symlinks_path, "test_allowed.py") |
| 848 | prohibited_symlink = os.path.join(symlinks_path, "test_prohibited.py") |
| 849 | os.symlink(allowed_script, allowed_symlink) |
| 850 | os.symlink(prohibited_script, prohibited_symlink) |
| 851 | allowed_bc = importlib.util.cache_from_source(allowed_symlink) |
| 852 | prohibited_bc = importlib.util.cache_from_source(prohibited_symlink) |
| 853 | |
| 854 | self.assertRunOK(symlinks_path, "-e", allowed_path) |
| 855 | |
| 856 | self.assertTrue(os.path.isfile(allowed_bc)) |
| 857 | self.assertFalse(os.path.isfile(prohibited_bc)) |
| 858 | |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 859 | def test_hardlink_bad_args(self): |
| 860 | # Bad arguments combination, hardlink deduplication make sense |
| 861 | # only for more than one optimization level |
| 862 | self.assertRunNotOK(self.directory, "-o 1", "--hardlink-dupes") |
| 863 | |
| 864 | def test_hardlink(self): |
| 865 | # 'a = 0' code produces the same bytecode for the 3 optimization |
| 866 | # levels. All three .pyc files must have the same inode (hardlinks). |
| 867 | # |
| 868 | # If deduplication is disabled, all pyc files must have different |
| 869 | # inodes. |
| 870 | for dedup in (True, False): |
| 871 | with tempfile.TemporaryDirectory() as path: |
| 872 | with self.subTest(dedup=dedup): |
| 873 | script = script_helper.make_script(path, "script", "a = 0") |
| 874 | pycs = get_pycs(script) |
| 875 | |
| 876 | args = ["-q", "-o 0", "-o 1", "-o 2"] |
| 877 | if dedup: |
| 878 | args.append("--hardlink-dupes") |
| 879 | self.assertRunOK(path, *args) |
| 880 | |
| 881 | self.assertEqual(is_hardlink(pycs[0], pycs[1]), dedup) |
| 882 | self.assertEqual(is_hardlink(pycs[1], pycs[2]), dedup) |
| 883 | self.assertEqual(is_hardlink(pycs[0], pycs[2]), dedup) |
| 884 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 885 | |
Min ho Kim | c4cacc8 | 2019-07-31 08:16:13 +1000 | [diff] [blame] | 886 | class CommandLineTestsWithSourceEpoch(CommandLineTestsBase, |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 887 | unittest.TestCase, |
| 888 | metaclass=SourceDateEpochTestMeta, |
| 889 | source_date_epoch=True): |
| 890 | pass |
| 891 | |
| 892 | |
Min ho Kim | c4cacc8 | 2019-07-31 08:16:13 +1000 | [diff] [blame] | 893 | class CommandLineTestsNoSourceEpoch(CommandLineTestsBase, |
Elvis Pranskevichus | a6b3ec5 | 2018-10-10 12:43:14 -0400 | [diff] [blame] | 894 | unittest.TestCase, |
| 895 | metaclass=SourceDateEpochTestMeta, |
| 896 | source_date_epoch=False): |
| 897 | pass |
| 898 | |
| 899 | |
| 900 | |
Lumír 'Frenzy' Balhar | e77d428 | 2020-05-14 16:17:22 +0200 | [diff] [blame] | 901 | class HardlinkDedupTestsBase: |
| 902 | # Test hardlink_dupes parameter of compileall.compile_dir() |
| 903 | |
| 904 | def setUp(self): |
| 905 | self.path = None |
| 906 | |
| 907 | @contextlib.contextmanager |
| 908 | def temporary_directory(self): |
| 909 | with tempfile.TemporaryDirectory() as path: |
| 910 | self.path = path |
| 911 | yield path |
| 912 | self.path = None |
| 913 | |
| 914 | def make_script(self, code, name="script"): |
| 915 | return script_helper.make_script(self.path, name, code) |
| 916 | |
| 917 | def compile_dir(self, *, dedup=True, optimize=(0, 1, 2), force=False): |
| 918 | compileall.compile_dir(self.path, quiet=True, optimize=optimize, |
| 919 | hardlink_dupes=dedup, force=force) |
| 920 | |
| 921 | def test_bad_args(self): |
| 922 | # Bad arguments combination, hardlink deduplication make sense |
| 923 | # only for more than one optimization level |
| 924 | with self.temporary_directory(): |
| 925 | self.make_script("pass") |
| 926 | with self.assertRaises(ValueError): |
| 927 | compileall.compile_dir(self.path, quiet=True, optimize=0, |
| 928 | hardlink_dupes=True) |
| 929 | with self.assertRaises(ValueError): |
| 930 | # same optimization level specified twice: |
| 931 | # compile_dir() removes duplicates |
| 932 | compileall.compile_dir(self.path, quiet=True, optimize=[0, 0], |
| 933 | hardlink_dupes=True) |
| 934 | |
| 935 | def create_code(self, docstring=False, assertion=False): |
| 936 | lines = [] |
| 937 | if docstring: |
| 938 | lines.append("'module docstring'") |
| 939 | lines.append('x = 1') |
| 940 | if assertion: |
| 941 | lines.append("assert x == 1") |
| 942 | return '\n'.join(lines) |
| 943 | |
| 944 | def iter_codes(self): |
| 945 | for docstring in (False, True): |
| 946 | for assertion in (False, True): |
| 947 | code = self.create_code(docstring=docstring, assertion=assertion) |
| 948 | yield (code, docstring, assertion) |
| 949 | |
| 950 | def test_disabled(self): |
| 951 | # Deduplication disabled, no hardlinks |
| 952 | for code, docstring, assertion in self.iter_codes(): |
| 953 | with self.subTest(docstring=docstring, assertion=assertion): |
| 954 | with self.temporary_directory(): |
| 955 | script = self.make_script(code) |
| 956 | pycs = get_pycs(script) |
| 957 | self.compile_dir(dedup=False) |
| 958 | self.assertFalse(is_hardlink(pycs[0], pycs[1])) |
| 959 | self.assertFalse(is_hardlink(pycs[0], pycs[2])) |
| 960 | self.assertFalse(is_hardlink(pycs[1], pycs[2])) |
| 961 | |
| 962 | def check_hardlinks(self, script, docstring=False, assertion=False): |
| 963 | pycs = get_pycs(script) |
| 964 | self.assertEqual(is_hardlink(pycs[0], pycs[1]), |
| 965 | not assertion) |
| 966 | self.assertEqual(is_hardlink(pycs[0], pycs[2]), |
| 967 | not assertion and not docstring) |
| 968 | self.assertEqual(is_hardlink(pycs[1], pycs[2]), |
| 969 | not docstring) |
| 970 | |
| 971 | def test_hardlink(self): |
| 972 | # Test deduplication on all combinations |
| 973 | for code, docstring, assertion in self.iter_codes(): |
| 974 | with self.subTest(docstring=docstring, assertion=assertion): |
| 975 | with self.temporary_directory(): |
| 976 | script = self.make_script(code) |
| 977 | self.compile_dir() |
| 978 | self.check_hardlinks(script, docstring, assertion) |
| 979 | |
| 980 | def test_only_two_levels(self): |
| 981 | # Don't build the 3 optimization levels, but only 2 |
| 982 | for opts in ((0, 1), (1, 2), (0, 2)): |
| 983 | with self.subTest(opts=opts): |
| 984 | with self.temporary_directory(): |
| 985 | # code with no dostring and no assertion: |
| 986 | # same bytecode for all optimization levels |
| 987 | script = self.make_script(self.create_code()) |
| 988 | self.compile_dir(optimize=opts) |
| 989 | pyc1 = get_pyc(script, opts[0]) |
| 990 | pyc2 = get_pyc(script, opts[1]) |
| 991 | self.assertTrue(is_hardlink(pyc1, pyc2)) |
| 992 | |
| 993 | def test_duplicated_levels(self): |
| 994 | # compile_dir() must not fail if optimize contains duplicated |
| 995 | # optimization levels and/or if optimization levels are not sorted. |
| 996 | with self.temporary_directory(): |
| 997 | # code with no dostring and no assertion: |
| 998 | # same bytecode for all optimization levels |
| 999 | script = self.make_script(self.create_code()) |
| 1000 | self.compile_dir(optimize=[1, 0, 1, 0]) |
| 1001 | pyc1 = get_pyc(script, 0) |
| 1002 | pyc2 = get_pyc(script, 1) |
| 1003 | self.assertTrue(is_hardlink(pyc1, pyc2)) |
| 1004 | |
| 1005 | def test_recompilation(self): |
| 1006 | # Test compile_dir() when pyc files already exists and the script |
| 1007 | # content changed |
| 1008 | with self.temporary_directory(): |
| 1009 | script = self.make_script("a = 0") |
| 1010 | self.compile_dir() |
| 1011 | # All three levels have the same inode |
| 1012 | self.check_hardlinks(script) |
| 1013 | |
| 1014 | pycs = get_pycs(script) |
| 1015 | inode = os.stat(pycs[0]).st_ino |
| 1016 | |
| 1017 | # Change of the module content |
| 1018 | script = self.make_script("print(0)") |
| 1019 | |
| 1020 | # Recompilation without -o 1 |
| 1021 | self.compile_dir(optimize=[0, 2], force=True) |
| 1022 | |
| 1023 | # opt-1.pyc should have the same inode as before and others should not |
| 1024 | self.assertEqual(inode, os.stat(pycs[1]).st_ino) |
| 1025 | self.assertTrue(is_hardlink(pycs[0], pycs[2])) |
| 1026 | self.assertNotEqual(inode, os.stat(pycs[2]).st_ino) |
| 1027 | # opt-1.pyc and opt-2.pyc have different content |
| 1028 | self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True)) |
| 1029 | |
| 1030 | def test_import(self): |
| 1031 | # Test that import updates a single pyc file when pyc files already |
| 1032 | # exists and the script content changed |
| 1033 | with self.temporary_directory(): |
| 1034 | script = self.make_script(self.create_code(), name="module") |
| 1035 | self.compile_dir() |
| 1036 | # All three levels have the same inode |
| 1037 | self.check_hardlinks(script) |
| 1038 | |
| 1039 | pycs = get_pycs(script) |
| 1040 | inode = os.stat(pycs[0]).st_ino |
| 1041 | |
| 1042 | # Change of the module content |
| 1043 | script = self.make_script("print(0)", name="module") |
| 1044 | |
| 1045 | # Import the module in Python with -O (optimization level 1) |
| 1046 | script_helper.assert_python_ok( |
| 1047 | "-O", "-c", "import module", __isolated=False, PYTHONPATH=self.path |
| 1048 | ) |
| 1049 | |
| 1050 | # Only opt-1.pyc is changed |
| 1051 | self.assertEqual(inode, os.stat(pycs[0]).st_ino) |
| 1052 | self.assertEqual(inode, os.stat(pycs[2]).st_ino) |
| 1053 | self.assertFalse(is_hardlink(pycs[1], pycs[2])) |
| 1054 | # opt-1.pyc and opt-2.pyc have different content |
| 1055 | self.assertFalse(filecmp.cmp(pycs[1], pycs[2], shallow=True)) |
| 1056 | |
| 1057 | |
| 1058 | class HardlinkDedupTestsWithSourceEpoch(HardlinkDedupTestsBase, |
| 1059 | unittest.TestCase, |
| 1060 | metaclass=SourceDateEpochTestMeta, |
| 1061 | source_date_epoch=True): |
| 1062 | pass |
| 1063 | |
| 1064 | |
| 1065 | class HardlinkDedupTestsNoSourceEpoch(HardlinkDedupTestsBase, |
| 1066 | unittest.TestCase, |
| 1067 | metaclass=SourceDateEpochTestMeta, |
| 1068 | source_date_epoch=False): |
| 1069 | pass |
| 1070 | |
| 1071 | |
Brett Cannon | befb14f | 2009-02-10 02:10:16 +0000 | [diff] [blame] | 1072 | if __name__ == "__main__": |
Brett Cannon | 7822e12 | 2013-06-14 23:04:02 -0400 | [diff] [blame] | 1073 | unittest.main() |