Debian Codegraph @

Lib/test/test_importlib/resources/test_files.py

raw
1 import os
2 import pathlib
3 import py_compile
4 import shutil
5 import textwrap
6 import unittest
7 import warnings
8 import importlib
9 import contextlib
10
11 from importlib import resources
12 from importlib.resources.abc import Traversable
13 from . import util
14 from test.support import os_helper, import_helper
15
16
17 @contextlib.contextmanager
18 def suppress_known_deprecation():
19 with warnings.catch_warnings(record=True) as ctx:
20 warnings.simplefilter('default', category=DeprecationWarning)
21 yield ctx
22
23
24 class FilesTests:
25 def test_read_bytes(self):
26 files = resources.files(self.data)
27 actual = files.joinpath('utf-8.file').read_bytes()
28 assert actual == b'Hello, UTF-8 world!\n'
29
30 def test_read_text(self):
31 files = resources.files(self.data)
32 actual = files.joinpath('utf-8.file').read_text(encoding='utf-8')
33 assert actual == 'Hello, UTF-8 world!\n'
34
35 def test_traversable(self):
36 assert isinstance(resources.files(self.data), Traversable)
37
38 def test_joinpath_with_multiple_args(self):
39 files = resources.files(self.data)
40 binfile = files.joinpath('subdirectory', 'binary.file')
41 self.assertTrue(binfile.is_file())
42
43 def test_old_parameter(self):
44 """
45 Files used to take a 'package' parameter. Make sure anyone
46 passing by name is still supported.
47 """
48 with suppress_known_deprecation():
49 resources.files(package=self.data)
50
51
52 class OpenDiskTests(FilesTests, util.DiskSetup, unittest.TestCase):
53 pass
54
55
56 class OpenZipTests(FilesTests, util.ZipSetup, unittest.TestCase):
57 pass
58
59
60 class OpenNamespaceTests(FilesTests, util.DiskSetup, unittest.TestCase):
61 MODULE = 'namespacedata01'
62
63 def test_non_paths_in_dunder_path(self):
64 """
65 Non-path items in a namespace package's ``__path__`` are ignored.
66
67 As reported in python/importlib_resources#311, some tools
68 like Setuptools, when creating editable packages, will inject
69 non-paths into a namespace package's ``__path__``, a
70 sentinel like
71 ``__editable__.sample_namespace-1.0.finder.__path_hook__``
72 to cause the ``PathEntryFinder`` to be called when searching
73 for packages. In that case, resources should still be loadable.
74 """
75 import namespacedata01
76
77 namespacedata01.__path__.append(
78 '__editable__.sample_namespace-1.0.finder.__path_hook__'
79 )
80
81 resources.files(namespacedata01)
82
83
84 class OpenNamespaceZipTests(FilesTests, util.ZipSetup, unittest.TestCase):
85 ZIP_MODULE = 'namespacedata01'
86
87
88 class DirectSpec:
89 """
90 Override behavior of ModuleSetup to write a full spec directly.
91 """
92
93 MODULE = 'unused'
94
95 def load_fixture(self, name):
96 self.tree_on_path(self.spec)
97
98
99 class ModulesFiles:
100 spec = {
101 'mod.py': '',
102 'res.txt': 'resources are the best',
103 }
104
105 def test_module_resources(self):
106 """
107 A module can have resources found adjacent to the module.
108 """
109 import mod # type: ignore[import-not-found]
110
111 actual = resources.files(mod).joinpath('res.txt').read_text(encoding='utf-8')
112 assert actual == self.spec['res.txt']
113
114
115 class ModuleFilesDiskTests(DirectSpec, util.DiskSetup, ModulesFiles, unittest.TestCase):
116 pass
117
118
119 class ModuleFilesZipTests(DirectSpec, util.ZipSetup, ModulesFiles, unittest.TestCase):
120 pass
121
122
123 class ImplicitContextFiles:
124 set_val = textwrap.dedent(
125 f"""
126 import {resources.__name__} as res
127 val = res.files().joinpath('res.txt').read_text(encoding='utf-8')
128 """
129 )
130 spec = {
131 'somepkg': {
132 '__init__.py': set_val,
133 'submod.py': set_val,
134 'res.txt': 'resources are the best',
135 },
136 'frozenpkg': {
137 '__init__.py': set_val.replace(resources.__name__, 'c_resources'),
138 'res.txt': 'resources are the best',
139 },
140 }
141
142 def test_implicit_files_package(self):
143 """
144 Without any parameter, files() will infer the location as the caller.
145 """
146 assert importlib.import_module('somepkg').val == 'resources are the best'
147
148 def test_implicit_files_submodule(self):
149 """
150 Without any parameter, files() will infer the location as the caller.
151 """
152 assert importlib.import_module('somepkg.submod').val == 'resources are the best'
153
154 def _compile_importlib(self):
155 """
156 Make a compiled-only copy of the importlib resources package.
157
158 Currently only code is copied, as importlib resources doesn't itself
159 have any resources.
160 """
161 bin_site = self.fixtures.enter_context(os_helper.temp_dir())
162 c_resources = pathlib.Path(bin_site, 'c_resources')
163 sources = pathlib.Path(resources.__file__).parent
164
165 for source_path in sources.glob('**/*.py'):
166 c_path = c_resources.joinpath(source_path.relative_to(sources)).with_suffix('.pyc')
167 py_compile.compile(source_path, c_path)
168 self.fixtures.enter_context(import_helper.DirsOnSysPath(bin_site))
169
170 def test_implicit_files_with_compiled_importlib(self):
171 """
172 Caller detection works for compiled-only resources module.
173
174 python/cpython#123085
175 """
176 self._compile_importlib()
177 assert importlib.import_module('frozenpkg').val == 'resources are the best'
178
179
180 class ImplicitContextFilesDiskTests(
181 DirectSpec, util.DiskSetup, ImplicitContextFiles, unittest.TestCase
182 ):
183 pass
184
185
186 class ImplicitContextFilesZipTests(
187 DirectSpec, util.ZipSetup, ImplicitContextFiles, unittest.TestCase
188 ):
189 pass
190
191
192 if __name__ == '__main__':
193 unittest.main()