Skip to content

Replace tests of legacy API with comparable tests of traversable API. #239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Oct 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ omit =
# leading `*/` for pytest-dev/pytest-cov#456
*/.tox/*
*/_itertools.py
*/_legacy.py

[report]
show_missing = True
6 changes: 6 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
v5.4.0
======

* *80: Test suite now relies entirely on the traversable
API.

v5.3.0
======

Expand Down
15 changes: 1 addition & 14 deletions importlib_resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import types
import importlib

from typing import Union, Any, Optional
from typing import Union, Optional
from .abc import ResourceReader, Traversable

from ._compat import wrap_spec
Expand All @@ -23,19 +23,6 @@ def files(package):
return from_package(get_package(package))


def normalize_path(path):
# type: (Any) -> str
"""Normalize a path by ensuring it is a string.

If the resulting string contains path separators, an exception is raised.
"""
str_path = str(path)
parent, file_name = os.path.split(str_path)
if parent:
raise ValueError(f'{path!r} must be only a file name')
return file_name


def get_resource_reader(package):
# type: (types.ModuleType) -> Optional[ResourceReader]
"""
Expand Down
25 changes: 19 additions & 6 deletions importlib_resources/_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import types
import warnings

from typing import Union, Iterable, ContextManager, BinaryIO, TextIO
from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any

from . import _common

Expand All @@ -27,16 +27,29 @@ def wrapper(*args, **kwargs):
return wrapper


def normalize_path(path):
# type: (Any) -> str
"""Normalize a path by ensuring it is a string.

