• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import unittest
2
3from importlib import resources
4from . import data01
5from . import util
6
7
8class CommonBinaryTests(util.CommonResourceTests, unittest.TestCase):
9    def execute(self, package, path):
10        with resources.open_binary(package, path):
11            pass
12
13
14class CommonTextTests(util.CommonResourceTests, unittest.TestCase):
15    def execute(self, package, path):
16        with resources.open_text(package, path):
17            pass
18
19
20class OpenTests:
21    def test_open_binary(self):
22        with resources.open_binary(self.data, 'binary.file') as fp:
23            result = fp.read()
24            self.assertEqual(result, b'\x00\x01\x02\x03')
25
26    def test_open_text_default_encoding(self):
27        with resources.open_text(self.data, 'utf-8.file') as fp:
28            result = fp.read()
29            self.assertEqual(result, 'Hello, UTF-8 world!\n')
30
31    def test_open_text_given_encoding(self):
32        with resources.open_text(self.data, 'utf-16.file', 'utf-16', 'strict') as fp:
33            result = fp.read()
34        self.assertEqual(result, 'Hello, UTF-16 world!\n')
35
36    def test_open_text_with_errors(self):
37        # Raises UnicodeError without the 'errors' argument.
38        with resources.open_text(self.data, 'utf-16.file', 'utf-8', 'strict') as fp:
39            self.assertRaises(UnicodeError, fp.read)
40        with resources.open_text(self.data, 'utf-16.file', 'utf-8', 'ignore') as fp:
41            result = fp.read()
42        self.assertEqual(
43            result,
44            'H\x00e\x00l\x00l\x00o\x00,\x00 '
45            '\x00U\x00T\x00F\x00-\x001\x006\x00 '
46            '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00',
47        )
48
49    def test_open_binary_FileNotFoundError(self):
50        self.assertRaises(
51            FileNotFoundError, resources.open_binary, self.data, 'does-not-exist'
52        )
53
54    def test_open_text_FileNotFoundError(self):
55        self.assertRaises(
56            FileNotFoundError, resources.open_text, self.data, 'does-not-exist'
57        )
58
59
60class OpenDiskTests(OpenTests, unittest.TestCase):
61    def setUp(self):
62        self.data = data01
63
64
65class OpenDiskNamespaceTests(OpenTests, unittest.TestCase):
66    def setUp(self):
67        from . import namespacedata01
68
69        self.data = namespacedata01
70
71
72class OpenZipTests(OpenTests, util.ZipSetup, unittest.TestCase):
73    pass
74
75
76if __name__ == '__main__':
77    unittest.main()
78