diff --git a/importlib_resources/_common.py b/importlib_resources/_common.py index 9bb6bda5..5d5e7a72 100644 --- a/importlib_resources/_common.py +++ b/importlib_resources/_common.py @@ -109,8 +109,17 @@ def as_file(path): @as_file.register(pathlib.Path) @contextlib.contextmanager -def _(path): +def _as_file_pathlib(path): """ Degenerate behavior for pathlib.Path objects. """ yield path + + +@as_file.register(os.PathLike) +@contextlib.contextmanager +def _as_file_pathlike(path): + """ + Degenerate behavior for os.PathLike objects. + """ + yield pathlib.Path(os.fspath(path)) diff --git a/importlib_resources/tests/test_path.py b/importlib_resources/tests/test_path.py index 9180626f..63f575ab 100644 --- a/importlib_resources/tests/test_path.py +++ b/importlib_resources/tests/test_path.py @@ -1,7 +1,10 @@ import io +import os +import pathlib import unittest import importlib_resources as resources +from importlib_resources.abc import TraversableResources from . import data01 from . import util @@ -57,5 +60,39 @@ def test_remove_in_context_manager(self): path.unlink() +class PathLikeTests(PathTests, unittest.TestCase): + class PathLikeTraversable: + """pathlib.Path proxy, is os.PathLike but is not pathlib.Path""" + + def __init__(self, *args, **kwargs): + self._path = pathlib.Path(*args, **kwargs) + + def __fspath__(self): + return os.fspath(self._path) + + def joinpath(self, other): + return self.__class__(self, other) + + __truediv__ = joinpath + + @property + def parent(self): + return self.__class__(self._path.parent) + + class PathLikeResources(TraversableResources): + def __init__(self, loader): + self.path = PathLikeTests.PathLikeTraversable(loader.path).parent + + def get_resource_reader(self, package): + return self + + def files(self): + return self.path + + def setUp(self): + reader = self.PathLikeResources(data01.__loader__) + self.data = util.create_package_from_loader(reader) + + if __name__ == '__main__': unittest.main()