Skip to content

Commit

Permalink
Add function to check hashes against known digests
Browse files Browse the repository at this point in the history
  • Loading branch information
sbidoul committed Mar 25, 2023
1 parent 8271fdb commit b1b885e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/pip/_internal/utils/hashes.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ def check_against_path(self, path: str) -> None:
with open(path, "rb") as file:
return self.check_against_file(file)

def has_one_of(self, hashes: Dict[str, str]) -> bool:
"""Return whether any of the given hashes are allowed."""
for hash_name, hex_digest in hashes.items():
if self.is_hash_allowed(hash_name, hex_digest):
return True
return False

def __bool__(self) -> bool:
"""Return whether I know any known-good hashes."""
return bool(self._allowed)
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,14 @@ def test_hash(self) -> None:
cache[Hashes({"sha256": ["ab", "cd"]})] = 42
assert cache[Hashes({"sha256": ["ab", "cd"]})] == 42

def test_has_one_of(self) -> None:
hashes = Hashes({"sha256": ["abcd", "efgh"], "sha384": ["ijkl"]})
assert hashes.has_one_of({"sha256": "abcd"})
assert hashes.has_one_of({"sha256": "efgh"})
assert not hashes.has_one_of({"sha256": "xyzt"})
empty_hashes = Hashes()
assert not empty_hashes.has_one_of({"sha256": "xyzt"})


class TestEncoding:
"""Tests for pip._internal.utils.encoding"""
Expand Down

0 comments on commit b1b885e

Please sign in to comment.