1import io
2import unittest
3
4from importlib import resources
5from . import data01
6from .resources import util
7
8
9class CommonTests(util.CommonTests, unittest.TestCase):
10    def execute(self, package, path):
11        with resources.as_file(resources.files(package).joinpath(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        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
29class PathDiskTests(PathTests, unittest.TestCase):
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
41class PathMemoryTests(PathTests, unittest.TestCase):
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
52class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
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
61if __name__ == '__main__':
62    unittest.main()
63