• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import unittest
2
3from importlib import import_module, resources
4from . import data01
5from . import util
6
7
8class CommonBinaryTests(util.CommonResourceTests, unittest.TestCase):
9    def execute(self, package, path):
10        resources.read_binary(package, path)
11
12
13class CommonTextTests(util.CommonResourceTests, unittest.TestCase):
14    def execute(self, package, path):
15        resources.read_text(package, path)
16
17
18class ReadTests:
19    def test_read_binary(self):
20        result = resources.read_binary(self.data, 'binary.file')
21        self.assertEqual(result, b'\0\1\2\3')
22
23    def test_read_text_default_encoding(self):
24        result = resources.read_text(self.data, 'utf-8.file')
25        self.assertEqual(result, 'Hello, UTF-8 world!\n')
26
27    def test_read_text_given_encoding(self):
28        result = resources.read_text(self.data, 'utf-16.file', encoding='utf-16')
29        self.assertEqual(result, 'Hello, UTF-16 world!\n')
30
31    def test_read_text_with_errors(self):
32        # Raises UnicodeError without the 'errors' argument.
33        self.assertRaises(UnicodeError, resources.read_text, self.data, 'utf-16.file')
34        result = resources.read_text(self.data, 'utf-16.file', errors='ignore')
35        self.assertEqual(
36            result,
37            'H\x00e\x00l\x00l\x00o\x00,\x00 '
38            '\x00U\x00T\x00F\x00-\x001\x006\x00 '
39            '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00',
40        )
41
42
43class ReadDiskTests(ReadTests, unittest.TestCase):
44    data = data01
45
46
47class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase):
48    def test_read_submodule_resource(self):
49        submodule = import_module('ziptestdata.subdirectory')
50        result = resources.read_binary(submodule, 'binary.file')
51        self.assertEqual(result, b'\0\1\2\3')
52
53    def test_read_submodule_resource_by_name(self):
54        result = resources.read_binary('ziptestdata.subdirectory', 'binary.file')
55        self.assertEqual(result, b'\0\1\2\3')
56
57
58if __name__ == '__main__':
59    unittest.main()
60