Skip to content

Commit b1b885e

Browse files
committed
Add function to check hashes against known digests
1 parent 8271fdb commit b1b885e

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/pip/_internal/utils/hashes.py

+7
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

+8
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,14 @@ def test_hash(self) -> None:
426426
cache[Hashes({"sha256": ["ab", "cd"]})] = 42
427427
assert cache[Hashes({"sha256": ["ab", "cd"]})] == 42
428428

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

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

0 commit comments

Comments
 (0)