Created
April 28, 2011 19:35
-
-
Save mattjmorrison/947138 to your computer and use it in GitHub Desktop.
How to mock django's Q object
This file contains 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
@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) |
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
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:
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 :)