Add an __eq__ method to Identity

This commit is contained in:
Gergely Polonkai 2022-05-04 13:52:20 +02:00
parent 476e6ad22d
commit 1d40bbebc5
No known key found for this signature in database
GPG Key ID: 2D2885533B869ED4
2 changed files with 42 additions and 0 deletions

View File

@ -58,6 +58,17 @@ class Identity:
def __repr__(self) -> str: def __repr__(self) -> str:
return f'<Identity {self}>' return f'<Identity {self}>'
def __eq__(self, other: object) -> bool:
if isinstance(other, str):
return str(self) == other
if isinstance(other, Identity):
return str(self) == str(other)
raise TypeError(
'Dont know how to compare {self.__class__.__name__} and {other.__class__.__name__}'
)
@classmethod @classmethod
def from_address(cls, address: str) -> 'Identity': def from_address(cls, address: str) -> 'Identity':
"""Load an identity from an author address""" """Load an identity from an author address"""

View File

@ -168,3 +168,34 @@ def test_valid_address() -> None:
"""Test if valid_address passes on valid addresses""" """Test if valid_address passes on valid addresses"""
assert Identity.valid_address('@test.bcz76z52y5dlpohtkmpuj3jsdcvfmebzpcgfmtmhu4u7hlexzreya') assert Identity.valid_address('@test.bcz76z52y5dlpohtkmpuj3jsdcvfmebzpcgfmtmhu4u7hlexzreya')
def test_eq_str() -> None:
"""Test if an Identity is considered equal to its string representation"""
identity_str = '@test.bcz76z52y5dlpohtkmpuj3jsdcvfmebzpcgfmtmhu4u7hlexzreya'
identity = Identity.from_address(identity_str)
assert identity == identity_str
assert identity != '@test.cz76z52y5dlpohtkmpuj3jsdcvfmebzpcgfmtmhu4u7hlexzreyb'
def test_eq_identity() -> None:
"""Test if two different identities are considered equal if their verifying key is equal"""
identity_str = '@test.bcz76z52y5dlpohtkmpuj3jsdcvfmebzpcgfmtmhu4u7hlexzreya'
identity1 = Identity.from_address(identity_str)
identity2 = Identity.from_address(identity_str)
identity3 = Identity.generate('some')
assert identity1 == identity2
assert identity1 != identity3
@pytest.mark.id_key_seed(TEST_SEED)
@pytest.mark.id_name('test')
def test_eq_other(identity: Identity) -> None:
"""Test if Identity cannot be compared to something like an int"""
with pytest.raises(TypeError):
assert identity == 1