mirror of https://github.com/pypa/pip
utils: make Hashes object hashable
This commit is contained in:
parent
a0e34e9cf7
commit
4dc48da9db
|
@ -39,7 +39,12 @@ class Hashes(object):
|
|||
: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
|
||||
|
@ -128,6 +133,22 @@ class Hashes(object):
|
|||
# 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
|
||||
|
|
|
@ -541,6 +541,16 @@ class TestHashes(object):
|
|||
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"""
|
||||
|
|
Loading…
Reference in New Issue