Skip to content

Commit

Permalink
Merge pull request #9078 from xavfernandez/cache_find_best_candidate
Browse files Browse the repository at this point in the history
  • Loading branch information
pradyunsg authored Oct 31, 2020
2 parents a0e34e9 + 5ec275f commit 2e11f31
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/pip/_internal/index/package_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,7 @@ def make_candidate_evaluator(
hashes=hashes,
)

@lru_cache(maxsize=None)
def find_best_candidate(
self,
project_name, # type: str
Expand Down
23 changes: 22 additions & 1 deletion src/pip/_internal/utils/hashes.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ def __init__(self, hashes=None):
:param hashes: A dict of algorithm names pointing to lists of allowed
hex digests
"""
self._allowed = {} if hashes is None else hashes
allowed = {}
if hashes is not None:
for alg, keys in hashes.items():
# Make sure values are always sorted (to ease equality checks)
allowed[alg] = sorted(keys)
self._allowed = allowed

def __and__(self, other):
# type: (Hashes) -> Hashes
Expand Down Expand Up @@ -128,6 +133,22 @@ def __bool__(self):
# type: () -> bool
return self.__nonzero__()

def __eq__(self, other):
# type: (object) -> bool
if not isinstance(other, Hashes):
return NotImplemented
return self._allowed == other._allowed

def __hash__(self):
# type: () -> int
return hash(
",".join(sorted(
":".join((alg, digest))
for alg, digest_list in self._allowed.items()
for digest in digest_list
))
)


class MissingHashes(Hashes):
"""A workalike for Hashes used when we're missing a hash for a requirement
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,16 @@ def test_non_zero(self):
assert not Hashes()
assert not Hashes({})

def test_equality(self):
assert Hashes() == Hashes()
assert Hashes({'sha256': ['abcd']}) == Hashes({'sha256': ['abcd']})
assert Hashes({'sha256': ['ab', 'cd']}) == Hashes({'sha256': ['cd', 'ab']})

def test_hash(self):
cache = {}
cache[Hashes({'sha256': ['ab', 'cd']})] = 42
assert cache[Hashes({'sha256': ['ab', 'cd']})] == 42


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

0 comments on commit 2e11f31

Please sign in to comment.