Add __eq__ to Q and Q operations

This commit is contained in:
Filip Kucharczyk 2019-12-03 00:42:10 +01:00
parent 138e759161
commit 0458ef869e
2 changed files with 44 additions and 0 deletions

View File

@ -96,9 +96,11 @@ class QNode(object):
"""Combine this node with another node into a QCombination """Combine this node with another node into a QCombination
object. object.
""" """
# If the other Q() is empty, ignore it and just use `self`.
if getattr(other, "empty", True): if getattr(other, "empty", True):
return self return self
# Or if this Q is empty, ignore it and just use `other`.
if self.empty: if self.empty:
return other return other
@ -146,6 +148,13 @@ class QCombination(QNode):
def empty(self): def empty(self):
return not bool(self.children) return not bool(self.children)
def __eq__(self, other):
return (
self.__class__ == other.__class__
and self.operation == other.operation
and self.children == other.children
)
class Q(QNode): class Q(QNode):
"""A simple query object, used in a query tree to build up more complex """A simple query object, used in a query tree to build up more complex
@ -164,3 +173,6 @@ class Q(QNode):
@property @property
def empty(self): def empty(self):
return not bool(self.query) return not bool(self.query)
def __eq__(self, other):
return self.__class__ == other.__class__ and self.query == other.query

View File

@ -374,6 +374,38 @@ class TestQ(unittest.TestCase):
== 2 == 2
) )
def test_equality(self):
assert Q(name="John") == Q(name="John")
assert Q() == Q()
def test_inequality(self):
assert Q(name="John") != Q(name="Ralph")
def test_operation_equality(self):
q1 = Q(name="John") | Q(title="Sir") & Q(surname="Paul")
q2 = Q(name="John") | Q(title="Sir") & Q(surname="Paul")
assert q1 == q2
def test_operation_inequality(self):
q1 = Q(name="John") | Q(title="Sir")
q2 = Q(title="Sir") | Q(name="John")
assert q1 != q2
def test_combine_and_empty(self):
q = Q(x=1)
assert q & Q() == q
assert Q() & q == q
def test_combine_and_both_empty(self):
assert Q() & Q() == Q()
def test_combine_or_empty(self):
q = Q(x=1)
assert q | Q() == q
assert Q() | q == q
def test_combine_or_both_empty(self):
assert Q() | Q() == Q()
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()