|
| 1 | +import sys |
| 2 | +import pathlib |
| 3 | +import unittest |
| 4 | + |
| 5 | +from . import fixtures |
| 6 | +from importlib_metadata import ( |
| 7 | + distribution, |
| 8 | + distributions, |
| 9 | + entry_points, |
| 10 | + metadata, |
| 11 | + version, |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +class OldStdlibFinderTests(fixtures.DistInfoPkgOffPath, unittest.TestCase): |
| 16 | + def setUp(self): |
| 17 | + python_version = sys.version_info[:2] |
| 18 | + if python_version < (3, 8) or python_version > (3, 9): |
| 19 | + self.skipTest("Tests specific for Python 3.8/3.9") |
| 20 | + super().setUp() |
| 21 | + |
| 22 | + def _meta_path_finder(self): |
| 23 | + from importlib.metadata import ( |
| 24 | + Distribution, |
| 25 | + DistributionFinder, |
| 26 | + PathDistribution, |
| 27 | + ) |
| 28 | + from importlib.util import spec_from_file_location |
| 29 | + |
| 30 | + path = pathlib.Path(self.site_dir) |
| 31 | + |
| 32 | + class CustomDistribution(Distribution): |
| 33 | + def __init__(self, name, path): |
| 34 | + self.name = name |
| 35 | + self._path_distribution = PathDistribution(path) |
| 36 | + |
| 37 | + def read_text(self, filename): |
| 38 | + return self._path_distribution.read_text(filename) |
| 39 | + |
| 40 | + def locate_file(self, path): |
| 41 | + return self._path_distribution.locate_file(path) |
| 42 | + |
| 43 | + class CustomFinder: |
| 44 | + @classmethod |
| 45 | + def find_spec(cls, fullname, _path=None, _target=None): |
| 46 | + candidate = pathlib.Path(path, *fullname.split(".")).with_suffix(".py") |
| 47 | + if candidate.exists(): |
| 48 | + return spec_from_file_location(fullname, candidate) |
| 49 | + |
| 50 | + @classmethod |
| 51 | + def find_distributions(self, context=DistributionFinder.Context()): |
| 52 | + for dist_info in path.glob("*.dist-info"): |
| 53 | + yield PathDistribution(dist_info) |
| 54 | + name, _, _ = str(dist_info).partition("-") |
| 55 | + yield CustomDistribution(name + "_custom", dist_info) |
| 56 | + |
| 57 | + return CustomFinder |
| 58 | + |
| 59 | + def test_compatibility_with_old_stdlib_path_distribution(self): |
| 60 | + """ |
| 61 | + Given a custom finder that uses Python 3.8/3.9 importlib.metadata is installed, |
| 62 | + when importlib_metadata functions are called, there should be no exceptions. |
| 63 | + Ref python/importlib_metadata#396. |
| 64 | + """ |
| 65 | + self.fixtures.enter_context(fixtures.install_finder(self._meta_path_finder())) |
| 66 | + |
| 67 | + assert list(distributions()) |
| 68 | + assert distribution("distinfo_pkg") |
| 69 | + assert distribution("distinfo_pkg_custom") |
| 70 | + assert version("distinfo_pkg") > "0" |
| 71 | + assert version("distinfo_pkg_custom") > "0" |
| 72 | + assert list(metadata("distinfo_pkg")) |
| 73 | + assert list(metadata("distinfo_pkg_custom")) |
| 74 | + assert list(entry_points(group="entries")) |
0 commit comments