PK!U __init__.pynu["""Read resources contained within a package.""" import sys from ._compat import metadata from ._common import as_file # for compatibility. Ref #88 __import__('importlib_resources.trees') __all__ = [ 'Package', 'Resource', 'ResourceReader', 'as_file', 'contents', 'files', 'is_resource', 'open_binary', 'open_text', 'path', 'read_binary', 'read_text', ] if sys.version_info >= (3,): from importlib_resources._py3 import ( Package, Resource, contents, files, is_resource, open_binary, open_text, path, read_binary, read_text, ) from importlib_resources.abc import ResourceReader else: from importlib_resources._py2 import ( contents, files, is_resource, open_binary, open_text, path, read_binary, read_text, ) del __all__[:3] __version__ = metadata.version('importlib_resources') PK!t`0II _common.pynu[from __future__ import absolute_import import os import tempfile import contextlib from ._compat import ( Path, package_spec, FileNotFoundError, ZipPath, singledispatch, suppress, ) def from_package(package): """ Return a Traversable object for the given package. """ spec = package_spec(package) return from_traversable_resources(spec) or fallback_resources(spec) def from_traversable_resources(spec): """ If the spec.loader implements TraversableResources, directly or implicitly, it will have a ``files()`` method. """ with suppress(AttributeError): return spec.loader.files() def fallback_resources(spec): package_directory = Path(spec.origin).parent try: archive_path = spec.loader.archive rel_path = package_directory.relative_to(archive_path) return ZipPath(archive_path, str(rel_path) + '/') except Exception: pass return package_directory @contextlib.contextmanager def _tempfile(reader, suffix=''): # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' # blocks due to the need to close the temporary file to work on Windows # properly. fd, raw_path = tempfile.mkstemp(suffix=suffix) try: os.write(fd, reader()) os.close(fd) yield Path(raw_path) finally: try: os.remove(raw_path) except FileNotFoundError: pass @singledispatch @contextlib.contextmanager def as_file(path): """ Given a Traversable object, return that object as a path on the local file system in a context manager. """ with _tempfile(path.read_bytes, suffix=path.name) as local: yield local @as_file.register(Path) @contextlib.contextmanager def _(path): """ Degenerate behavior for pathlib.Path objects. """ yield path PK! 1 _compat.pynu[from __future__ import absolute_import # flake8: noqa try: from pathlib import Path, PurePath except ImportError: from pathlib2 import Path, PurePath # type: ignore try: from contextlib import suppress except ImportError: from contextlib2 import suppress # type: ignore try: from functools import singledispatch except ImportError: from singledispatch import singledispatch # type: ignore try: from abc import ABC # type: ignore except ImportError: from abc import ABCMeta class ABC(object): # type: ignore __metaclass__ = ABCMeta try: FileNotFoundError = FileNotFoundError # type: ignore except NameError: FileNotFoundError = OSError # type: ignore try: from importlib import metadata except ImportError: import importlib_metadata as metadata # type: ignore try: from zipfile import Path as ZipPath # type: ignore except ImportError: from zipp import Path as ZipPath # type: ignore try: from typing import runtime_checkable # type: ignore except ImportError: def runtime_checkable(cls): # type: ignore return cls try: from typing import Protocol # type: ignore except ImportError: Protocol = ABC # type: ignore class PackageSpec(object): def __init__(self, **kwargs): vars(self).update(kwargs) def package_spec(package): return getattr(package, '__spec__', None) or \ PackageSpec( origin=package.__file__, loader=getattr(package, '__loader__', None), ) PK!~d%j_py2.pynu[import os import errno from . import _common from ._compat import FileNotFoundError from importlib import import_module from io import BytesIO, TextIOWrapper, open as io_open def _resolve(name): """If name is a string, resolve to a module.""" if not isinstance(name, basestring): # noqa: F821 return name return import_module(name) def _get_package(package): """Normalize a path by ensuring it is a string. If the resulting string contains path separators, an exception is raised. """ module = _resolve(package) if not hasattr(module, '__path__'): raise TypeError("{!r} is not a package".format(package)) return module def _normalize_path(path): """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("{!r} must be only a file name".format(path)) return file_name def open_binary(package, resource): """Return a file-like object opened for binary reading of the resource.""" resource = _normalize_path(resource) package = _get_package(package) # Using pathlib doesn't work well here due to the lack of 'strict' argument # for pathlib.Path.resolve() prior to Python 3.6. package_path = os.path.dirname(package.__file__) relative_path = os.path.join(package_path, resource) full_path = os.path.abspath(relative_path) try: return io_open(full_path, 'rb') except IOError: # This might be a package in a zip file. zipimport provides a loader # with a functioning get_data() method, however we have to strip the # archive (i.e. the .zip file's name) off the front of the path. This # is because the zipimport loader in Python 2 doesn't actually follow # PEP 302. It should allow the full path, but actually requires that # the path be relative to the zip file. try: loader = package.__loader__ full_path = relative_path[len(loader.archive)+1:] data = loader.get_data(full_path) except (IOError, AttributeError): package_name = package.__name__ message = '{!r} resource not found in {!r}'.format( resource, package_name) raise FileNotFoundError(message) return BytesIO(data) def open_text(package, resource, encoding='utf-8', errors='strict'): """Return a file-like object opened for text reading of the resource.""" return TextIOWrapper( open_binary(package, resource), encoding=encoding, errors=errors) def read_binary(package, resource): """Return the binary contents of the resource.""" with open_binary(package, resource) as fp: return fp.read() def read_text(package, resource, encoding='utf-8', errors='strict'): """Return the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode(). """ with open_text(package, resource, encoding, errors) as fp: return fp.read() def files(package): return _common.from_package(_get_package(package)) def path(package, resource): """A context manager providing a file path object to the resource. If the resource does not already exist on its own on the file system, a temporary file will be created. If the file was created, the file will be deleted upon exiting the context manager (no exception is raised if the file was deleted prior to the context manager exiting). """ path = files(package).joinpath(_normalize_path(resource)) if not path.is_file(): raise FileNotFoundError(path) return _common.as_file(path) def is_resource(package, name): """True if name is a resource inside package. Directories are *not* resources. """ package = _get_package(package) _normalize_path(name) try: package_contents = set(contents(package)) except OSError as error: if error.errno not in (errno.ENOENT, errno.ENOTDIR): # We won't hit this in the Python 2 tests, so it'll appear # uncovered. We could mock os.listdir() to return a non-ENOENT or # ENOTDIR, but then we'd have to depend on another external # library since Python 2 doesn't have unittest.mock. It's not # worth it. raise # pragma: nocover return False if name not in package_contents: return False return (_common.from_package(package) / name).is_file() def contents(package): """Return an iterable of entries in `package`. Note that not all entries are resources. Specifically, directories are not considered resources. Use `is_resource()` on each entry returned here to check if it is a resource or not. """ package = _get_package(package) return list(item.name for item in _common.from_package(package).iterdir()) PK!Z^  _py3.pynu[import os import sys from . import abc as resources_abc from . import _common from contextlib import contextmanager, suppress from importlib import import_module from importlib.abc import ResourceLoader from io import BytesIO, TextIOWrapper from pathlib import Path from types import ModuleType from typing import Iterable, Iterator, Optional, Set, Union # noqa: F401 from typing import cast from typing.io import BinaryIO, TextIO if False: # TYPE_CHECKING from typing import ContextManager Package = Union[ModuleType, str] if sys.version_info >= (3, 6): Resource = Union[str, os.PathLike] # pragma: <=35 else: Resource = str # pragma: >=36 def _resolve(name) -> ModuleType: """If name is a string, resolve to a module.""" if hasattr(name, '__spec__'): return name return import_module(name) def _get_package(package) -> ModuleType: """Take a package name or module object and return the module. If a name, the module is imported. If the resolved module object is not a package, raise an exception. """ module = _resolve(package) if module.__spec__.submodule_search_locations is None: raise TypeError('{!r} is not a package'.format(package)) return module def _normalize_path(path) -> 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('{!r} must be only a file name'.format(path)) return file_name def _get_resource_reader( package: ModuleType) -> Optional[resources_abc.ResourceReader]: # Return the package's loader if it's a ResourceReader. We can't use # a issubclass() check here because apparently abc.'s __subclasscheck__() # hook wants to create a weak reference to the object, but # zipimport.zipimporter does not support weak references, resulting in a # TypeError. That seems terrible. spec = package.__spec__ reader = getattr(spec.loader, 'get_resource_reader', None) if reader is None: return None return cast(resources_abc.ResourceReader, reader(spec.name)) def open_binary(package: Package, resource: Resource) -> BinaryIO: """Return a file-like object opened for binary reading of the resource.""" resource = _normalize_path(resource) package = _get_package(package) reader = _get_resource_reader(package) if reader is not None: return reader.open_resource(resource) # Using pathlib doesn't work well here due to the lack of 'strict' # argument for pathlib.Path.resolve() prior to Python 3.6. absolute_package_path = os.path.abspath( package.__spec__.origin or 'non-existent file') package_path = os.path.dirname(absolute_package_path) full_path = os.path.join(package_path, resource) try: return open(full_path, mode='rb') except OSError: # Just assume the loader is a resource loader; all the relevant # importlib.machinery loaders are and an AttributeError for # get_data() will make it clear what is needed from the loader. loader = cast(ResourceLoader, package.__spec__.loader) data = None if hasattr(package.__spec__.loader, 'get_data'): with suppress(OSError): data = loader.get_data(full_path) if data is None: package_name = package.__spec__.name message = '{!r} resource not found in {!r}'.format( resource, package_name) raise FileNotFoundError(message) return BytesIO(data) def open_text(package: Package, resource: Resource, encoding: str = 'utf-8', errors: str = 'strict') -> TextIO: """Return a file-like object opened for text reading of the resource.""" return TextIOWrapper( open_binary(package, resource), encoding=encoding, errors=errors) def read_binary(package: Package, resource: Resource) -> bytes: """Return the binary contents of the resource.""" with open_binary(package, resource) as fp: return fp.read() def read_text(package: Package, resource: Resource, encoding: str = 'utf-8', errors: str = 'strict') -> str: """Return the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode(). """ with open_text(package, resource, encoding, errors) as fp: return fp.read() def files(package: Package) -> resources_abc.Traversable: """ Get a Traversable resource from a package """ return _common.from_package(_get_package(package)) def path( package: Package, resource: Resource, ) -> 'ContextManager[Path]': """A context manager providing a file path object to the resource. If the resource does not already exist on its own on the file system, a temporary file will be created. If the file was created, the file will be deleted upon exiting the context manager (no exception is raised if the file was deleted prior to the context manager exiting). """ reader = _get_resource_reader(_get_package(package)) return ( _path_from_reader(reader, resource) if reader else _common.as_file(files(package).joinpath(_normalize_path(resource))) ) @contextmanager def _path_from_reader(reader, resource): norm_resource = _normalize_path(resource) with suppress(FileNotFoundError): yield Path(reader.resource_path(norm_resource)) return opener_reader = reader.open_resource(norm_resource) with _common._tempfile(opener_reader.read, suffix=norm_resource) as res: yield res def is_resource(package: Package, name: str) -> bool: """True if `name` is a resource inside `package`. Directories are *not* resources. """ package = _get_package(package) _normalize_path(name) reader = _get_resource_reader(package) if reader is not None: return reader.is_resource(name) package_contents = set(contents(package)) if name not in package_contents: return False return (_common.from_package(package) / name).is_file() def contents(package: Package) -> Iterable[str]: """Return an iterable of entries in `package`. Note that not all entries are resources. Specifically, directories are not considered resources. Use `is_resource()` on each entry returned here to check if it is a resource or not. """ package = _get_package(package) reader = _get_resource_reader(package) if reader is not None: return reader.contents() # Is the package a namespace package? By definition, namespace packages # cannot have resources. namespace = ( package.__spec__.origin is None or package.__spec__.origin == 'namespace' ) if namespace or not package.__spec__.has_location: return () return list(item.name for item in _common.from_package(package).iterdir()) PK!I-55abc.pynu[from __future__ import absolute_import import abc from ._compat import ABC, FileNotFoundError, runtime_checkable, Protocol # Use mypy's comment syntax for Python 2 compatibility try: from typing import BinaryIO, Iterable, Text except ImportError: pass class ResourceReader(ABC): """Abstract base class for loaders to provide resource reading support.""" @abc.abstractmethod def open_resource(self, resource): # type: (Text) -> BinaryIO """Return an opened, file-like object for binary reading. The 'resource' argument is expected to represent only a file name. If the resource cannot be found, FileNotFoundError is raised. """ # This deliberately raises FileNotFoundError instead of # NotImplementedError so that if this method is accidentally called, # it'll still do the right thing. raise FileNotFoundError @abc.abstractmethod def resource_path(self, resource): # type: (Text) -> Text """Return the file system path to the specified resource. The 'resource' argument is expected to represent only a file name. If the resource does not exist on the file system, raise FileNotFoundError. """ # This deliberately raises FileNotFoundError instead of # NotImplementedError so that if this method is accidentally called, # it'll still do the right thing. raise FileNotFoundError @abc.abstractmethod def is_resource(self, path): # type: (Text) -> bool """Return True if the named 'path' is a resource. Files are resources, directories are not. """ raise FileNotFoundError @abc.abstractmethod def contents(self): # type: () -> Iterable[str] """Return an iterable of entries in `package`.""" raise FileNotFoundError @runtime_checkable class Traversable(Protocol): """ An object with a subset of pathlib.Path methods suitable for traversing directories and opening files. """ @abc.abstractmethod def iterdir(self): """ Yield Traversable objects in self """ @abc.abstractmethod def read_bytes(self): """ Read contents of self as bytes """ @abc.abstractmethod def read_text(self, encoding=None): """ Read contents of self as bytes """ @abc.abstractmethod def is_dir(self): """ Return True if self is a dir """ @abc.abstractmethod def is_file(self): """ Return True if self is a file """ @abc.abstractmethod def joinpath(self, child): """ Return Traversable child in self """ @abc.abstractmethod def __truediv__(self, child): """ Return Traversable child in self """ @abc.abstractmethod def open(self, mode='r', *args, **kwargs): """ mode may be 'r' or 'rb' to open as text or binary. Return a handle suitable for reading (same as pathlib.Path.open). When opening as text, accepts encoding parameters such as those accepted by io.TextIOWrapper. """ @abc.abstractproperty def name(self): # type: () -> str """ The base name of this object without any parent references. """ class TraversableResources(ResourceReader): @abc.abstractmethod def files(self): """Return a Traversable object for the loaded package.""" def open_resource(self, resource): return self.files().joinpath(resource).open('rb') def resource_path(self, resource): raise FileNotFoundError(resource) def is_resource(self, path): return self.files().joinpath(path).isfile() def contents(self): return (item.name for item in self.files().iterdir()) PK!"uutrees.pynu[# for compatibility with 1.1, continue to expose as_file here. from ._common import as_file __all__ = ['as_file'] PK!tests/__init__.pynu[PK!;tests/test_files.pynu[import typing import unittest import importlib_resources as resources from importlib_resources.abc import Traversable from . import data01 from . import util class FilesTests: def test_read_bytes(self): files = resources.files(self.data) actual = files.joinpath('utf-8.file').read_bytes() assert actual == b'Hello, UTF-8 world!\n' def test_read_text(self): files = resources.files(self.data) actual = files.joinpath('utf-8.file').read_text() assert actual == 'Hello, UTF-8 world!\n' @unittest.skipUnless( hasattr(typing, 'runtime_checkable'), "Only suitable when typing supports runtime_checkable", ) def test_traversable(self): assert isinstance(resources.files(self.data), Traversable) class OpenDiskTests(FilesTests, unittest.TestCase): def setUp(self): self.data = data01 class OpenZipTests(FilesTests, util.ZipSetup, unittest.TestCase): pass if __name__ == '__main__': unittest.main() PK!=tests/test_open.pynu[import unittest import importlib_resources as resources from . import data01 from . import util from .._compat import FileNotFoundError class CommonBinaryTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.open_binary(package, path): pass class CommonTextTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.open_text(package, path): pass class OpenTests: def test_open_binary(self): with resources.open_binary(self.data, 'utf-8.file') as fp: result = fp.read() self.assertEqual(result, b'Hello, UTF-8 world!\n') def test_open_text_default_encoding(self): with resources.open_text(self.data, 'utf-8.file') as fp: result = fp.read() self.assertEqual(result, 'Hello, UTF-8 world!\n') def test_open_text_given_encoding(self): with resources.open_text( self.data, 'utf-16.file', 'utf-16', '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 resources.open_text( self.data, 'utf-16.file', 'utf-8', 'strict') as fp: self.assertRaises(UnicodeError, fp.read) with resources.open_text( self.data, 'utf-16.file', 'utf-8', 'ignore') as fp: result = fp.read() self.assertEqual( result, 'H\x00e\x00l\x00l\x00o\x00,\x00 ' '\x00U\x00T\x00F\x00-\x001\x006\x00 ' '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00') def test_open_binary_FileNotFoundError(self): self.assertRaises( FileNotFoundError, resources.open_binary, self.data, 'does-not-exist') def test_open_text_FileNotFoundError(self): self.assertRaises( FileNotFoundError, resources.open_text, self.data, 'does-not-exist') class OpenDiskTests(OpenTests, unittest.TestCase): def setUp(self): self.data = data01 class OpenZipTests(OpenTests, util.ZipSetup, unittest.TestCase): pass if __name__ == '__main__': unittest.main() PK!9tests/test_path.pynu[import unittest import importlib_resources as resources from . import data01 from . import util class CommonTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): with resources.path(package, 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 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) class PathDiskTests(PathTests, unittest.TestCase): data = data01 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 resources.path(self.data, 'utf-8.file') as path: path.unlink() if __name__ == '__main__': unittest.main() PK!ltests/test_read.pynu[import unittest import importlib_resources as resources from . import data01 from . import util from importlib import import_module class CommonBinaryTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): resources.read_binary(package, path) class CommonTextTests(util.CommonTests, unittest.TestCase): def execute(self, package, path): resources.read_text(package, path) class ReadTests: def test_read_binary(self): result = resources.read_binary(self.data, 'binary.file') self.assertEqual(result, b'\0\1\2\3') def test_read_text_default_encoding(self): result = resources.read_text(self.data, 'utf-8.file') self.assertEqual(result, 'Hello, UTF-8 world!\n') def test_read_text_given_encoding(self): result = resources.read_text( self.data, 'utf-16.file', encoding='utf-16') self.assertEqual(result, 'Hello, UTF-16 world!\n') def test_read_text_with_errors(self): # Raises UnicodeError without the 'errors' argument. self.assertRaises( UnicodeError, resources.read_text, self.data, 'utf-16.file') result = resources.read_text(self.data, 'utf-16.file', errors='ignore') self.assertEqual( result, 'H\x00e\x00l\x00l\x00o\x00,\x00 ' '\x00U\x00T\x00F\x00-\x001\x006\x00 ' '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00') class ReadDiskTests(ReadTests, unittest.TestCase): data = data01 class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase): def test_read_submodule_resource(self): submodule = import_module('ziptestdata.subdirectory') result = resources.read_binary( submodule, 'binary.file') self.assertEqual(result, b'\0\1\2\3') def test_read_submodule_resource_by_name(self): result = resources.read_binary( 'ziptestdata.subdirectory', 'binary.file') self.assertEqual(result, b'\0\1\2\3') if __name__ == '__main__': unittest.main() PK!CCtests/test_resource.pynu[import sys import unittest import importlib_resources as resources from . import data01 from . import zipdata01, zipdata02 from . import util from importlib import import_module class ResourceTests: # Subclasses are expected to set the `data` attribute. def test_is_resource_good_path(self): self.assertTrue(resources.is_resource(self.data, 'binary.file')) def test_is_resource_missing(self): self.assertFalse(resources.is_resource(self.data, 'not-a-file')) def test_is_resource_subresource_directory(self): # Directories are not resources. self.assertFalse(resources.is_resource(self.data, 'subdirectory')) def test_contents(self): contents = set(resources.contents(self.data)) # There may be cruft in the directory listing of the data directory. # Under Python 3 we could have a __pycache__ directory, and under # Python 2 we could have .pyc files. These are both artifacts of the # test suite importing these modules and writing these caches. They # aren't germane to this test, so just filter them out. contents.discard('__pycache__') contents.discard('__init__.pyc') contents.discard('__init__.pyo') self.assertEqual(contents, { '__init__.py', 'subdirectory', 'utf-8.file', 'binary.file', 'utf-16.file', }) class ResourceDiskTests(ResourceTests, unittest.TestCase): def setUp(self): self.data = data01 class ResourceZipTests(ResourceTests, util.ZipSetup, unittest.TestCase): pass @unittest.skipIf(sys.version_info < (3,), 'No ResourceReader in Python 2') class ResourceLoaderTests(unittest.TestCase): def test_resource_contents(self): package = util.create_package( file=data01, path=data01.__file__, contents=['A', 'B', 'C']) self.assertEqual( set(resources.contents(package)), {'A', 'B', 'C'}) def test_resource_is_resource(self): package = util.create_package( file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F']) self.assertTrue(resources.is_resource(package, 'B')) def test_resource_directory_is_not_resource(self): package = util.create_package( file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F']) self.assertFalse(resources.is_resource(package, 'D')) def test_resource_missing_is_not_resource(self): package = util.create_package( file=data01, path=data01.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F']) self.assertFalse(resources.is_resource(package, 'Z')) class ResourceCornerCaseTests(unittest.TestCase): def test_package_has_no_reader_fallback(self): # Test odd ball packages which: # 1. Do not have a ResourceReader as a loader # 2. Are not on the file system # 3. Are not in a zip file module = util.create_package( file=data01, path=data01.__file__, contents=['A', 'B', 'C']) # Give the module a dummy loader. module.__loader__ = object() # Give the module a dummy origin. module.__file__ = '/path/which/shall/not/be/named' if sys.version_info >= (3,): module.__spec__.loader = module.__loader__ module.__spec__.origin = module.__file__ self.assertFalse(resources.is_resource(module, 'A')) class ResourceFromZipsTest01(util.ZipSetupBase, unittest.TestCase): ZIP_MODULE = zipdata01 # type: ignore def test_is_submodule_resource(self): submodule = import_module('ziptestdata.subdirectory') self.assertTrue( resources.is_resource(submodule, 'binary.file')) def test_read_submodule_resource_by_name(self): self.assertTrue( resources.is_resource('ziptestdata.subdirectory', 'binary.file')) def test_submodule_contents(self): submodule = import_module('ziptestdata.subdirectory') self.assertEqual( set(resources.contents(submodule)), {'__init__.py', 'binary.file'}) def test_submodule_contents_by_name(self): self.assertEqual( set(resources.contents('ziptestdata.subdirectory')), {'__init__.py', 'binary.file'}) class ResourceFromZipsTest02(util.ZipSetupBase, unittest.TestCase): ZIP_MODULE = zipdata02 # type: ignore def test_unrelated_contents(self): # https://gitlab.com/python-devs/importlib_resources/issues/44 # # Here we have a zip file with two unrelated subpackages. The bug # reports that getting the contents of a resource returns unrelated # files. self.assertEqual( set(resources.contents('ziptestdata.one')), {'__init__.py', 'resource1.txt'}) self.assertEqual( set(resources.contents('ziptestdata.two')), {'__init__.py', 'resource2.txt'}) @unittest.skipIf(sys.version_info < (3,), 'No namespace packages in Python 2') class NamespaceTest(unittest.TestCase): def test_namespaces_cannot_have_resources(self): contents = resources.contents( 'importlib_resources.tests.data03.namespace') self.assertFalse(list(contents)) # Even though there is a file in the namespace directory, it is not # considered a resource, since namespace packages can't have them. self.assertFalse(resources.is_resource( 'importlib_resources.tests.data03.namespace', 'resource1.txt')) # We should get an exception if we try to read it or open it. self.assertRaises( FileNotFoundError, resources.open_text, 'importlib_resources.tests.data03.namespace', 'resource1.txt') self.assertRaises( FileNotFoundError, resources.open_binary, 'importlib_resources.tests.data03.namespace', 'resource1.txt') self.assertRaises( FileNotFoundError, resources.read_text, 'importlib_resources.tests.data03.namespace', 'resource1.txt') self.assertRaises( FileNotFoundError, resources.read_binary, 'importlib_resources.tests.data03.namespace', 'resource1.txt') if __name__ == '__main__': unittest.main() PK!1lmDD tests/util.pynu[import abc import importlib import io import sys import types import unittest from . import data01 from . import zipdata01 from .._compat import ABC, Path, PurePath, FileNotFoundError from ..abc import ResourceReader try: from test.support import modules_setup, modules_cleanup except ImportError: # Python 2.7. def modules_setup(): return sys.modules.copy(), def modules_cleanup(oldmodules): # Encoders/decoders are registered permanently within the internal # codec cache. If we destroy the corresponding modules their # globals will be set to None which will trip up the cached functions. encodings = [(k, v) for k, v in sys.modules.items() if k.startswith('encodings.')] sys.modules.clear() sys.modules.update(encodings) # XXX: This kind of problem can affect more than just encodings. In # particular extension modules (such as _ssl) don't cope with reloading # properly. Really, test modules should be cleaning out the test # specific modules they know they added (ala test_runpy) rather than # relying on this function (as test_importhooks and test_pkg do # currently). Implicitly imported *real* modules should be left alone # (see issue 10556). sys.modules.update(oldmodules) try: from importlib.machinery import ModuleSpec except ImportError: ModuleSpec = None # type: ignore def create_package(file, path, is_package=True, contents=()): class Reader(ResourceReader): def get_resource_reader(self, package): return self def open_resource(self, path): self._path = path if isinstance(file, Exception): raise file else: return file def resource_path(self, path_): self._path = path_ if isinstance(path, Exception): raise path else: return path def is_resource(self, path_): self._path = path_ if isinstance(path, Exception): raise path for entry in contents: parts = entry.split('/') if len(parts) == 1 and parts[0] == path_: return True return False def contents(self): if isinstance(path, Exception): raise path # There's no yield from in baseball, er, Python 2. for entry in contents: yield entry name = 'testingpackage' # Unforunately importlib.util.module_from_spec() was not introduced until # Python 3.5. module = types.ModuleType(name) if ModuleSpec is None: # Python 2. module.__name__ = name module.__file__ = 'does-not-exist' if is_package: module.__path__ = [] else: # Python 3. loader = Reader() spec = ModuleSpec( name, loader, origin='does-not-exist', is_package=is_package) module.__spec__ = spec module.__loader__ = loader return module class CommonTests(ABC): @abc.abstractmethod def execute(self, package, path): raise NotImplementedError def test_package_name(self): # Passing in the package name should succeed. self.execute(data01.__name__, 'utf-8.file') def test_package_object(self): # Passing in the package itself should succeed. self.execute(data01, 'utf-8.file') def test_string_path(self): # Passing in a string for the path should succeed. path = 'utf-8.file' self.execute(data01, path) @unittest.skipIf(sys.version_info < (3, 6), 'requires os.PathLike support') def test_pathlib_path(self): # Passing in a pathlib.PurePath object for the path should succeed. path = PurePath('utf-8.file') self.execute(data01, path) def test_absolute_path(self): # An absolute path is a ValueError. path = Path(__file__) full_path = path.parent/'utf-8.file' with self.assertRaises(ValueError): self.execute(data01, full_path) def test_relative_path(self): # A reative path is a ValueError. with self.assertRaises(ValueError): self.execute(data01, '../data01/utf-8.file') def test_importing_module_as_side_effect(self): # The anchor package can already be imported. del sys.modules[data01.__name__] self.execute(data01.__name__, 'utf-8.file') def test_non_package_by_name(self): # The anchor package cannot be a module. with self.assertRaises(TypeError): self.execute(__name__, 'utf-8.file') def test_non_package_by_package(self): # The anchor package cannot be a module. with self.assertRaises(TypeError): module = sys.modules['importlib_resources.tests.util'] self.execute(module, 'utf-8.file') @unittest.skipIf(sys.version_info < (3,), 'No ResourceReader in Python 2') def test_resource_opener(self): bytes_data = io.BytesIO(b'Hello, world!') package = create_package(file=bytes_data, path=FileNotFoundError()) self.execute(package, 'utf-8.file') self.assertEqual(package.__loader__._path, 'utf-8.file') @unittest.skipIf(sys.version_info < (3,), 'No ResourceReader in Python 2') def test_resource_path(self): bytes_data = io.BytesIO(b'Hello, world!') path = __file__ package = create_package(file=bytes_data, path=path) self.execute(package, 'utf-8.file') self.assertEqual(package.__loader__._path, 'utf-8.file') def test_useless_loader(self): package = create_package(file=FileNotFoundError(), path=FileNotFoundError()) with self.assertRaises(FileNotFoundError): self.execute(package, 'utf-8.file') class ZipSetupBase: ZIP_MODULE = None @classmethod def setUpClass(cls): data_path = Path(cls.ZIP_MODULE.__file__) data_dir = data_path.parent cls._zip_path = str(data_dir / 'ziptestdata.zip') sys.path.append(cls._zip_path) cls.data = importlib.import_module('ziptestdata') @classmethod def tearDownClass(cls): try: sys.path.remove(cls._zip_path) except ValueError: pass try: del sys.path_importer_cache[cls._zip_path] del sys.modules[cls.data.__name__] except KeyError: pass try: del cls.data del cls._zip_path except AttributeError: pass def setUp(self): modules = modules_setup() self.addCleanup(modules_cleanup, *modules) class ZipSetup(ZipSetupBase): ZIP_MODULE = zipdata01 # type: ignore PK!tests/data01/__init__.pynu[PK!tests/data01/binary.filenu[PK!"<,,tests/data01/utf-16.filenu[Hello, UTF-16 world! PK!štests/data01/utf-8.filenu[Hello, UTF-8 world! PK!%tests/data01/subdirectory/__init__.pynu[PK!%tests/data01/subdirectory/binary.filenu[PK!`?K=tests/data01/subdirectory/__pycache__/__init__.cpython-38.pycnu[U af@sdS)Nrrrg/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/data01/subdirectory/__init__.pyPK!/0tests/data01/__pycache__/__init__.cpython-38.pycnu[U af@sdS)NrrrZ/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/data01/__init__.pyPK!tests/data02/__init__.pynu[PK!tests/data02/one/__init__.pynu[PK! tests/data02/one/resource1.txtnu[one resource PK!nھ4tests/data02/one/__pycache__/__init__.cpython-38.pycnu[U af@sdS)Nrrr^/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/data02/one/__init__.pyPK!tests/data02/two/__init__.pynu[PK!]o, tests/data02/two/resource2.txtnu[two resource PK!FQ4tests/data02/two/__pycache__/__init__.cpython-38.pycnu[U af@sdS)Nrrr^/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/data02/two/__init__.pyPK!F0$0tests/data02/__pycache__/__init__.cpython-38.pycnu[U af@sdS)NrrrZ/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/data02/__init__.pyPK!tests/data03/__init__.pynu[PK!$tests/data03/namespace/resource1.txtnu[PK!յ0tests/data03/__pycache__/__init__.cpython-38.pycnu[U af@sdS)NrrrZ/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/data03/__init__.pyPK!tests/zipdata01/__init__.pynu[PK!}Alltests/zipdata01/ziptestdata.zipnu[PKhK"<,,ziptestdata/utf-16.fileHello, UTF-16 world! PKhKšziptestdata/utf-8.fileHello, UTF-8 world! PKhKziptestdata/__init__.pyPKhKziptestdata/binary.filePKhK$ziptestdata/subdirectory/__init__.pyPKhK$ziptestdata/subdirectory/binary.filePKhK"<,,ziptestdata/utf-16.filePKhKšaziptestdata/utf-8.filePKhKziptestdata/__init__.pyPKhKziptestdata/binary.filePKhK$ziptestdata/subdirectory/__init__.pyPKhK$Yziptestdata/subdirectory/binary.filePKPK!vjո3tests/zipdata01/__pycache__/__init__.cpython-38.pycnu[U af@sdS)Nrrr]/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/zipdata01/__init__.pyPK!tests/zipdata02/__init__.pynu[PK!a K@tests/zipdata02/ziptestdata.zipnu[PKhKziptestdata/__init__.pyPKhKziptestdata/one/__init__.pyPKhK ziptestdata/one/resource1.txtone resource PKhKziptestdata/two/__init__.pyPKhK]o, ziptestdata/two/resource2.txttwo resource PKhKziptestdata/__init__.pyPKhK5ziptestdata/one/__init__.pyPKhK nziptestdata/one/resource1.txtPKhKziptestdata/two/__init__.pyPKhK]o, ziptestdata/two/resource2.txtPKm7PK!v~u3tests/zipdata02/__pycache__/__init__.cpython-38.pycnu[U af@sdS)Nrrr]/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/zipdata02/__init__.pyPK!k)tests/__pycache__/__init__.cpython-38.pycnu[U af@sdS)NrrrS/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/__init__.pyPK!==+tests/__pycache__/test_files.cpython-38.pycnu[U af@sddlZddlZddlZddlmZddlmZddlmZGdddZ Gdd d e ej Z Gd d d e ej ej Z ed kredS) N) Traversable)data01)utilc@s6eZdZddZddZeeeddddZ d S) FilesTestscCs*t|j}|d}|dks&tdS)N utf-8.filesHello, UTF-8 world! ) resourcesfilesdatajoinpath read_bytesAssertionErrorselfr actualrU/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/test_files.pytest_read_bytes s zFilesTests.test_read_bytescCs*t|j}|d}|dks&tdS)NrzHello, UTF-8 world! )rr r r read_textr rrrrtest_read_texts zFilesTests.test_read_textruntime_checkablez4Only suitable when typing supports runtime_checkablecCstt|jtstdSN) isinstancerr r rr rrrrtest_traversableszFilesTests.test_traversableN) __name__ __module__ __qualname__rrunittestZ skipUnlesshasattrtypingrrrrrr src@seZdZddZdS) OpenDiskTestscCs t|_dSr)rr rrrrsetUpszOpenDiskTests.setUpN)rrrr"rrrrr!sr!c@s eZdZdS) OpenZipTestsN)rrrrrrrr#"sr#__main__)r rZimportlib_resourcesrZimportlib_resources.abcrrrrZTestCaser!ZZipSetupr#rmainrrrrs   PK!| *tests/__pycache__/test_open.cpython-38.pycnu[U af@sddlZddlZddlmZddlmZddlmZGdddejej Z Gd d d ejej Z Gd d d Z Gd dde ej Z Gddde ejej ZedkredS)N)data01)util)FileNotFoundErrorc@seZdZddZdS)CommonBinaryTestsc Cst||W5QRXdSN) resources open_binaryselfpackagepathrT/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/test_open.pyexecute szCommonBinaryTests.executeN__name__ __module__ __qualname__rrrrrr src@seZdZddZdS)CommonTextTestsc Cst||W5QRXdSr)r open_textr rrrrszCommonTextTests.executeNrrrrrrsrc@s<eZdZddZddZddZddZd d Zd d Zd S) OpenTestsc Cs2t|jd}|}||dW5QRXdS)N utf-8.filesHello, UTF-8 world! )r r dataread assertEqualr fpresultrrrtest_open_binaryszOpenTests.test_open_binaryc Cs2t|jd}|}||dW5QRXdS)NrzHello, UTF-8 world! r rrrrrrrrtest_open_text_default_encodingsz)OpenTests.test_open_text_default_encodingc Cs6t|jddd}|}W5QRX||ddS)N utf-16.filezutf-16strictzHello, UTF-16 world! r!rrrrtest_open_text_given_encoding sz'OpenTests.test_open_text_given_encodingc Csbt|jddd}|t|jW5QRXt|jddd}|}W5QRX||ddS)Nr#zutf-8r$ignorez*Hello, UTF-16 world! )r rr assertRaises UnicodeErrorrrrrrrtest_open_text_with_errors&s(z$OpenTests.test_open_text_with_errorscCs|ttj|jddSNzdoes-not-exist)r'rr r rr rrr"test_open_binary_FileNotFoundError4s z,OpenTests.test_open_binary_FileNotFoundErrorcCs|ttj|jddSr*)r'rr rrr+rrr test_open_text_FileNotFoundError9s z*OpenTests.test_open_text_FileNotFoundErrorN) rrrr r"r%r)r,r-rrrrrs rc@seZdZddZdS) OpenDiskTestscCs t|_dSr)rrr+rrrsetUp@szOpenDiskTests.setUpN)rrrr/rrrrr.?sr.c@s eZdZdS) OpenZipTestsN)rrrrrrrr0Dsr0__main__)unittestZimportlib_resourcesr rrZ_compatrZ CommonTestsZTestCaserrrr.ZZipSetupr0rmainrrrrs   *PK!QoA*tests/__pycache__/test_path.cpython-38.pycnu[U af@sddlZddlZddlmZddlmZGdddejejZGdddZGd d d eejZ Gd d d eej ejZ e d kre dS)N)data01)utilc@seZdZddZdS) CommonTestsc Cst||W5QRXdS)N) resourcespath)selfpackagerr T/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/test_path.pyexecute szCommonTests.executeN)__name__ __module__ __qualname__r r r r r rsrc@seZdZddZdS) PathTestsc Csdt|jdL}||jdt||jddd}|}W5QRX| d|W5QRXdS)N utf-8.filerzutf-8)encodingzHello, UTF-8 world! ) rrdata assertTruenameendswithrepropenread assertEqual)rrfiletextr r r test_readings zPathTests.test_readingN)r rrrr r r r rsrc@seZdZeZdS) PathDiskTestsN)r rrrrr r r r rsrc@seZdZddZdS) PathZipTestsc Cs&t|jd}|W5QRXdS)Nr)rrrunlink)rrr r r test_remove_in_context_manager"sz+PathZipTests.test_remove_in_context_managerN)r rrr"r r r r r !sr __main__)unittestZimportlib_resourcesrrrrZTestCaserrZZipSetupr r mainr r r r s  PK!4 *tests/__pycache__/test_read.cpython-38.pycnu[U af@sddlZddlZddlmZddlmZddlmZGdddejej Z Gdd d ejej Z Gd d d Z Gd d d e ej Z Gddde ejej ZedkredS)N)data01)util) import_modulec@seZdZddZdS)CommonBinaryTestscCst||dSN) resources read_binaryselfpackagepathrT/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/test_read.pyexecute szCommonBinaryTests.executeN__name__ __module__ __qualname__rrrrrr src@seZdZddZdS)CommonTextTestscCst||dSr)r read_textr rrrrszCommonTextTests.executeNrrrrrrsrc@s,eZdZddZddZddZddZd S) ReadTestscCst|jd}||ddS)N binary.file)rr data assertEqualr resultrrrtest_read_binaryszReadTests.test_read_binarycCst|jd}||ddS)Nz utf-8.filezHello, UTF-8 world! rrrrrrrrtest_read_text_default_encodingsz)ReadTests.test_read_text_default_encodingcCs"tj|jddd}||ddS)N utf-16.filezutf-16)encodingzHello, UTF-16 world! rrrrrtest_read_text_given_encodings z'ReadTests.test_read_text_given_encodingcCs6|ttj|jdtj|jddd}||ddS)Nr!ignore)errorsz*Hello, UTF-16 world! ) assertRaises UnicodeErrorrrrrrrrrtest_read_text_with_errors!sz$ReadTests.test_read_text_with_errorsN)rrrrr r#r(rrrrrsrc@seZdZeZdS) ReadDiskTestsN)rrrrrrrrrr)-sr)c@seZdZddZddZdS) ReadZipTestscCs$td}t|d}||ddSNzziptestdata.subdirectoryrr)rrr r)r submodulerrrrtest_read_submodule_resource2s z)ReadZipTests.test_read_submodule_resourcecCstdd}||ddSr+)rr rrrrr$test_read_submodule_resource_by_name8s z1ReadZipTests.test_read_submodule_resource_by_nameN)rrrr-r.rrrrr*1sr*__main__)unittestZimportlib_resourcesrrr importlibrZ CommonTestsZTestCaserrrr)ZZipSetupr*rmainrrrrs    PK!j.tests/__pycache__/test_resource.cpython-38.pycnu[U afC@s"ddlZddlZddlZddlmZddlmZmZddlmZddl m Z GdddZ Gd d d e ej Z Gd d d e ejej Zeejd kdGdddej ZGdddej ZGdddejej ZGdddejej Zeejd kdGdddej ZedkredS)N)data01) zipdata01 zipdata02)util) import_modulec@s,eZdZddZddZddZddZd S) ResourceTestscCs|t|jddS)N binary.file) assertTrue resources is_resourcedataselfrX/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/test_resource.pytest_is_resource_good_pathsz(ResourceTests.test_is_resource_good_pathcCs|t|jddS)Nz not-a-file assertFalser r r rrrrtest_is_resource_missingsz&ResourceTests.test_is_resource_missingcCs|t|jddS)N subdirectoryrrrrr&test_is_resource_subresource_directorysz4ResourceTests.test_is_resource_subresource_directorycCsHtt|j}|d|d|d||dddddhdS) N __pycache__z __init__.pycz __init__.pyo __init__.pyrz utf-8.filer z utf-16.file)setr contentsr discard assertEqualrrrrr test_contentss   zResourceTests.test_contentsN)__name__ __module__ __qualname__rrrrrrrrr src@seZdZddZdS)ResourceDiskTestscCs t|_dS)N)rr rrrrsetUp,szResourceDiskTests.setUpN)r r!r"r$rrrrr#+sr#c@s eZdZdS)ResourceZipTestsN)r r!r"rrrrr%0sr%zNo ResourceReader in Python 2c@s,eZdZddZddZddZddZd S) ResourceLoaderTestscCs8tjttjdddgd}|tt|dddhdS)NABCfilepathr)rcreate_packager__file__rrr rrpackagerrrtest_resource_contents6s z*ResourceLoaderTests.test_resource_contentscCs2tjttjdddddgd}|t|ddS)Nr)r*r+D/ED/Fr,)rr/rr0r r r r1rrrtest_resource_is_resource=s  z-ResourceLoaderTests.test_resource_is_resourcecCs2tjttjdddddgd}|t|ddS)Nr)r*r+r4r5r,Drr/rr0rr r r1rrr'test_resource_directory_is_not_resourceCs  z;ResourceLoaderTests.test_resource_directory_is_not_resourcecCs2tjttjdddddgd}|t|ddS)Nr)r*r+r4r5r,Zr8r1rrr%test_resource_missing_is_not_resourceIs  z9ResourceLoaderTests.test_resource_missing_is_not_resourceN)r r!r"r3r6r9r;rrrrr(4sr(c@seZdZddZdS)ResourceCornerCaseTestscCsZtjttjdddgd}t|_d|_tjdkrD|j|j_ |j|j_ | t |ddS)Nr)r*r+r,z/path/which/shall/not/be/namedr&)rr/rr0object __loader__sys version_info__spec__loaderoriginrr r )rmodulerrr#test_package_has_no_reader_fallbackQs   z;ResourceCornerCaseTests.test_package_has_no_reader_fallbackN)r r!r"rErrrrr<Psr<c@s0eZdZeZddZddZddZddZd S) ResourceFromZipsTest01cCstd}|t|ddSNziptestdata.subdirectoryr )rr r r r submodulerrrtest_is_submodule_resourcees z1ResourceFromZipsTest01.test_is_submodule_resourcecCs|tdddSrG)r r r rrrr$test_read_submodule_resource_by_namejs z;ResourceFromZipsTest01.test_read_submodule_resource_by_namecCs&td}|tt|ddhdSNrHrr )rrrr rrIrrrtest_submodule_contentsns  z.ResourceFromZipsTest01.test_submodule_contentscCs|ttdddhdSrMrrr rrrrrtest_submodule_contents_by_namets z6ResourceFromZipsTest01.test_submodule_contents_by_nameN) r r!r"r ZIP_MODULErKrLrNrPrrrrrFbs rFc@seZdZeZddZdS)ResourceFromZipsTest02cCs8|ttdddh|ttdddhdS)Nzziptestdata.oner resource1.txtzziptestdata.twoz resource2.txtrOrrrrtest_unrelated_contents}s  z.ResourceFromZipsTest02.test_unrelated_contentsN)r r!r"rrQrTrrrrrRzsrRz!No namespace packages in Python 2c@seZdZddZdS) NamespaceTestcCsvtd}|t||tdd|ttjdd|ttjdd|ttj dd|ttj dddS)Nz*importlib_resources.tests.data03.namespacerS) r rrlistr assertRaisesFileNotFoundError open_text open_binary read_text read_binaryrrrr%test_namespaces_cannot_have_resourcess@z3NamespaceTest.test_namespaces_cannot_have_resourcesN)r r!r"r]rrrrrUsrU__main__)r?unittestZimportlib_resourcesr rrrr importlibrrZTestCaser#ZZipSetupr%ZskipIfr@r(r<Z ZipSetupBaserFrRrUr mainrrrrs$     PK!+)>>%tests/__pycache__/util.cpython-38.pycnu[U afD@s ddlZddlZddlZddlZddlZddlZddlmZddlmZddl m Z m Z m Z m Z ddlmZzddlmZmZWn$ek rd d Zd d ZYnXzdd lmZWnek rdZYnXdddZGddde ZGdddZGdddeZdS)N)data01) zipdata01)ABCPathPurePathFileNotFoundError)ResourceReader) modules_setupmodules_cleanupcCs tjfSN)sysmodulescopyrrO/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/tests/util.pyr sr cCs:ddtjD}tjtj|tj|dS)NcSs"g|]\}}|dr||fqS)z encodings.) startswith).0kvrrr s z#modules_cleanup..)rritemsclearupdate)Z oldmodules encodingsrrrr s  r ) ModuleSpecTrc slGfdddt}d}t|}tdkrF||_d|_|rhg|_n"|}t||d|d}||_||_|S)NcsHeZdZddZfddZfddZfddZfd d Zd S) zcreate_package..ReadercSs|Sr rselfpackagerrrget_resource_reader.sz2create_package..Reader.get_resource_readercs||_ttrnSdSr _path isinstance Exceptionrpath)filerr open_resource1s z,create_package..Reader.open_resourcecs||_ttrnSdSr r!)rpath_)r&rr resource_path8s z,create_package..Reader.resource_pathcsJ||_ttrD],}|d}t|dkr|d|krdSqdS)N/rrTF)r"r#r$splitlen)rr)entrypartscontentsr&rr is_resource?s  z*create_package..Reader.is_resourcec3s"ttrD] }|VqdSr )r#r$)rr.r0rrr1Is z'create_package..Reader.contentsN)__name__ __module__ __qualname__r r(r*r2r1rr1r'r&rrReader-s    r7Ztestingpackagezdoes-not-exist)origin is_package) r types ModuleTyperr3__file____path____spec__ __loader__) r'r&r9r1r7namemoduleloaderspecrr6rcreate_package,s$# rDc@seZdZejddZddZddZddZe e j d kd d d Z d dZddZddZddZddZe e j dkdddZe e j dkdddZddZdS) CommonTestscCstdSr )NotImplementedError)rrr&rrrexecutehszCommonTests.executecCs|tjddSN utf-8.file)rGrr3rrrrtest_package_namelszCommonTests.test_package_namecCs|tddSrHrGrrJrrrtest_package_objectpszCommonTests.test_package_objectcCsd}|t|dSrHrLr%rrrtest_string_pathtszCommonTests.test_string_path)zrequires os.PathLike supportcCstd}|t|dSrH)rrGrr%rrrtest_pathlib_pathyszCommonTests.test_pathlib_pathc Cs8tt}|jd}|t|t|W5QRXdSrH)rr<parent assertRaises ValueErrorrGr)rr& full_pathrrrtest_absolute_paths  zCommonTests.test_absolute_pathc Cs&|t|tdW5QRXdS)Nz../data01/utf-8.file)rSrTrGrrJrrrtest_relative_paths zCommonTests.test_relative_pathcCstjtj=|tjddSrH)rrrr3rGrJrrr$test_importing_module_as_side_effects z0CommonTests.test_importing_module_as_side_effectc Cs&|t|tdW5QRXdSrH)rS TypeErrorrGr3rJrrrtest_non_package_by_names z$CommonTests.test_non_package_by_namec Cs0|ttjd}||dW5QRXdS)Nzimportlib_resources.tests.utilrI)rSrYrrrG)rrArrrtest_non_package_by_packages  z'CommonTests.test_non_package_by_package)rOzNo ResourceReader in Python 2cCs8td}t|td}||d||jjddSNs Hello, world!r'r&rI)ioBytesIOrDr rG assertEqualr?r")r bytes_datarrrrtest_resource_openers  z CommonTests.test_resource_openercCs:td}t}t||d}||d||jjddSr\)r^r_r<rDrGr`r?r")rrar&rrrrtest_resource_paths    zCommonTests.test_resource_pathc Cs6tttd}|t||dW5QRXdS)Nr]rI)rDr rSrGrrrrtest_useless_loaders  zCommonTests.test_useless_loaderN)r3r4r5abcabstractmethodrGrKrMrNunittestZskipIfr version_inforQrVrWrXrZr[rbrcrdrrrrrEfs"    rEc@s0eZdZdZeddZeddZddZdS) ZipSetupBaseNcCs>t|jj}|j}t|d|_tj|jt d|_ dS)Nzziptestdata.zipZ ziptestdata) r ZIP_MODULEr<rRstr _zip_pathrr&append importlib import_moduledata)clsZ data_pathdata_dirrrr setUpClasss  zZipSetupBase.setUpClasscCs~ztj|jWntk r&YnXztj|j=tj|jj=Wnt k rVYnXz |`|`Wnt k rxYnXdSr ) rr&removerlrTpath_importer_cacherrpr3KeyErrorAttributeError)rqrrr tearDownClasss zZipSetupBase.tearDownClasscCst}|jtf|dSr )r Z addCleanupr )rrrrrsetUpszZipSetupBase.setUp)r3r4r5rj classmethodrsrxryrrrrris   ric@seZdZeZdS)ZipSetupN)r3r4r5rrjrrrrr{sr{)Tr)rernr^rr:rgrrZ_compatrrrr r Z test.supportr r ImportErrorZimportlib.machineryrrDrErir{rrrrs,     :K#PK!)I#__pycache__/__init__.cpython-38.pycnu[U af @sdZddlZddlmZddlmZedddd d d d d dddddg Zejdkrddl m Z m Z m Z m Z mZmZmZmZmZmZddlmZn2ddlm Z m Z mZmZmZmZmZmZedd=edZdS)z*Read resources contained within a package.N)metadata)as_filezimportlib_resources.treesPackageResourceResourceReaderrcontentsfiles is_resource open_binary open_textpath read_binary read_text)) rrrr r r r r rr)r)rr r r r r rrrZimportlib_resources)__doc__sysZ_compatrZ_commonr __import____all__ version_infoZimportlib_resources._py3rrrr r r r r rrZimportlib_resources.abcrZimportlib_resources._py2version __version__rrM/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/__init__.pys.   0 ( PK!oy99"__pycache__/_common.cpython-38.pycnu[U afI@sddlmZddlZddlZddlZddlmZmZmZm Z m Z m Z ddZ ddZ d d Zejdd d Ze ejddZeeejddZdS))absolute_importN)Path package_specFileNotFoundErrorZipPathsingledispatchsuppresscCst|}t|pt|S)z= Return a Traversable object for the given package. )rfrom_traversable_resourcesfallback_resources)packagespecrL/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/_common.py from_package src Cs*tt|jW5QRSQRXdS)z| If the spec.loader implements TraversableResources, directly or implicitly, it will have a ``files()`` method. N)r AttributeErrorloaderfiles)r rrrr s r cCsLt|jj}z&|jj}||}t|t|dWStk rFYnX|S)N/) roriginparentrarchive relative_torstr Exception)r package_directory archive_pathrel_pathrrrr s  r ccsbtj|d\}}z&t||t|t|VW5zt|Wntk rZYnXXdS)Nsuffix)tempfilemkstemposremoverwritecloser)readerr fdraw_pathrrr _tempfile*s r*c cs&t|j|jd }|VW5QRXdS)zu Given a Traversable object, return that object as a path on the local file system in a context manager. rN)r* read_bytesname)pathlocalrrras_file;sr/ccs |VdS)z7 Degenerate behavior for pathlib.Path objects. Nr)r-rrr_Fsr0)r) __future__rr#r! contextlibZ_compatrrrrrr rr r contextmanagerr*r/registerr0rrrrs       PK! ֓,,"__pycache__/_compat.cpython-38.pycnu[U af@sddlmZzddlmZmZWn$ek rDddlmZmZYnXzddlmZWn ek rvddl mZYnXzddl m Z Wn ek rddl m Z YnXzddl m Z Wn0ek rddl mZGdddeZ YnXzeZWnek reZYnXzdd lmZWnek r>dd lZYnXzdd lmZWn"ek rrdd lmZYnXzdd lmZWnek rd dZYnXzddlmZWnek re ZYnXGdddeZddZd S))absolute_import)PathPurePath)suppress)singledispatch)ABC)ABCMetac@seZdZeZdS)rN)__name__ __module__ __qualname__r __metaclass__r r L/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/_compat.pyrsr)metadataN)r)runtime_checkablecCs|SNr )clsr r rr5sr)Protocolc@seZdZddZdS) PackageSpeccKst||dSr)varsupdate)selfkwargsr r r__init__@szPackageSpec.__init__N)r r r rr r r rr?srcCs"t|ddp t|jt|dddS)N__spec__ __loader__)originloader)getattrr__file__)packager r r package_specDs   r!) __future__rpathlibrr ImportErrorZpathlib2 contextlibrZ contextlib2 functoolsrabcrrobjectFileNotFoundError NameErrorOSError importlibrZimportlib_metadatazipfileZZipPathZzipptypingrrrr!r r r rsN    PK!%%__pycache__/_py2.cpython-38.pycnu[U af@sddlZddlZddlmZddlmZddlmZddlm Z m Z m Z ddZ d d Zd d Zd dZdddZddZd ddZddZddZddZddZdS)!N)_common)FileNotFoundError) import_module)BytesIO TextIOWrapperopencCst|ts|St|S)z)If name is a string, resolve to a module.) isinstance basestringrnamer I/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/_py2.py_resolve s rcCs$t|}t|ds td||S)Normalize a path by ensuring it is a string. If the resulting string contains path separators, an exception is raised. __path__z{!r} is not a package)rhasattr TypeErrorformat)packagemoduler r r _get_packages rcCs.t|}tj|\}}|r*td||S)rz{!r} must be only a file name)strospathsplit ValueErrorr)rZstr_pathparent file_namer r r_normalize_paths rc Cst|}t|}tj|j}tj||}tj|}z t|dWSt k rz*|j }|t |j dd}| |}Wn2t tfk r|j}d||}t|YnXt|YSXdS)zDReturn a file-like object opened for binary reading of the resource.rbrNz{!r} resource not found in {!r})rrrrdirname__file__joinabspathio_openIOError __loader__lenarchiveget_dataAttributeError__name__rrr) rresource package_path relative_path full_pathloaderdata package_namemessager r r open_binary(s(  r5utf-8strictcCstt||||dS)zBReturn a file-like object opened for text reading of the resource.)encodingerrors)rr5)rr-r8r9r r r open_textFs r:c Cs*t||}|W5QRSQRXdS)z+Return the binary contents of the resource.N)r5read)rr-fpr r r read_binaryLs r=c Cs.t||||}|W5QRSQRXdS)zReturn the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode(). N)r:r;)rr-r8r9r<r r r read_textRsr>cCstt|SN)r from_packagerrr r rfiles\srBcCs,t|t|}|s"t|t|S)akA context manager providing a file path object to the resource. If the resource does not already exist on its own on the file system, a temporary file will be created. If the file was created, the file will be deleted upon exiting the context manager (no exception is raised if the file was deleted prior to the context manager exiting). )rBjoinpathris_filerrZas_file)rr-rr r rr`s rc Cs|t|}t|ztt|}Wn<tk r\}z|jtjtjfkrFWYdSd}~XYnX||krjdSt || S)zUTrue if name is a resource inside package. Directories are *not* resources. FN) rrsetcontentsOSErrorerrnoENOENTENOTDIRrr@rD)rr package_contentserrorr r r is_resourceosrMcCs$t|}tddt|DS)zReturn an iterable of entries in `package`. Note that not all entries are resources. Specifically, directories are not considered resources. Use `is_resource()` on each entry returned here to check if it is a resource or not. css|] }|jVqdSr?r ).0itemr r r szcontents..)rlistrr@iterdirrAr r rrFsrF)r6r7)r6r7)rrHrZ_compatr importlibriorrrr%rrrr5r:r=r>rBrrMrFr r r rs        PK!HW00__pycache__/_py3.cpython-38.pycnu[U af @sddlZddlZddlmZddlmZddlmZmZddl m Z ddl m Z ddl mZmZdd lmZdd lmZdd lmZmZmZmZmZdd lmZdd lmZmZeeefZ ej!dkreeej"fZ#neZ#edddZ$edddZ%edddZ&eeej'dddZ(e e#edddZ)d1e e#eeeddd Z*e e#e+dd!d"Z,d2e e#eeedd#d$Z-e ej.dd%d&Z/e e#d'dd(d)Z0ed*d+Z1e ee2d,d-d.Z3e eedd/d0Z4dS)3N)abc)_common)contextmanagersuppress) import_module)ResourceLoader)BytesIO TextIOWrapper)Path) ModuleType)IterableIteratorOptionalSetUnion)cast)BinaryIOTextIO))returncCst|dr|St|S)z)If name is a string, resolve to a module.__spec__)hasattrrnamerI/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/_py3.py_resolves rcCs&t|}|jjdkr"td||S)zTake a package name or module object and return the module. If a name, the module is imported. If the resolved module object is not a package, raise an exception. Nz{!r} is not a package)rrsubmodule_search_locations TypeErrorformat)packagemodulerrr _get_package!s r$cCs.t|}tj|\}}|r*td||S)zNormalize a path by ensuring it is a string. If the resulting string contains path separators, an exception is raised. z{!r} must be only a file name)strospathsplit ValueErrorr!)r'Zstr_pathparent file_namerrr_normalize_path-s r,)r"rcCs2|j}t|jdd}|dkr dSttj||jS)Nget_resource_reader)rgetattrloaderr resources_abcResourceReaderr)r"specreaderrrr_get_resource_reader9s r4)r"resourcerc Cst|}t|}t|}|dk r*||Stj|jjp:d}tj |}tj ||}zt |ddWSt k rt t|jj}d}t|jjdrtt ||}W5QRX|dkr|jj}d||} t| t|YSXdS)zDReturn a file-like object opened for binary reading of the resource.Nznon-existent filerb)modeget_dataz{!r} resource not found in {!r})r,r$r4 open_resourcer&r'abspathrorigindirnamejoinopenOSErrorrrr/rrr8rr!FileNotFoundErrorr ) r"r5r3absolute_package_path package_path full_pathr/data package_namemessagerrr open_binaryGs4    rGutf-8strict)r"r5encodingerrorsrcCstt||||dS)zBReturn a file-like object opened for text reading of the resource.)rJrK)r rG)r"r5rJrKrrr open_textgs rLc Cs*t||}|W5QRSQRXdS)z+Return the binary contents of the resource.N)rGread)r"r5fprrr read_binaryps rOc Cs.t||||}|W5QRSQRXdS)zReturn the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode(). N)rLrM)r"r5rJrKrNrrr read_textvs rPcCstt|S)z3 Get a Traversable resource from a package )r from_packager$)r"rrrfilessrRzContextManager[Path]cCs2tt|}|rt||Stt|t|S)akA context manager providing a file path object to the resource. If the resource does not already exist on its own on the file system, a temporary file will be created. If the file was created, the file will be deleted upon exiting the context manager (no exception is raised if the file was deleted prior to the context manager exiting). )r4r$_path_from_readerrZas_filerRjoinpathr,)r"r5r3rrrr's  r'c csft|}tt t||VW5QRdSQRX||}tj|j|d }|VW5QRXdS)N)suffix) r,rr@r resource_pathr9rZ _tempfilerM)r3r5Z norm_resourceZ opener_readerresrrrrSs  rS)r"rrcCsTt|}t|t|}|dk r*||Stt|}||krBdSt||S)zYTrue if `name` is a resource inside `package`. Directories are *not* resources. NF) r$r,r4 is_resourcesetcontentsrrQis_file)r"rr3package_contentsrrrrXs  rXcCsdt|}t|}|dk r |S|jjdkp6|jjdk}|sD|jjsHdStddt| DS)zReturn an iterable of entries in `package`. Note that not all entries are resources. Specifically, directories are not considered resources. Use `is_resource()` on each entry returned here to check if it is a resource or not. N namespacercss|] }|jVqdS)Nr).0itemrrr szcontents..) r$r4rZrr; has_locationlistrrQiterdir)r"r3r]rrrrZs   rZ)rHrI)rHrI)5r&sysrr0r contextlibrr importlibr importlib.abcrior r pathlibr typesr typingr rrrrrZ typing.iorrContextManagerr%Package version_infoPathLikeResourcerr$r,r1r4rGrLbytesrOrPZ TraversablerRr'rSboolrXrZrrrrsb            "    PK!hy__pycache__/abc.cpython-38.pycnu[U af5@sddlmZddlZddlmZmZmZmZzddlm Z m Z m Z Wne k rXYnXGdddeZ eGdd d eZGd d d e ZdS) )absolute_importN)ABCFileNotFoundErrorruntime_checkableProtocol)BinaryIOIterableTextc@sHeZdZdZejddZejddZejddZejdd Z d S) ResourceReaderzDAbstract base class for loaders to provide resource reading support.cCstdS)zReturn an opened, file-like object for binary reading. The 'resource' argument is expected to represent only a file name. If the resource cannot be found, FileNotFoundError is raised. NrselfresourcerH/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/abc.py open_resources zResourceReader.open_resourcecCstdS)zReturn the file system path to the specified resource. The 'resource' argument is expected to represent only a file name. If the resource does not exist on the file system, raise FileNotFoundError. Nr r rrr resource_paths zResourceReader.resource_pathcCstdS)zjReturn True if the named 'path' is a resource. Files are resources, directories are not. Nr rpathrrr is_resource,szResourceReader.is_resourcecCstdS)z+Return an iterable of entries in `package`.Nr rrrrcontents5szResourceReader.contentsN) __name__ __module__ __qualname____doc__abcabstractmethodrrrrrrrrr s   r c@seZdZdZejddZejddZejdddZejd d Z ejd d Z ejd dZ ejddZ ejdddZ ejddZdS) Traversablezt An object with a subset of pathlib.Path methods suitable for traversing directories and opening files. cCsdS)z3 Yield Traversable objects in self NrrrrriterdirCszTraversable.iterdircCsdSz0 Read contents of self as bytes Nrrrrr read_bytesIszTraversable.read_bytesNcCsdSr!r)rencodingrrr read_textOszTraversable.read_textcCsdS)z. Return True if self is a dir Nrrrrris_dirUszTraversable.is_dircCsdS)z/ Return True if self is a file Nrrrrris_file[szTraversable.is_filecCsdSz2 Return Traversable child in self NrrchildrrrjoinpathaszTraversable.joinpathcCsdSr'rr(rrr __truediv__gszTraversable.__truediv__rcOsdS)z mode may be 'r' or 'rb' to open as text or binary. Return a handle suitable for reading (same as pathlib.Path.open). When opening as text, accepts encoding parameters such as those accepted by io.TextIOWrapper. Nr)rmodeargskwargsrrropenmszTraversable.opencCsdS)zM The base name of this object without any parent references. NrrrrrnamewszTraversable.name)N)r,)rrrrrrr r"r$r%r&r*r+r0abstractpropertyr1rrrrr<s&        rc@s:eZdZejddZddZddZddZd d Z d S) TraversableResourcescCsdS)z3Return a Traversable object for the loaded package.NrrrrrfilesszTraversableResources.filescCs||dS)Nrb)r4r*r0r rrrrsz"TraversableResources.open_resourcecCs t|dSNr r rrrrsz"TraversableResources.resource_pathcCs||Sr6)r4r*isfilerrrrrsz TraversableResources.is_resourcecCsdd|DS)Ncss|] }|jVqdSr6)r1).0itemrrr sz0TraversableResources.contents..)r4r rrrrrszTraversableResources.contentsN) rrrrrr4rrrrrrrrr3s  r3) __future__rrZ_compatrrrrtypingrr r ImportErrorr rr3rrrrs .BPK!D __pycache__/trees.cpython-38.pycnu[U afu@sddlmZdgZdS))as_filerN)Z_commonr__all__rrJ/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/importlib_resources/trees.pys PK!U __init__.pynu[PK!t`0II 3_common.pynu[PK! 1  _compat.pynu[PK!~d%j_py2.pynu[PK!Z^  &_py3.pynu[PK!I-55Babc.pynu[PK!"uuDRtrees.pynu[PK!Rtests/__init__.pynu[PK!;2Stests/test_files.pynu[PK!=nWtests/test_open.pynu[PK!9`tests/test_path.pynu[PK!letests/test_read.pynu[PK!CCntests/test_resource.pynu[PK!1lmDD tests/util.pynu[PK!tests/data01/__init__.pynu[PK!Xtests/data01/binary.filenu[PK!"<,,tests/data01/utf-16.filenu[PK!štests/data01/utf-8.filenu[PK!%stests/data01/subdirectory/__init__.pynu[PK!%Ȥtests/data01/subdirectory/binary.filenu[PK!`?K=!tests/data01/subdirectory/__pycache__/__init__.cpython-38.pycnu[PK!/0Ptests/data01/__pycache__/__init__.cpython-38.pycnu[PK!etests/data02/__init__.pynu[PK!tests/data02/one/__init__.pynu[PK! tests/data02/one/resource1.txtnu[PK!nھ4Ttests/data02/one/__pycache__/__init__.cpython-38.pycnu[PK!qtests/data02/two/__init__.pynu[PK!]o, tests/data02/two/resource2.txtnu[PK!FQ4tests/data02/two/__pycache__/__init__.cpython-38.pycnu[PK!F0$05tests/data02/__pycache__/__init__.cpython-38.pycnu[PK!Jtests/data03/__init__.pynu[PK!$tests/data03/namespace/resource1.txtnu[PK!յ0tests/data03/__pycache__/__init__.cpython-38.pycnu[PK!tests/zipdata01/__init__.pynu[PK!}AllFtests/zipdata01/ziptestdata.zipnu[PK!vjո3tests/zipdata01/__pycache__/__init__.cpython-38.pycnu[PK!tests/zipdata02/__init__.pynu[PK!a K@gtests/zipdata02/ziptestdata.zipnu[PK!v~u3ptests/zipdata02/__pycache__/__init__.cpython-38.pycnu[PK!k)tests/__pycache__/__init__.cpython-38.pycnu[PK!==+tests/__pycache__/test_files.cpython-38.pycnu[PK!| **tests/__pycache__/test_open.cpython-38.pycnu[PK!QoA*ftests/__pycache__/test_path.cpython-38.pycnu[PK!4 *tests/__pycache__/test_read.cpython-38.pycnu[PK!j.tests/__pycache__/test_resource.cpython-38.pycnu[PK!+)>>%tests/__pycache__/util.cpython-38.pycnu[PK!)I#__pycache__/__init__.cpython-38.pycnu[PK!oy99"__pycache__/_common.cpython-38.pycnu[PK! ֓,,"}#__pycache__/_compat.cpython-38.pycnu[PK!%%*__pycache__/_py2.cpython-38.pycnu[PK!HW00o<__pycache__/_py3.cpython-38.pycnu[PK!hyT__pycache__/abc.cpython-38.pycnu[PK!D 6i__pycache__/trees.cpython-38.pycnu[PK55hj