summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStéphane Bidoul <stephane.bidoul@gmail.com>2023-03-25 14:17:48 +0100
committerStéphane Bidoul <stephane.bidoul@gmail.com>2023-04-14 08:03:48 +0200
commit8e2205d8495474df088d773b4658aa4a40aefcac (patch)
tree5c0128b6d19f8759b126ef9be29f7fddea11f1b0
parentf7787f8798712e475ebbf71f5487f92158f043a9 (diff)
downloadpip-8e2205d8495474df088d773b4658aa4a40aefcac.tar.gz
Add function to check hashes against known digests
-rw-r--r--src/pip/_internal/utils/hashes.py7
-rw-r--r--tests/unit/test_utils.py8
2 files changed, 15 insertions, 0 deletions
diff --git a/src/pip/_internal/utils/hashes.py b/src/pip/_internal/utils/hashes.py
index 76727306a..843cffc6b 100644
--- a/src/pip/_internal/utils/hashes.py
+++ b/src/pip/_internal/utils/hashes.py
@@ -105,6 +105,13 @@ class Hashes:
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)
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
index a67a7c110..450081cfd 100644
--- a/tests/unit/test_utils.py
+++ b/tests/unit/test_utils.py
@@ -425,6 +425,14 @@ class TestHashes:
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"""