Debian Codegraph @

Lib/test/test_importlib/resources/test_path.py

raw
1 import io
2 import pathlib
3 import unittest
4
5 from importlib import resources
6 from . import util
7 from test.support.testcase import ExtraAssertions
8
9
10 class CommonTests(util.CommonTests, unittest.TestCase):
11 def execute(self, package, path):
12 with resources.as_file(resources.files(package).joinpath(path)):
13 pass
14
15
16 class PathTests(ExtraAssertions):
17 def test_reading(self):
18 """
19 Path should be readable and a pathlib.Path instance.
20 """
21 target = resources.files(self.data) / 'utf-8.file'
22 with resources.as_file(target) as path:
23 self.assertIsInstance(path, pathlib.Path)
24 self.assertEndsWith(path.name, "utf-8.file")
25 self.assertEqual('Hello, UTF-8 world!\n', path.read_text(encoding='utf-8'))
26
27
28 class PathDiskTests(PathTests, util.DiskSetup, unittest.TestCase):
29 def test_natural_path(self):
30 # Guarantee the internal implementation detail that
31 # file-system-backed resources do not get the tempdir
32 # treatment.
33 target = resources.files(self.data) / 'utf-8.file'
34 with resources.as_file(target) as path:
35 assert 'data' in str(path)
36
37
38 class PathMemoryTests(PathTests, unittest.TestCase):
39 def setUp(self):
40 file = io.BytesIO(b'Hello, UTF-8 world!\n')
41 self.addCleanup(file.close)
42 self.data = util.create_package(
43 file=file, path=FileNotFoundError("package exists only in memory")
44 )
45 self.data.__spec__.origin = None
46 self.data.__spec__.has_location = False
47
48
49 class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
50 def test_remove_in_context_manager(self):
51 """
52 It is not an error if the file that was temporarily stashed on the
53 file system is removed inside the `with` stanza.
54 """
55 target = resources.files(self.data) / 'utf-8.file'
56 with resources.as_file(target) as path:
57 path.unlink()
58
59
60 if __name__ == '__main__':
61 unittest.main()