Skip to content

Commit

Permalink
allow bytes, fix literal check
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Sep 15, 2022
1 parent 1c13be9 commit aa706fc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
13 changes: 10 additions & 3 deletions dirty_equals/_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,27 +166,34 @@ def __init__(self, hash_type: HashTypes):
from dirty_equals import IsHash
assert 'f1e069787ece74531d112559945c6871' == IsHash('md5')
assert b'f1e069787ece74531d112559945c6871' == IsHash('md5')
assert 'f1e069787ece74531d112559945c6871' != IsHash('sha-256')
assert 'F1E069787ECE74531D112559945C6871' == IsHash('md5')
assert '40bd001563085fc35165329ea1ff5c5ecbdbbeef' == IsHash('sha-1')
assert 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3' == IsHash('sha-256')
```
"""

allowed_hashes = 'md5', 'sha-1', 'sha-256'
if hash_type not in HashTypes.__args__: # type: ignore[attr-defined]
allowed_hashes = HashTypes.__args__ # type: ignore[attr-defined]
if hash_type not in allowed_hashes:
raise ValueError(f"Hash type must be one of the following values: {', '.join(allowed_hashes)}")

self.hash_type = hash_type
super().__init__(hash_type)

def equals(self, other: Any) -> bool:
if isinstance(other, str):
s = other
elif isinstance(other, (bytes, bytearray)):
s = other.decode()
else:
return False
hash_type_regex_patterns = {
'md5': r'[a-fA-F\d]{32}',
'sha-1': r'[a-fA-F\d]{40}',
'sha-256': r'[a-fA-F\d]{64}',
}
return bool(re.fullmatch(hash_type_regex_patterns[self.hash_type], other))
return bool(re.fullmatch(hash_type_regex_patterns[self.hash_type], s))


IP = TypeVar('IP', IPv4Address, IPv4Network, IPv6Address, IPv6Network, Union[str, int, bytes])
Expand Down
3 changes: 3 additions & 0 deletions tests/test_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ def test_ip_bad_netmask():
('f1e069787ECE74531d112559945c6871', IsHash('md5')),
('40bd001563085fc35165329ea1FF5c5ecbdbbeef', IsHash('sha-1')),
('a665a45920422f9d417e4867eFDC4fb8a04a1f3fff1fa07e998e86f7f7a27ae3', IsHash('sha-256')),
(b'f1e069787ECE74531d112559945c6871', IsHash('md5')),
(bytearray(b'f1e069787ECE74531d112559945c6871'), IsHash('md5')),
],
)
def test_is_hash_true(other, dirty):
Expand All @@ -202,6 +204,7 @@ def test_is_hash_true(other, dirty):
'other,dirty',
[
('foobar', IsHash('md5')),
(b'\x81 UnicodeDecodeError', IsHash('md5')),
([1, 2, 3], IsHash('sha-1')),
('f1e069787ECE74531d112559945c6871d', IsHash('md5')),
('400bd001563085fc35165329ea1FF5c5ecbdbbeef', IsHash('sha-1')),
Expand Down

0 comments on commit aa706fc

Please sign in to comment.