Skip to content

Commit c571e94

Browse files
committed
Add tests asserting that protocols match stdlib also.
1 parent 95967ae commit c571e94

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

importlib_metadata/_meta.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
Protocol,
88
TypeVar,
99
overload,
10+
runtime_checkable,
1011
)
1112

1213
_T = TypeVar("_T")
1314

1415

16+
@runtime_checkable
1517
class PackageMetadata(Protocol):
1618
def __len__(self) -> int: ... # pragma: no cover
1719

@@ -71,6 +73,7 @@ def read_bytes(self) -> bytes: ... # pragma: no cover
7173
def exists(self) -> bool: ... # pragma: no cover
7274

7375

76+
@runtime_checkable
7477
class IPackagePath(Protocol):
7578
hash: Any | None
7679
size: int | None
@@ -88,6 +91,7 @@ def parts(self) -> tuple[str, ...]: ... # pragma: no cover
8891
def __fspath__(self) -> str: ... # pragma: no cover
8992

9093

94+
@runtime_checkable
9195
class IDistribution(Protocol):
9296
def read_text(
9397
self, filename: str | os.PathLike[str]

tests/test_protocols.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from __future__ import annotations
2+
3+
import importlib.metadata as stdlib
4+
import pathlib
5+
import tempfile
6+
import unittest
7+
8+
from importlib_metadata import IDistribution, IPackagePath, PackageMetadata
9+
10+
11+
class ProtocolTests(unittest.TestCase):
12+
def setUp(self):
13+
self.tmpdir = tempfile.TemporaryDirectory()
14+
self.addCleanup(self.tmpdir.cleanup)
15+
tmp_path = pathlib.Path(self.tmpdir.name)
16+
dist_info = tmp_path / 'protocol_sample-1.0.dist-info'
17+
dist_info.mkdir()
18+
(dist_info / 'METADATA').write_text(
19+
'Name: protocol-sample\nVersion: 1.0\n', encoding='utf-8'
20+
)
21+
self.dist = stdlib.PathDistribution(dist_info)
22+
23+
def test_stdlib_distribution_matches_protocol(self):
24+
assert isinstance(self.dist, IDistribution)
25+
26+
def test_stdlib_metadata_matches_protocol(self):
27+
meta = self.dist.metadata
28+
assert meta is not None
29+
assert isinstance(meta, PackageMetadata)
30+
31+
def test_stdlib_package_path_matches_protocol(self):
32+
package_path = stdlib.PackagePath('protocol_sample/__init__.py')
33+
package_path.hash = None
34+
package_path.size = 0
35+
package_path.dist = self.dist
36+
assert isinstance(package_path, IPackagePath)

0 commit comments

Comments
 (0)