Skip to content

Commit 8e2205d

Browse files
committed
Add function to check hashes against known digests
1 parent f7787f8 commit 8e2205d

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/pip/_internal/utils/hashes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ def check_against_path(self, path: str) -> None:
105105
with open(path, "rb") as file:
106106
return self.check_against_file(file)
107107

108+
def has_one_of(self, hashes: Dict[str, str]) -> bool:
109+
"""Return whether any of the given hashes are allowed."""
110+
for hash_name, hex_digest in hashes.items():
111+
if self.is_hash_allowed(hash_name, hex_digest):
112+
return True
113+
return False
114+
108115
def __bool__(self) -> bool:
109116
"""Return whether I know any known-good hashes."""
110117
return bool(self._allowed)

tests/unit/test_utils.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,14 @@ def test_hash(self) -> None:
425425
cache[Hashes({"sha256": ["ab", "cd"]})] = 42
426426
assert cache[Hashes({"sha256": ["ab", "cd"]})] == 42
427427

428+
def test_has_one_of(self) -> None:
429+
hashes = Hashes({"sha256": ["abcd", "efgh"], "sha384": ["ijkl"]})
430+
assert hashes.has_one_of({"sha256": "abcd"})
431+
assert hashes.has_one_of({"sha256": "efgh"})
432+
assert not hashes.has_one_of({"sha256": "xyzt"})
433+
empty_hashes = Hashes()
434+
assert not empty_hashes.has_one_of({"sha256": "xyzt"})
435+
428436

429437
class TestEncoding:
430438
"""Tests for pip._internal.utils.encoding"""

0 commit comments

Comments
 (0)