From 813e9476153c47e28163d3b635481f741f93d54e Mon Sep 17 00:00:00 2001 From: Alexandre Ferland Date: Thu, 13 Aug 2020 16:46:46 -0400 Subject: [PATCH] add missing magic methods for comparison --- setup.py | 2 +- tests/test_xid.py | 20 ++++++++++++-------- xid/xid.py | 21 ++++++++++++++++++--- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/setup.py b/setup.py index 3711427..3d285c3 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ setup( name="py-xid", - version="0.2.0", + version="0.3.0", description="", url="http://github.com/alexferl/xid", author="Alexandre Ferland", diff --git a/tests/test_xid.py b/tests/test_xid.py index c47550b..4244349 100644 --- a/tests/test_xid.py +++ b/tests/test_xid.py @@ -99,14 +99,6 @@ def test_from_bytes_invariant(): assert xid1.bytes() == xid2.bytes() -def test_sort(): - xid1 = XID() - xid2 = XID() - - assert xid1 < xid2 - assert xid2 > xid1 - - def test_repr(): xid = XID( id_=bytes( @@ -125,3 +117,15 @@ def test_pass_timestamp(): def test_pass_wrong_type(): with pytest.raises(TypeError): XID(id_=[]) + + +def test_compare(): + xid1 = XID() + xid2 = XID() + + assert (xid1 == xid2) is False + assert xid1 != xid2 + assert xid1 < xid2 + assert xid1 <= xid2 + assert xid2 > xid1 + assert xid2 >= xid1 diff --git a/xid/xid.py b/xid/xid.py index 3e60888..46ee60b 100644 --- a/xid/xid.py +++ b/xid/xid.py @@ -201,18 +201,33 @@ def counter(self) -> int: def bytes(self) -> bytes: return self.id - def __repr__(self): - return "XID('%s')" % self.__str__() - def __str__(self): return self.string() + def __hash__(self): + return hash(self.id) + + def __eq__(self, other: XID) -> bool: + return self.string() == other.string() + + def __ne__(self, other: XID) -> bool: + return self.string() != other.string() + def __lt__(self, other: XID) -> bool: return self.string() < other.string() + def __le__(self, other: XID) -> bool: + return self.string() <= other.string() + def __gt__(self, other: XID) -> bool: return self.string() > other.string() + def __ge__(self, other: XID) -> bool: + return self.string() >= other.string() + + def __repr__(self): + return "XID('%s')" % self.__str__() + def _uint8(n: int) -> int: return ctypes.c_uint8(n).value