Skip to content

Commit

Permalink
Consolidate MemoryTraversable._resolve.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jan 3, 2025
1 parent d001110 commit 30bc726
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions importlib_resources/tests/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,18 @@ def __init__(self, module, fullname):
self._module = module
self._fullname = fullname

def iterdir(self):
def _resolve(self):
"""
Fully traverse the `fixtures` dictionary.
This should be wrapped in a `try/except KeyError`
but it is not currently needed and lowers the code coverage numbers.
"""
path = pathlib.PurePosixPath(self._fullname)
directory = functools.reduce(lambda d, p: d[p], path.parts, fixtures)
return functools.reduce(lambda d, p: d[p], path.parts, fixtures)

def iterdir(self):
directory = self._resolve()
if not isinstance(directory, dict):
# Filesystem openers raise OSError, and that exception is mirrored here.
raise OSError(f"{self._fullname} is not a directory")
Expand All @@ -272,21 +281,15 @@ def iterdir(self):
)

def is_dir(self) -> bool:
path = pathlib.PurePosixPath(self._fullname)
# Fully traverse the `fixtures` dictionary.
# This should be wrapped in a `try/except KeyError`
# but it is not currently needed, and lowers the code coverage numbers.
directory = functools.reduce(lambda d, p: d[p], path.parts, fixtures)
directory = self._resolve()
return isinstance(directory, dict)

def is_file(self) -> bool:
path = pathlib.PurePosixPath(self._fullname)
directory = functools.reduce(lambda d, p: d[p], path.parts, fixtures)
directory = self._resolve()
return not isinstance(directory, dict)

def open(self, mode='r', encoding=None, errors=None, *_, **__):
path = pathlib.PurePosixPath(self._fullname)
contents = functools.reduce(lambda d, p: d[p], path.parts, fixtures)
contents = self._resolve()
if isinstance(contents, dict):
# Filesystem openers raise OSError when attempting to open a directory,
# and that exception is mirrored here.
Expand Down

0 comments on commit 30bc726

Please sign in to comment.