Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnitTest Python Mock first call to method, second call go as usual

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?

Code

Try 1

with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=Exception)):

Try 2

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.

like image 517
A.J. Avatar asked Dec 07 '15 14:12

A.J.


People also ask

How do you mock method calls in Python?

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 .

Does Unittest run tests in order?

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.

What is Side_effect in mock python?

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.


1 Answers

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')])
like image 113
Dan Avatar answered Sep 22 '22 13:09

Dan