I am mocking a method. I want to raise an exception on the first call, but on exception, I am calling that method again with different parameters, so I want the second call to be processed normally. What do I need to do?
with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=Exception)):
with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=[Exception, some_method])):
On the second call, some_method
is returned as it is, and data is not processed with different parameters.
How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .
Note that the order in which the various test cases will be run is determined by sorting the test function names with respect to the built-in ordering for strings.
side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.
class Foo(object):
def Method1(self, arg):
pass
def Method2(self, arg):
if not arg:
raise
self.Method1(arg)
def Method3(self, arg):
try:
self.Method2(arg)
except:
self.Method2('some default value')
class FooTest(unittest.TestCase):
def SetUp(self):
self.helper = Foo()
def TestFooMethod3(self):
with mock.patch.object(self.helper, 'Method2',
side_effect=[Exception,self.helper.Method1]
) as mock_object:
self.helper.Method3('fake_arg')
mock_object.assert_has_calls([mock.call('fake_arg'),
mock.call('some default value')])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With