From b1b885ee02ea4c4d5dd6e1f4be3dd0ec7fd3918a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Bidoul?= <stephane.bidoul@gmail.com> Date: Sat, 25 Mar 2023 14:17:48 +0100 Subject: [PATCH] Add function to check hashes against known digests --- src/pip/_internal/utils/hashes.py | 7 +++++++ tests/unit/test_utils.py | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/src/pip/_internal/utils/hashes.py b/src/pip/_internal/utils/hashes.py index 76727306a4c..843cffc6b3d 100644 --- a/src/pip/_internal/utils/hashes.py +++ b/src/pip/_internal/utils/hashes.py @@ -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) diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 1daaecbf490..f5aec5cdd9b 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -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"""