|
1 | 1 | import typing
|
| 2 | +import os |
| 3 | +import pathlib |
| 4 | +import py_compile |
| 5 | +import shutil |
2 | 6 | import textwrap
|
3 | 7 | import unittest
|
4 | 8 | import warnings
|
|
10 | 14 | from . import data01
|
11 | 15 | from . import util
|
12 | 16 | from . import _path
|
13 |
| -from test.support import os_helper |
14 |
| -from test.support import import_helper |
| 17 | +from test.support import os_helper, import_helper |
15 | 18 |
|
16 | 19 |
|
17 | 20 | @contextlib.contextmanager
|
@@ -144,6 +147,45 @@ def create_zip_from_directory(source_dir, zip_filename):
|
144 | 147 | self.fixtures.enter_context(import_helper.DirsOnSysPath(zip_file))
|
145 | 148 | assert importlib.import_module('somepkg.submod').val == 'resources are the best'
|
146 | 149 |
|
| 150 | + def _compile_importlib(self): |
| 151 | + """ |
| 152 | + Make a compiled-only copy of the importlib resources package. |
| 153 | + """ |
| 154 | + bin_site = self.fixtures.enter_context(os_helper.temp_dir()) |
| 155 | + c_resources = pathlib.Path(bin_site, 'c_resources') |
| 156 | + sources = pathlib.Path(resources.__file__).parent |
| 157 | + shutil.copytree(sources, c_resources, ignore=lambda *_: ['__pycache__']) |
| 158 | + |
| 159 | + for dirpath, _, filenames in os.walk(c_resources): |
| 160 | + for filename in filenames: |
| 161 | + source_path = pathlib.Path(dirpath) / filename |
| 162 | + cfile = source_path.with_suffix('.pyc') |
| 163 | + py_compile.compile(source_path, cfile) |
| 164 | + pathlib.Path.unlink(source_path) |
| 165 | + self.fixtures.enter_context(import_helper.DirsOnSysPath(bin_site)) |
| 166 | + |
| 167 | + def test_implicit_files_with_compiled_importlib(self): |
| 168 | + """ |
| 169 | + Caller detection works for compiled-only resources module. |
| 170 | +
|
| 171 | + python/cpython#123085 |
| 172 | + """ |
| 173 | + set_val = textwrap.dedent( |
| 174 | + f""" |
| 175 | + import {resources.__name__} as res |
| 176 | + val = res.files().joinpath('res.txt').read_text(encoding='utf-8') |
| 177 | + """ |
| 178 | + ) |
| 179 | + spec = { |
| 180 | + 'frozenpkg': { |
| 181 | + '__init__.py': set_val.replace(resources.__name__, 'c_resources'), |
| 182 | + 'res.txt': 'resources are the best', |
| 183 | + }, |
| 184 | + } |
| 185 | + _path.build(spec, self.site_dir) |
| 186 | + self._compile_importlib() |
| 187 | + assert importlib.import_module('frozenpkg').val == 'resources are the best' |
| 188 | + |
147 | 189 |
|
148 | 190 | if __name__ == '__main__':
|
149 | 191 | unittest.main()
|
0 commit comments