• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import io
2import unittest
3
4from importlib import resources
5from . import data01
6from . import util
7
8
9class CommonTests(util.CommonResourceTests, unittest.TestCase):
10    def execute(self, package, path):
11        with resources.path(package, path):
12            pass
13
14
15class PathTests:
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        with resources.path(self.data, 'utf-8.file') as path:
21            self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
22            # pathlib.Path.read_text() was introduced in Python 3.5.
23            with path.open('r', encoding='utf-8') as file:
24                text = file.read()
25            self.assertEqual('Hello, UTF-8 world!\n', text)
26
27
28class PathDiskTests(PathTests, unittest.TestCase):
29    data = data01
30
31    def test_natural_path(self):
32        # Guarantee the internal implementation detail that
33        # file-system-backed resources do not get the tempdir
34        # treatment.
35        with resources.path(self.data, 'utf-8.file') as path:
36            assert 'data' in str(path)
37
38
39class PathMemoryTests(PathTests, unittest.TestCase):
40    def setUp(self):
41        file = io.BytesIO(b'Hello, UTF-8 world!\n')
42        self.addCleanup(file.close)
43        self.data = util.create_package(
44            file=file, path=FileNotFoundError("package exists only in memory")
45        )
46        self.data.__spec__.origin = None
47        self.data.__spec__.has_location = False
48
49
50class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
51    def test_remove_in_context_manager(self):
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        with resources.path(self.data, 'utf-8.file') as path:
55            path.unlink()
56
57
58if __name__ == '__main__':
59    unittest.main()
60