tortoise-orm
tortoise-orm copied to clipboard
Add __eq__ method to Q to more easily test dynamically-built queries
Add __eq__ method to Q to more easily test dynamically-built queries
Description
When a query is built dynamically it is needed to be tested if it is built correctly. As query is built in a tree it is too hard to test it.
Motivation and Context
Lets say the following query is built dynamically
def build_dynamic_query():
return (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane")
Currently to test it, the following code needs to be written which is already too complicated with just three Q objects.
def test_build_dynamic_query():
dynamic_query = build_dynamic_query()
expected_query = (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane")
assert dynamic_query.join_type == expected_query.join_type
assert dynamic_query.filters == expected_query.filters
q1_2, q3 = expected_query.children
expected_q3 = Q(mother_name="Jane")
assert q1_2.join_type == Q.AND
assert q3.join_type == expected_q3.join_type
assert q3.filters == expected_q3.filters
assert q3.children == expected_q3.children
q1, q2 = q1_2.children
expected_q2 = Q(lastname="Doe")
assert q2.join_type == expected_q2.join_type
assert q2.filters == expected_q2.filters
assert q2.children == expected_q2.children
expected_q1 = Q(firstname="John")
assert q1.join_type == expected_q1.join_type
assert q1.filters == expected_q1.filters
assert q1.children == expected_q1.children
With this feature, the result will be checked against the expected value
def test_build_dynamic_query():
dynamic_query = build_dynamic_query()
expected_query = (Q(firstname="John") & Q(lastname="Doe")) | Q(mother_name="Jane")
assert dynamic_query == expected_query
How Has This Been Tested?
I added tests for various queries including basic, or, and, combination of and and or.
Checklist:
- [x] My code follows the code style of this project.
- [x] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have added the changelog accordingly.
- [x] I have read the CONTRIBUTING document.
- [x] I have added tests to cover my changes.
- [x] All new and existing tests passed.
Thanks! Please update changelog.
Thanks! Please update changelog.
Done