Last active
June 4, 2017 09:26
-
-
Save jamescooke/1bed3414fee7d5c72540e567bcd63887 to your computer and use it in GitHub Desktop.
Tests on Django Q object assertion helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
import pytest | |
from django.db.models import Q | |
def assert_q_equal(left, right): | |
""" | |
Simply test two Q objects for equality. Does is not match commutative. | |
Args: | |
left (Q) | |
right (Q) | |
Raises: | |
AssertionError: When - | |
* `left` or `right` are not an instance of `Q` | |
* `left` and `right` are not considered equal. | |
""" | |
assert isinstance(left, Q), f'{left.__class__} is not subclass of Q' | |
assert isinstance(right, Q), f'{right.__class__} is not subclass of Q' | |
assert str(left) == str(right), f'Q{left} != Q{right}' | |
# --- Matches --- | |
def test_eq_self(): | |
""" | |
Matching is reflexive, matches self | |
""" | |
q_a = Q(location='London') | |
assert_q_equal(q_a, q_a) | |
def test_eq(): | |
""" | |
Matching Q objects matches their internal | |
""" | |
assert_q_equal(Q(location='北京市'), Q(location='北京市')) | |
def test_eq_multi_and(): | |
""" | |
assert_q_equal matches multi Qs | |
""" | |
assert_q_equal(Q(direction='north') & Q(speed=12), Q(direction='north') & Q(speed=12)) | |
assert_q_equal(Q(direction='north') | Q(speed=12), Q(direction='north') | Q(speed=12)) | |
# Non-matches | |
def test_neq_simple(): | |
""" | |
assert_q_equal spots that Q filters do not match | |
""" | |
q_a = Q(location='北京市') | |
q_b = Q(location='北京') | |
with pytest.raises(AssertionError): | |
assert_q_equal(q_a, q_b) | |
def test_neq_multi_and(): | |
""" | |
assert_q_equal matches multi Qs | |
""" | |
q_a = Q(direction='north') & Q(speed=13) | |
q_b = Q(direction='north') & Q(speed=12) | |
with pytest.raises(AssertionError): | |
assert_q_equal(q_a, q_b) | |
def test_neq_multi_not_commutative(): | |
""" | |
assert_q_equal does not match commutative: A & B != B & A | |
""" | |
q_a = Q(speed=12) & Q(direction='north') | |
q_b = Q(direction='north') & Q(speed=12) | |
with pytest.raises(AssertionError): | |
assert_q_equal(q_a, q_b) | |
def test_neq_type_a(): | |
""" | |
assert_q_equal raises if either q is not of type Q, left side | |
""" | |
q_a = 1 | |
q_b = Q(location='New York') | |
with pytest.raises(AssertionError): | |
assert_q_equal(q_a, q_b) | |
def test_neq_type_b(): | |
""" | |
assert_q_equal raises if either q is not of type Q, right side | |
""" | |
q_a = Q(location='New York') | |
q_b = "(AND: ('location', u'New York'))" | |
with pytest.raises(AssertionError): | |
assert_q_equal(q_a, q_b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment