Skip to content

Instantly share code, notes, and snippets.

@mattjmorrison
Created April 28, 2011 19:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattjmorrison/947138 to your computer and use it in GitHub Desktop.
Save mattjmorrison/947138 to your computer and use it in GitHub Desktop.
How to mock django's Q object
@patch('quote_options.models.LiabilityLimit.objects.filter')
@patch('quote.models.Q')
def should_filter_with_q_object_in_get_liability_limits(self, q_object, limit_filter):
manager_instance = Mock(spec=quote_models.LiabilityManager())
policy = mock.Mock()
q_instance = mock.Mock()
q_or_method = mock.Mock()
q_or_method.return_value = q_instance
q_instance.__or__ = q_or_method
q_object.return_value = q_instance
results = quote_models.LiabilityManager.get_liability_limits(manager_instance, policy)
limit_filter.assert_called_once_with(q_instance)
self.assertEqual(2, q_or_method.call_count)
self.assertEqual(limit_filter.return_value, results)
@azaghal
Copy link

azaghal commented Oct 14, 2013

This seems like a very useful snippet for testing-out custom manager methods that call filter with Q objects, but I just can't seem to get it working in a small project of my own.

On what would be the line 13 in my project (it's not the same code, of course), I keep getting something similar to:

  File "/home/branko/.virtualenvs/conntrackt/local/lib/python2.7/site-packages/django/db/models/query_utils.py", line 44, in __init__
    super(Q, self).__init__(children=list(args) + list(six.iteritems(kwargs)))
TypeError: must be type, not MagicMock

Have you faced something like this before? I can post the full code sample from test (didn't want to spam your gist, so that's why I haven't :)

@azaghal
Copy link

azaghal commented Nov 10, 2013

Ok, so in the end I figured out I was patching the object using a wrong namespace. Essentially, I failed to read:

http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch

Thanks for the gist once again :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment