How to mock the Django Model.save() function in python?
I'm using the mock library and I want to be able to mock the save()
function of my model class in the following way:
Twice the original function should be i开发者_开发百科nvoked (and succeed in actually saving the model), and the third time it should throw an exception.
This is for a unit test of a function that calls save
three times (and this particular test needs to handle a case in which only the third call fails).
Based on http://pypi.python.org/pypi/mock documentation.
>>> values = [1, 2]
>>> def side_effect():
... return values.pop()
...
>>> real = SomeModelClass()
>>> real.save = Mock(side_effect=side_effect)
Should work twice, then fail with an IndexError
every time after that.
I have no clue what that can possibly demonstrate about your code when the infrastructure stops working. Are you also testing all OS calls? All Python library calls? All other Django methods to see that your application somehow copes with those failures?
精彩评论