Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat add IsHash #44

Merged
merged 5 commits into from
Sep 15, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion dirty_equals/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
IsPositiveFloat,
IsPositiveInt,
)
from ._other import FunctionCheck, IsJson, IsUUID
from ._other import FunctionCheck, IsHash, IsJson, IsUUID
from ._sequence import Contains, HasLen, IsList, IsListOrTuple, IsTuple
from ._strings import IsAnyStr, IsBytes, IsStr

Expand Down Expand Up @@ -69,6 +69,7 @@
'FunctionCheck',
'IsJson',
'IsUUID',
'IsHash',
# strings
'IsStr',
'IsBytes',
Expand Down
40 changes: 40 additions & 0 deletions dirty_equals/_other.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import re
from typing import Any, Callable, TypeVar, overload
from uuid import UUID

Expand Down Expand Up @@ -145,3 +146,42 @@ def is_even(x):

def equals(self, other: Any) -> bool:
return self.func(other)

samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved

class IsHash(DirtyEquals[str]):
"""
A class that checks if a value is a valid common hash type.
osintalex marked this conversation as resolved.
Show resolved Hide resolved
"""

def __init__(self, hash_type: Literal['md5', 'sha-1', 'sha-256']):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def __init__(self, hash_type: Literal['md5', 'sha-1', 'sha-256']):
def __init__(self, hash_type: HashTypes):

"""
Args:
hash_type: The hash type to check. Must be specified.

```py title="IsUUID"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```py title="IsUUID"
```py title="IsHash"

from dirty_equals import IsHash

assert '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 and hash_type not in allowed_hashes:
osintalex marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError(f"Hash type must be one of the following values: {', '.join(allowed_hashes)}")

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

md5_regex = re.compile(r'^[a-fA-F\d]{32}$')
sha_1_regex = re.compile(r'^[a-fA-F\d]{40}$')
sha256_regex = re.compile(r'^[a-fA-F\d]{64}$')
osintalex marked this conversation as resolved.
Show resolved Hide resolved
self.hash_type_regex_patterns = {'md5': md5_regex, 'sha-1': sha_1_regex, 'sha-256': sha256_regex}

def equals(self, other: Any) -> bool:
match = re.fullmatch(self.hash_type_regex_patterns[self.hash_type], other)
result = True if match else False
return result
osintalex marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 2 additions & 0 deletions docs/types/other.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@
::: dirty_equals.AnyThing

::: dirty_equals.IsOneOf

::: dirty_equals.IsHash
44 changes: 43 additions & 1 deletion tests/test_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from dirty_equals import FunctionCheck, IsJson, IsUUID
from dirty_equals import FunctionCheck, IsHash, IsJson, IsUUID


@pytest.mark.parametrize(
Expand Down Expand Up @@ -128,3 +128,45 @@ def foobar(v):
def test_json_both():
with pytest.raises(TypeError, match='IsJson requires either an argument or kwargs, not both'):
IsJson(1, a=2)


@pytest.mark.parametrize(
'other,dirty',
[
('f1e069787ECE74531d112559945c6871', IsHash('md5')),
('40bd001563085fc35165329ea1FF5c5ecbdbbeef', IsHash('sha-1')),
('a665a45920422f9d417e4867eFDC4fb8a04a1f3fff1fa07e998e86f7f7a27ae3', IsHash('sha-256')),
],
)
def test_is_hash_true(other, dirty):
assert other == dirty


@pytest.mark.parametrize(
'other,dirty',
[
('foobar', IsHash('md5')),
([1, 2, 3], IsHash('sha-1')),
('f1e069787ECE74531d112559945c6871d', IsHash('md5')),
('400bd001563085fc35165329ea1FF5c5ecbdbbeef', IsHash('sha-1')),
('a665a45920422g9d417e4867eFDC4fb8a04a1f3fff1fa07e998e86f7f7a27ae3', IsHash('sha-256')),
],
)
def test_is_hash_false(other, dirty):
assert other != dirty


@pytest.mark.parametrize(
'hash_type',
['md5', 'sha-1', 'sha-256'],
)
def test_is_hash_md5_false_repr(hash_type):
is_hash = IsHash(hash_type)
with pytest.raises(AssertionError):
assert '123' == is_hash
assert str(is_hash) == f"IsHash('{hash_type}')"

osintalex marked this conversation as resolved.
Show resolved Hide resolved

def test_wrong_hash_type():
with pytest.raises(ValueError, match='Hash type must be one of the following values: md5, sha-1, sha-256'):
assert '123' == IsHash('ntlm')