test_open.py 2.6 KB

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