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