If the resulting string contains path separators, an exception is raised.
"""
str_path = str(path)
parent, file_name = os.path.split(str_path)
if parent:
raise ValueError(f'{path!r} must be only a file name')
return file_name


@deprecated
def open_binary(package: Package, resource: Resource) -> BinaryIO:
"""Return a file-like object opened for binary reading of the resource."""
return (_common.files(package) / _common.normalize_path(resource)).open('rb')
return (_common.files(package) / normalize_path(resource)).open('rb')


@deprecated
def read_binary(package: Package, resource: Resource) -> bytes:
"""Return the binary contents of the resource."""
return (_common.files(package) / _common.normalize_path(resource)).read_bytes()
return (_common.files(package) / normalize_path(resource)).read_bytes()


@deprecated
Expand All @@ -47,7 +60,7 @@ def open_text(
errors: str = 'strict',
) -> TextIO:
"""Return a file-like object opened for text reading of the resource."""
return (_common.files(package) / _common.normalize_path(resource)).open(
return (_common.files(package) / normalize_path(resource)).open(
'r', encoding=encoding, errors=errors
)

Expand Down Expand Up @@ -85,7 +98,7 @@ def is_resource(package: Package, name: str) -> bool:

Directories are *not* resources.
"""
resource = _common.normalize_path(name)
resource = normalize_path(name)
return any(
traversable.name == resource and traversable.is_file()
for traversable in _common.files(package).iterdir()
Expand All @@ -105,4 +118,4 @@ def path(
raised if the file was deleted prior to the context manager
exiting).
"""
return _common.as_file(_common.files(package) / _common.normalize_path(resource))
return _common.as_file(_common.files(package) / normalize_path(resource))
4 changes: 2 additions & 2 deletions importlib_resources/tests/test_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class ContentsTests:
}

def test_contents(self):
with util.suppress_known_deprecation():
assert self.expected <= set(resources.contents(self.data))
contents = {path.name for path in resources.files(self.data).iterdir()}
assert self.expected <= contents


class ContentsDiskTests(ContentsTests, unittest.TestCase):
Expand Down
57 changes: 25 additions & 32 deletions importlib_resources/tests/test_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,44 @@

class CommonBinaryTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with util.suppress_known_deprecation():
with resources.open_binary(package, path):
pass
target = resources.files(package).joinpath(path)
with target.open('rb'):
pass


class CommonTextTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with util.suppress_known_deprecation():
with resources.open_text(package, path):
pass
target = resources.files(package).joinpath(path)
with target.open():
pass


class OpenTests:
def test_open_binary(self):
with util.suppress_known_deprecation():
with resources.open_binary(self.data, 'binary.file') as fp:
result = fp.read()
self.assertEqual(result, b'\x00\x01\x02\x03')
target = resources.files(self.data) / 'binary.file'
with target.open('rb') as fp:
result = fp.read()
self.assertEqual(result, b'\x00\x01\x02\x03')

def test_open_text_default_encoding(self):
with util.suppress_known_deprecation():
with resources.open_text(self.data, 'utf-8.file') as fp:
result = fp.read()
target = resources.files(self.data) / 'utf-8.file'
with target.open() as fp:
result = fp.read()
self.assertEqual(result, 'Hello, UTF-8 world!\n')

def test_open_text_given_encoding(self):
with util.suppress_known_deprecation():
with resources.open_text(
self.data, 'utf-16.file', 'utf-16', 'strict'
) as fp:
result = fp.read()
target = resources.files(self.data) / 'utf-16.file'
with target.open(encoding='utf-16', errors='strict') as fp:
result = fp.read()
self.assertEqual(result, 'Hello, UTF-16 world!\n')

def test_open_text_with_errors(self):
# Raises UnicodeError without the 'errors' argument.
with util.suppress_known_deprecation():
with resources.open_text(self.data, 'utf-16.file', 'utf-8', 'strict') as fp:
self.assertRaises(UnicodeError, fp.read)
with util.suppress_known_deprecation():
with resources.open_text(self.data, 'utf-16.file', 'utf-8', 'ignore') as fp:
result = fp.read()
target = resources.files(self.data) / 'utf-16.file'
with target.open(encoding='utf-8', errors='strict') as fp:
self.assertRaises(UnicodeError, fp.read)
with target.open(encoding='utf-8', errors='ignore') as fp:
result = fp.read()
self.assertEqual(
result,
'H\x00e\x00l\x00l\x00o\x00,\x00 '
Expand All @@ -56,16 +53,12 @@ def test_open_text_with_errors(self):
)

def test_open_binary_FileNotFoundError(self):
with util.suppress_known_deprecation():
self.assertRaises(
FileNotFoundError, resources.open_binary, self.data, 'does-not-exist'
)
target = resources.files(self.data) / 'does-not-exist'
self.assertRaises(FileNotFoundError, target.open, 'rb')

def test_open_text_FileNotFoundError(self):
with util.suppress_known_deprecation():
self.assertRaises(
FileNotFoundError, resources.open_text, self.data, 'does-not-exist'
)
target = resources.files(self.data) / 'does-not-exist'
self.assertRaises(FileNotFoundError, target.open)


class OpenDiskTests(OpenTests, unittest.TestCase):
Expand Down
31 changes: 15 additions & 16 deletions importlib_resources/tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,22 @@

class CommonTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with util.suppress_known_deprecation():
with resources.path(package, path):
pass
with resources.as_file(resources.files(package).joinpath(path)):
pass


class PathTests:
def test_reading(self):
# Path should be readable.
# Test also implicitly verifies the returned object is a pathlib.Path
# instance.
with util.suppress_known_deprecation():
with resources.path(self.data, 'utf-8.file') as path:
self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
# pathlib.Path.read_text() was introduced in Python 3.5.
with path.open('r', encoding='utf-8') as file:
text = file.read()
self.assertEqual('Hello, UTF-8 world!\n', text)
target = resources.files(self.data) / 'utf-8.file'
with resources.as_file(target) as path:
self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
# pathlib.Path.read_text() was introduced in Python 3.5.
with path.open('r', encoding='utf-8') as file:
text = file.read()
self.assertEqual('Hello, UTF-8 world!\n', text)


class PathDiskTests(PathTests, unittest.TestCase):
Expand All @@ -36,9 +35,9 @@ def test_natural_path(self):
file-system-backed resources do not get the tempdir
treatment.
"""
with util.suppress_known_deprecation():
with resources.path(self.data, 'utf-8.file') as path:
assert 'data' in str(path)
target = resources.files(self.data) / 'utf-8.file'
with resources.as_file(target) as path:
assert 'data' in str(path)


class PathMemoryTests(PathTests, unittest.TestCase):
Expand All @@ -56,9 +55,9 @@ class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
def test_remove_in_context_manager(self):
# It is not an error if the file that was temporarily stashed on the
# file system is removed inside the `with` stanza.
with util.suppress_known_deprecation():
with resources.path(self.data, 'utf-8.file') as path:
path.unlink()
target = resources.files(self.data) / 'utf-8.file'
with resources.as_file(target) as path:
path.unlink()


if __name__ == '__main__':
Expand Down
40 changes: 19 additions & 21 deletions importlib_resources/tests/test_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,40 +8,36 @@

class CommonBinaryTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with util.suppress_known_deprecation():
resources.read_binary(package, path)
resources.files(package).joinpath(path).read_bytes()


class CommonTextTests(util.CommonTests, unittest.TestCase):
def execute(self, package, path):
with util.suppress_known_deprecation():
resources.read_text(package, path)
resources.files(package).joinpath(path).read_text()


class ReadTests:
def test_read_binary(self):
with util.suppress_known_deprecation():
result = resources.read_binary(self.data, 'binary.file')
def test_read_bytes(self):
result = resources.files(self.data).joinpath('binary.file').read_bytes()
self.assertEqual(result, b'\0\1\2\3')

def test_read_text_default_encoding(self):
with util.suppress_known_deprecation():
result = resources.read_text(self.data, 'utf-8.file')
result = resources.files(self.data).joinpath('utf-8.file').read_text()
self.assertEqual(result, 'Hello, UTF-8 world!\n')

def test_read_text_given_encoding(self):
with util.suppress_known_deprecation():
result = resources.read_text(self.data, 'utf-16.file', encoding='utf-16')
result = (
resources.files(self.data)
.joinpath('utf-16.file')
.read_text(encoding='utf-16')
)
self.assertEqual(result, 'Hello, UTF-16 world!\n')

def test_read_text_with_errors(self):
# Raises UnicodeError without the 'errors' argument.
with util.suppress_known_deprecation():
self.assertRaises(
UnicodeError, resources.read_text, self.data, 'utf-16.file'
)
with util.suppress_known_deprecation():
result = resources.read_text(self.data, 'utf-16.file', errors='ignore')
target = resources.files(self.data) / 'utf-16.file'
self.assertRaises(UnicodeError, target.read_text, encoding='utf-8')
result = target.read_text(encoding='utf-8', errors='ignore')
self.assertEqual(
result,
'H\x00e\x00l\x00l\x00o\x00,\x00 '
Expand All @@ -57,13 +53,15 @@ class ReadDiskTests(ReadTests, unittest.TestCase):
class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase):
def test_read_submodule_resource(self):
submodule = import_module('ziptestdata.subdirectory')
with util.suppress_known_deprecation():
result = resources.read_binary(submodule, 'binary.file')
result = resources.files(submodule).joinpath('binary.file').read_bytes()
self.assertEqual(result, b'\0\1\2\3')

def test_read_submodule_resource_by_name(self):
with util.suppress_known_deprecation():
result = resources.read_binary('ziptestdata.subdirectory', 'binary.file')
result = (
resources.files('ziptestdata.subdirectory')
.joinpath('binary.file')
.read_bytes()
)
self.assertEqual(result, b'\0\1\2\3')


Expand Down
Loading