Skip to content

Commit

Permalink
Add __eq__ method to Q to more easily test dynamically-built queries
Browse files Browse the repository at this point in the history
  • Loading branch information
cikay committed Nov 5, 2023
1 parent 0ec208b commit cb609e9
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Added
- Add binary compression support for `UUIDField` in `MySQL`. (#1458)
- Only `Model`, `Tortoise`, `BaseDBAsyncClient`, `__version__`, and `connections` are now exported from `tortoise`
- Add parameter `validators` to `pydantic_model_creator`. (#1471)
- Add __eq__ method to Q to more easily test dynamically-built queries (#1506)

Fixed
^^^^^
Expand Down
21 changes: 21 additions & 0 deletions tests/test_q.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,27 @@ def test_q_partial_or(self):
self.assertEqual(q.filters, {"moo": "cow"})
self.assertEqual(q.join_type, "OR")

def test_q_equality(self):
# basic query
basic_q1 = Q(moo="cow")
basic_q2 = Q(moo="cow")
self.assertEqual(basic_q1, basic_q2)

# and query
and_q1 = Q(firstname="John") & Q(lastname="Doe")
and_q2 = Q(firstname="John") & Q(lastname="Doe")
self.assertEqual(and_q1, and_q2)

# or query
or_q1 = Q(firstname="John") | Q(lastname="Doe")
or_q2 = Q(firstname="John") | Q(lastname="Doe")
self.assertEqual(or_q1, or_q2)

# complex query
complex_q1 = (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane")
complex_q2 = (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane")
self.assertEqual(complex_q1, complex_q2)


class TestQCall(TestCase):
def test_q_basic(self):
Expand Down
7 changes: 7 additions & 0 deletions tortoise/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,13 @@ def __invert__(self) -> "Q":
q.negate()
return q

def __eq__(self, other: "Q") -> bool:
return (
self.children == other.children
and self.join_type == other.join_type
and self.filters == other.filters
)

def negate(self) -> None:
"""
Negates the current Q object. (mutation)
Expand Down

0 comments on commit cb609e9

Please sign in to comment.