python (3.12.0)
1 import io
2 import unittest
3
4 from importlib import resources
5 from . import data01
6 from . import util
7
8
9 class ESC[4;38;5;81mCommonTests(ESC[4;38;5;149mutilESC[4;38;5;149m.ESC[4;38;5;149mCommonTests, ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
10 def execute(self, package, path):
11 with resources.as_file(resources.files(package).joinpath(path)):
12 pass
13
14
15 class ESC[4;38;5;81mPathTests:
16 def test_reading(self):
17 """
18 Path should be readable.
19
20 Test also implicitly verifies the returned object is a pathlib.Path
21 instance.
22 """
23 target = resources.files(self.data) / 'utf-8.file'
24 with resources.as_file(target) as path:
25 self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
26 # pathlib.Path.read_text() was introduced in Python 3.5.
27 with path.open('r', encoding='utf-8') as file:
28 text = file.read()
29 self.assertEqual('Hello, UTF-8 world!\n', text)
30
31
32 class ESC[4;38;5;81mPathDiskTests(ESC[4;38;5;149mPathTests, ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
33 data = data01
34
35 def test_natural_path(self):
36 # Guarantee the internal implementation detail that
37 # file-system-backed resources do not get the tempdir
38 # treatment.
39 target = resources.files(self.data) / 'utf-8.file'
40 with resources.as_file(target) as path:
41 assert 'data' in str(path)
42
43
44 class ESC[4;38;5;81mPathMemoryTests(ESC[4;38;5;149mPathTests, ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
45 def setUp(self):
46 file = io.BytesIO(b'Hello, UTF-8 world!\n')
47 self.addCleanup(file.close)
48 self.data = util.create_package(
49 file=file, path=FileNotFoundError("package exists only in memory")
50 )
51 self.data.__spec__.origin = None
52 self.data.__spec__.has_location = False
53
54
55 class ESC[4;38;5;81mPathZipTests(ESC[4;38;5;149mPathTests, ESC[4;38;5;149mutilESC[4;38;5;149m.ESC[4;38;5;149mZipSetup, ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
56 def test_remove_in_context_manager(self):
57 """
58 It is not an error if the file that was temporarily stashed on the
59 file system is removed inside the `with` stanza.
60 """
61 target = resources.files(self.data) / 'utf-8.file'
62 with resources.as_file(target) as path:
63 path.unlink()
64
65
66 if __name__ == '__main__':
67 unittest.main()