forked from indygreg/PyOxidizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_importer_pkg_resources.py
428 lines (346 loc) · 15.8 KB
/
test_importer_pkg_resources.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# email.parser may be unused. However, it is needed by Rust code and some
# sys.path mucking in tests may prevent it from being imported. So import
# here to ensure it is cached in sys.modules so Rust can import it.
import email.parser
import io
import os
import pathlib
import sys
import tempfile
import unittest
try:
import pkg_resources
except ImportError:
pkg_resources = None
from oxidized_importer import (
OxidizedFinder,
OxidizedPathEntryFinder,
OxidizedPkgResourcesProvider,
OxidizedResourceCollector,
OxidizedResource,
find_resources_in_path,
register_pkg_resources,
)
def make_in_memory_finder():
f = OxidizedFinder()
r = OxidizedResource()
r.is_module = True
r.is_package = True
r.name = "package0"
r.in_memory_source = b"pass"
r.in_memory_distribution_resources = {
"METADATA": b"Name: package0\nVersion: 1.0\n",
"entry_points.txt": b"[console_scripts]\ncli = package0:cli\n",
}
r.in_memory_package_resources = {
"file0": b"foo",
}
f.add_resource(r)
r = OxidizedResource()
r.is_module = True
r.is_package = True
r.name = "package1"
r.in_memory_source = b"pass"
r.in_memory_distribution_resources = {
"PKG-INFO": b"Name: package1\nVersion: 2.0\n",
"requires.txt": b"package0\n",
}
f.add_resource(r)
r = OxidizedResource()
r.is_module = True
r.is_package = True
r.name = "package0.p0child0"
r.in_memory_source = b"pass"
r.in_memory_distribution_resources = {
"METADATA": b"Name: p0child0\nVersion: 1.0\n",
}
r.in_memory_package_resources = {
"childfile0": b"foo",
}
f.add_resource(r)
r = OxidizedResource()
r.is_module = True
r.is_package = True
r.name = "package0.p0child0.p0grandchild0"
r.in_memory_source = b"pass"
r.in_memory_distribution_resources = {
"METADATA": b"Name: p0grandchild0\nVersion: 1.0\n",
}
f.add_resource(r)
return f
def install_distributions_finder():
f = make_in_memory_finder()
sys.meta_path.insert(0, f)
sys.path_hooks.insert(0, f.path_hook)
return f
@unittest.skipIf(pkg_resources is None, "pkg_resources not available")
class TestImporterPkgResources(unittest.TestCase):
@classmethod
def setUpClass(cls):
register_pkg_resources()
def setUp(self):
self.raw_temp_dir = tempfile.TemporaryDirectory(
prefix="oxidized_importer-test-"
)
self.td = pathlib.Path(self.raw_temp_dir.name)
self.old_finders = list(sys.meta_path)
self.old_path = list(sys.path)
self.old_path_hooks = list(sys.path_hooks)
self.old_path_importer_cache = dict(sys.path_importer_cache)
self.old_modules = dict(sys.modules)
self.old_provider_factories = dict(pkg_resources._provider_factories)
self.old_distribution_finders = dict(pkg_resources._distribution_finders)
def tearDown(self):
self.raw_temp_dir.cleanup()
del self.raw_temp_dir
del self.td
sys.meta_path[:] = self.old_finders
sys.path[:] = self.old_path
sys.path_hooks[:] = self.old_path_hooks
sys.path_importer_cache.clear()
sys.path_importer_cache.update(self.old_path_importer_cache)
sys.modules.clear()
sys.modules.update(self.old_modules)
pkg_resources._provider_factories.clear()
pkg_resources._provider_factories.update(self.old_provider_factories)
pkg_resources._distribution_finders.clear()
pkg_resources._distribution_finders.update(self.old_distribution_finders)
def _write_metadata(self):
metadata_path = self.td / "my_package-1.0.dist-info" / "METADATA"
metadata_path.parent.mkdir()
with metadata_path.open("wb") as fh:
fh.write(b"Name: my_package\n")
fh.write(b"Version: 1.0\n")
def _finder_from_td(self):
collector = OxidizedResourceCollector(allowed_locations=["in-memory"])
for r in find_resources_in_path(self.td):
collector.add_in_memory(r)
f = OxidizedFinder()
f.add_resources(collector.oxidize()[0])
return f
def test_provider_registered(self):
# Should have been done via setUpClass.
self.assertEqual(
pkg_resources._distribution_finders.get(OxidizedPathEntryFinder).__name__,
"pkg_resources_find_distributions",
)
self.assertEqual(
pkg_resources._provider_factories.get(OxidizedFinder),
OxidizedPkgResourcesProvider,
)
def test_package_provider(self):
self._write_metadata()
dist_info_path = self.td / "my_package-1.0.dist-info"
(dist_info_path / "subdir").mkdir()
(dist_info_path / "subdir" / "grandchild").mkdir()
with (dist_info_path / "subdir" / "file.txt").open("wb"):
pass
with (dist_info_path / "subdir" / "grandchild" / "file2.txt").open("wb"):
pass
my_package_path = self.td / "my_package"
my_package_path.mkdir(parents=True)
with (my_package_path / "__init__.py").open("wb"):
pass
with (my_package_path / "resource0.txt").open("wb") as fh:
fh.write(b"line0\n")
fh.write(b"line1\n")
(my_package_path / "subdir").mkdir()
(my_package_path / "subdir" / "grandchild").mkdir()
with (my_package_path / "subdir" / "child0.txt").open("wb"):
pass
with (my_package_path / "subdir" / "grandchild" / "grandchild.txt").open("wb"):
pass
f = self._finder_from_td()
sys.meta_path.insert(0, f)
provider = pkg_resources.get_provider("my_package")
self.assertIsInstance(provider, OxidizedPkgResourcesProvider)
self.assertFalse(provider.has_metadata("foo"))
self.assertTrue(provider.has_metadata("METADATA"))
with self.assertRaises(IOError):
provider.get_metadata("foo")
self.assertEqual(
provider.get_metadata("METADATA"), "Name: my_package\nVersion: 1.0\n"
)
lines = provider.get_metadata_lines("METADATA")
self.assertEqual(next(lines), "Name: my_package")
self.assertEqual(next(lines), "Version: 1.0")
with self.assertRaises(StopIteration):
next(lines)
self.assertFalse(provider.metadata_isdir("foo"))
self.assertFalse(provider.metadata_isdir("METADATA"))
self.assertFalse(provider.metadata_isdir(""))
self.assertTrue(provider.metadata_isdir("subdir"))
self.assertTrue(provider.metadata_isdir("subdir/"))
self.assertTrue(provider.metadata_isdir("subdir\\"))
self.assertEqual(provider.metadata_listdir("missing"), [])
self.assertEqual(provider.metadata_listdir(""), ["METADATA"])
self.assertEqual(provider.metadata_listdir("subdir"), ["file.txt"])
self.assertEqual(provider.metadata_listdir("subdir/"), ["file.txt"])
self.assertEqual(provider.metadata_listdir("subdir\\"), ["file.txt"])
self.assertEqual(provider.metadata_listdir("subdir/grandchild"), ["file2.txt"])
self.assertEqual(provider.metadata_listdir("subdir\\grandchild"), ["file2.txt"])
self.assertEqual(provider.metadata_listdir("subdir/grandchild/"), ["file2.txt"])
self.assertEqual(
provider.metadata_listdir("subdir\\grandchild\\"), ["file2.txt"]
)
with self.assertRaises(NotImplementedError):
provider.run_script("foo", "ns")
with self.assertRaises(NotImplementedError):
provider.get_resource_filename(None, "foo")
with self.assertRaises(IOError):
provider.get_resource_stream(None, "missing")
fh = provider.get_resource_stream(None, "resource0.txt")
self.assertIsInstance(fh, io.BytesIO)
self.assertEqual(fh.read(), b"line0\nline1\n")
with self.assertRaises(IOError):
provider.get_resource_string(None, "missing")
self.assertEqual(
provider.get_resource_string(None, "resource0.txt"), b"line0\nline1\n"
)
self.assertEqual(provider.get_resource_string(None, "subdir/child0.txt"), b"")
self.assertFalse(provider.has_resource("missing"))
self.assertTrue(provider.has_resource("resource0.txt"))
self.assertTrue(provider.has_resource("subdir/child0.txt"))
self.assertTrue(provider.has_resource("subdir/grandchild/grandchild.txt"))
self.assertFalse(provider.resource_isdir("missing"))
self.assertFalse(provider.resource_isdir("resource0.txt"))
self.assertFalse(provider.resource_isdir(""))
self.assertTrue(provider.resource_isdir("subdir"))
self.assertTrue(provider.resource_isdir("subdir/"))
self.assertTrue(provider.resource_isdir("subdir\\"))
self.assertTrue(provider.resource_isdir("subdir/grandchild"))
self.assertTrue(provider.resource_isdir("subdir/grandchild/"))
self.assertTrue(provider.resource_isdir("subdir\\grandchild"))
self.assertTrue(provider.resource_isdir("subdir\\grandchild\\"))
self.assertEqual(provider.resource_listdir("missing"), [])
self.assertEqual(provider.resource_listdir(""), ["resource0.txt"])
self.assertEqual(provider.resource_listdir("subdir"), ["child0.txt"])
self.assertEqual(provider.resource_listdir("subdir/"), ["child0.txt"])
self.assertEqual(provider.resource_listdir("subdir\\"), ["child0.txt"])
self.assertEqual(
provider.resource_listdir("subdir/grandchild"), ["grandchild.txt"]
)
self.assertEqual(
provider.resource_listdir("subdir\\grandchild"), ["grandchild.txt"]
)
self.assertEqual(
provider.resource_listdir("subdir/grandchild/"), ["grandchild.txt"]
)
self.assertEqual(
provider.resource_listdir("subdir\\grandchild\\"), ["grandchild.txt"]
)
def assert_package0(self, dist):
self.assertIsInstance(dist, pkg_resources.Distribution)
self.assertEqual(dist.project_name, "package0")
self.assertEqual(dist.version, "1.0")
self.assertEqual(list(dist.get_entry_map(None).keys()), ["console_scripts"])
def assert_package0_child0(self, dist):
self.assertIsInstance(dist, pkg_resources.Distribution)
self.assertEqual(dist.project_name, "p0child0")
self.assertEqual(dist.version, "1.0")
def assert_package0_grandchild0(self, dist):
self.assertIsInstance(dist, pkg_resources.Distribution)
self.assertEqual(dist.project_name, "p0grandchild0")
self.assertEqual(dist.version, "1.0")
def assert_package1(self, dist):
self.assertIsInstance(dist, pkg_resources.Distribution)
self.assertEqual(dist.project_name, "package1")
self.assertEqual(dist.version, "2.0")
self.assertEqual(dist.requires(), [pkg_resources.Requirement("package0")])
def test_finder_attribute(self):
f = install_distributions_finder()
self.assertTrue(f.pkg_resources_import_auto_register)
def test_find_distributions_no_path_hooks(self):
f = install_distributions_finder()
sys.path_hooks.clear()
self.assertEqual(
list(pkg_resources.find_distributions(f.path_hook_base_str, only=True)), []
)
def test_find_distributions_not_path_hook_base_str_path_hook(self):
install_distributions_finder()
self.assertEqual(list(pkg_resources.find_distributions("/some/other/path")), [])
def test_find_distributions_top_level_only_false(self):
f = install_distributions_finder()
dists = list(pkg_resources.find_distributions(f.path_hook_base_str, only=False))
self.assertEqual(len(dists), 4)
self.assert_package0(dists[0])
self.assert_package0_child0(dists[1])
self.assert_package0_grandchild0(dists[2])
self.assert_package1(dists[3])
def test_find_distributions_top_level_only_true(self):
f = install_distributions_finder()
search_path = f.path_hook_base_str
dists = list(pkg_resources.find_distributions(search_path, only=True))
self.assertEqual(len(dists), 2)
self.assert_package0(dists[0])
self.assert_package1(dists[1])
def test_find_distributions_search_path_missing(self):
f = install_distributions_finder()
search_path = os.path.join(f.path_hook_base_str, "missing_package")
dists = list(pkg_resources.find_distributions(search_path, only=False))
self.assertEqual(dists, [])
dists = list(pkg_resources.find_distributions(search_path, only=True))
self.assertEqual(dists, [])
def test_find_distributions_search_path_child_only_false(self):
f = install_distributions_finder()
search_path = os.path.join(f.path_hook_base_str, "package0")
dists = list(pkg_resources.find_distributions(search_path, only=False))
self.assertEqual(len(dists), 2)
self.assert_package0_child0(dists[0])
self.assert_package0_grandchild0(dists[1])
def test_find_distributions_search_path_child_only_true(self):
f = install_distributions_finder()
search_path = os.path.join(f.path_hook_base_str, "package0")
dists = list(pkg_resources.find_distributions(search_path, only=True))
self.assertEqual(len(dists), 1)
self.assert_package0_child0(dists[0])
def test_find_distributions_search_path_grandchild_only_false(self):
f = install_distributions_finder()
search_path = os.path.join(f.path_hook_base_str, "package0", "p0child0")
dists = list(pkg_resources.find_distributions(search_path, only=False))
self.assertEqual(len(dists), 1)
self.assert_package0_grandchild0(dists[0])
def test_find_distributions_search_path_grandchild_only_true(self):
f = install_distributions_finder()
search_path = os.path.join(f.path_hook_base_str, "package0", "p0child0")
dists = list(pkg_resources.find_distributions(search_path, only=True))
self.assertEqual(len(dists), 1)
self.assert_package0_grandchild0(dists[0])
def test_find_distributions_search_path_too_deep(self):
f = install_distributions_finder()
search_path = os.path.join(
f.path_hook_base_str, "package0", "p0child0", "grandchild0"
)
self.assertEqual(
list(pkg_resources.find_distributions(search_path, only=False)), []
)
self.assertEqual(
list(pkg_resources.find_distributions(search_path, only=True)), []
)
def test_resource_manager(self):
install_distributions_finder()
self.assertTrue(pkg_resources.resource_exists("package0", "file0"))
self.assertTrue(
pkg_resources.resource_exists("package0.p0child0", "childfile0")
)
self.assertFalse(pkg_resources.resource_exists("package0", "missing"))
self.assertFalse(pkg_resources.resource_exists("package0.p0child0", "missing"))
with self.assertRaises(ModuleNotFoundError):
pkg_resources.resource_exists("missing_package", "irrelevant")
self.assertIsInstance(
pkg_resources.resource_stream("package0", "file0"), io.BytesIO
)
self.assertIsInstance(
pkg_resources.resource_stream("package0.p0child0", "childfile0"), io.BytesIO
)
with self.assertRaises(OSError):
pkg_resources.resource_stream("package0", "missing")
with self.assertRaises(OSError):
pkg_resources.resource_stream("package0.p0child0", "missing")
with self.assertRaises(NotImplementedError):
pkg_resources.resource_filename("package0", "file0")
if __name__ == "__main__":
unittest.main()