Skip to content

Instantly share code, notes, and snippets.

@jamescooke
Created March 28, 2016 10:25
Show Gist options
  • Save jamescooke/b9bd5afba3a7253d53bd to your computer and use it in GitHub Desktop.
Save jamescooke/b9bd5afba3a7253d53bd to your computer and use it in GitHub Desktop.
Tests on `assertQEquals` assertion helper. Full blog post at http://jamescooke.info/comparing-django-q-objects.html
# encoding: utf-8
from __future__ import unicode_literals
from django.db.models import Q
from django.test import TestCase
from .helpers import QTestMixin
class TestHelpers(TestCase, QTestMixin):
# Matches
def test_eq_self(self):
"""
assertQEqual is reflexive, matches self
"""
q_a = Q(location='London')
self.assertQEqual(q_a, q_a)
def test_eq(self):
"""
assertQEqual matches logic
"""
q_a = Q(location='北京市')
q_b = Q(location='北京市')
self.assertQEqual(q_a, q_b)
def test_eq_multi_and(self):
"""
assertQEqual matches multi Qs
"""
q_a = Q(direction='north') & Q(speed=12)
q_b = Q(direction='north') & Q(speed=12)
self.assertQEqual(q_a, q_b)
def test_eq_multi_or(self):
"""
assertQEqual matches multi Qs
"""
q_a = Q(direction='north') | Q(speed=12)
q_b = Q(direction='north') | Q(speed=12)
self.assertQEqual(q_a, q_b)
# Non-matches
def test_neq_simple(self):
"""
assertQEqual spots that Q filters do not match
"""
q_a = Q(location='北京市')
q_b = Q(location='北京')
with self.assertRaises(AssertionError):
self.assertQEqual(q_a, q_b)
def test_neq_multi_and(self):
"""
assertQEqual matches multi Qs
"""
q_a = Q(direction='north') & Q(speed=13)
q_b = Q(direction='north') & Q(speed=12)
with self.assertRaises(AssertionError):
self.assertQEqual(q_a, q_b)
def test_neq_multi_not_commutative(self):
"""
assertQEqual 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 self.assertRaises(AssertionError):
self.assertQEqual(q_a, q_b)
def test_neq_type_a(self):
"""
assertQEqual raises if either q is not of type Q, left side
"""
q_a = "(AND: ('location', u'New York'))"
q_b = Q(location='New York')
with self.assertRaises(AssertionError):
self.assertQEqual(q_a, q_b)
def test_neq_type_b(self):
"""
assertQEqual 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 self.assertRaises(AssertionError):
self.assertQEqual(q_a, q_b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment