Debian Codegraph @

Lib/test/test_importlib/resources/test_files.py

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