1 import unittest 2 3 from importlib import resources 4 from . import data01 5 from . import util 6 7 8 class CommonBinaryTests(util.CommonResourceTests, unittest.TestCase): 9 def execute(self, package, path): 10 with resources.open_binary(package, path): 11 pass 12 13 14 class CommonTextTests(util.CommonResourceTests, unittest.TestCase): 15 def execute(self, package, path): 16 with resources.open_text(package, path): 17 pass 18 19 20 class 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( 33 self.data, 'utf-16.file', 'utf-16', 'strict') as fp: 34 result = fp.read() 35 self.assertEqual(result, 'Hello, UTF-16 world!\n') 36 37 def test_open_text_with_errors(self): 38 # Raises UnicodeError without the 'errors' argument. 39 with resources.open_text( 40 self.data, 'utf-16.file', 'utf-8', 'strict') as fp: 41 self.assertRaises(UnicodeError, fp.read) 42 with resources.open_text( 43 self.data, 'utf-16.file', 'utf-8', 'ignore') as fp: 44 result = fp.read() 45 self.assertEqual( 46 result, 47 'H\x00e\x00l\x00l\x00o\x00,\x00 ' 48 '\x00U\x00T\x00F\x00-\x001\x006\x00 ' 49 '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00') 50 51 def test_open_binary_FileNotFoundError(self): 52 self.assertRaises( 53 FileNotFoundError, 54 resources.open_binary, self.data, 'does-not-exist') 55 56 def test_open_text_FileNotFoundError(self): 57 self.assertRaises( 58 FileNotFoundError, 59 resources.open_text, self.data, 'does-not-exist') 60 61 62 class OpenDiskTests(OpenTests, unittest.TestCase): 63 def setUp(self): 64 self.data = data01 65 66 67 class OpenZipTests(OpenTests, util.ZipSetup, unittest.TestCase): 68 pass 69 70 71 if __name__ == '__main__': 72 unittest.main() 73