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( 29 self.data, 'utf-16.file', encoding='utf-16') 30 self.assertEqual(result, 'Hello, UTF-16 world!\n') 31 32 def test_read_text_with_errors(self): 33 # Raises UnicodeError without the 'errors' argument. 34 self.assertRaises( 35 UnicodeError, resources.read_text, self.data, 'utf-16.file') 36 result = resources.read_text(self.data, 'utf-16.file', errors='ignore') 37 self.assertEqual( 38 result, 39 'H\x00e\x00l\x00l\x00o\x00,\x00 ' 40 '\x00U\x00T\x00F\x00-\x001\x006\x00 ' 41 '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00') 42 43 44class ReadDiskTests(ReadTests, unittest.TestCase): 45 data = data01 46 47 48class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase): 49 def test_read_submodule_resource(self): 50 submodule = import_module('ziptestdata.subdirectory') 51 result = resources.read_binary( 52 submodule, 'binary.file') 53 self.assertEqual(result, b'\0\1\2\3') 54 55 def test_read_submodule_resource_by_name(self): 56 result = resources.read_binary( 57 'ziptestdata.subdirectory', 'binary.file') 58 self.assertEqual(result, b'\0\1\2\3') 59 60 61if __name__ == '__main__': 62 unittest.main() 63