|
| 1 | +import io |
| 2 | +import os.path |
| 3 | +import pathlib |
| 4 | +import sys |
| 5 | +import unittest |
| 6 | + |
| 7 | +import importlib_resources as resources |
| 8 | +from importlib_resources.tests import data |
| 9 | + |
| 10 | + |
| 11 | +class CommonTests(unittest.TestCase): |
| 12 | + |
| 13 | + def test_package_name(self): |
| 14 | + # Passing in the package name should succeed. |
| 15 | + resources.read(data.__name__, 'utf-8.file') |
| 16 | + |
| 17 | + def test_package_object(self): |
| 18 | + # Passing in the package itself should succeed. |
| 19 | + resources.read(data, 'utf-8.file') |
| 20 | + |
| 21 | + def test_string_path(self): |
| 22 | + path = 'utf-8.file' |
| 23 | + # Passing in a string for the path should succeed. |
| 24 | + resources.read(data, path) |
| 25 | + |
| 26 | + @unittest.skipIf(sys.version_info < (3, 6), 'requires os.PathLike support') |
| 27 | + def test_pathlib_path(self): |
| 28 | + # Passing in a pathlib.PurePath object for the path should succeed. |
| 29 | + path = pathlib.PurePath('utf-8.file') |
| 30 | + resources.read(data, path) |
| 31 | + |
| 32 | + def test_absolute_path(self): |
| 33 | + # An absolute path is a ValueError. |
| 34 | + path = pathlib.Path(__file__) |
| 35 | + full_path = path.parent/'utf-8.file' |
| 36 | + with self.assertRaises(ValueError): |
| 37 | + resources.read(data, str(full_path)) |
| 38 | + |
| 39 | + def test_relative_path(self): |
| 40 | + # A reative path is a ValueError. |
| 41 | + with self.assertRaises(ValueError): |
| 42 | + resources.read(data, '../data/utf-8.file') |
| 43 | + |
| 44 | + def test_importing_module_as_side_effect(self): |
| 45 | + # The anchor package can already be imported. |
| 46 | + del sys.modules[data.__name__] |
| 47 | + resources.read(data.__name__, 'utf-8.file') |
| 48 | + |
| 49 | + def test_non_package(self): |
| 50 | + # The anchor package cannot be a module. |
| 51 | + with self.assertRaises(TypeError): |
| 52 | + resources.read(__spec__.name, 'utf-8.file') |
| 53 | + |
| 54 | + |
| 55 | +class ReadTests(unittest.TestCase): |
| 56 | + |
| 57 | + def test_default_encoding(self): |
| 58 | + result = resources.read(data, 'utf-8.file') |
| 59 | + self.assertEqual("Hello, UTF-8 world!\n", result) |
| 60 | + |
| 61 | + def test_encoding(self): |
| 62 | + result = resources.read(data, 'utf-16.file', encoding='utf-16') |
| 63 | + self.assertEqual("Hello, UTF-16 world!\n", result) |
| 64 | + |
| 65 | + def test_errors(self): |
| 66 | + # Raises UnicodeError without the 'errors' argument. |
| 67 | + result = resources.read(data, 'utf-16.file', encoding='utf-8', |
| 68 | + errors='ignore') |
0 commit comments