1 import io
2 import unittest
3
4 from importlib import resources
5 from . import data01
6 from .resources 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 # Path should be readable.
18 # Test also implicitly verifies the returned object is a pathlib.Path
19 # instance.
20 target = resources.files(self.data) / 'utf-8.file'
21 with resources.as_file(target) as path:
22 self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
23 # pathlib.Path.read_text() was introduced in Python 3.5.
24 with path.open('r', encoding='utf-8') as file:
25 text = file.read()
26 self.assertEqual('Hello, UTF-8 world!\n', text)
27
28
29 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):
30 data = data01
31
32 def test_natural_path(self):
33 # Guarantee the internal implementation detail that
34 # file-system-backed resources do not get the tempdir
35 # treatment.
36 target = resources.files(self.data) / 'utf-8.file'
37 with resources.as_file(target) as path:
38 assert 'data' in str(path)
39
40
41 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):
42 def setUp(self):
43 file = io.BytesIO(b'Hello, UTF-8 world!\n')
44 self.addCleanup(file.close)
45 self.data = util.create_package(
46 file=file, path=FileNotFoundError("package exists only in memory")
47 )
48 self.data.__spec__.origin = None
49 self.data.__spec__.has_location = False
50
51
52 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):
53 def test_remove_in_context_manager(self):
54 # It is not an error if the file that was temporarily stashed on the
55 # file system is removed inside the `with` stanza.
56 target = resources.files(self.data) / 'utf-8.file'
57 with resources.as_file(target) as path:
58 path.unlink()
59
60
61 if __name__ == '__main__':
62 unittest.main()