Skip to content

Instantly share code, notes, and snippets.

@mattjmorrison
Created April 28, 2011 19:35
Show Gist options
  • 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 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