Conditional mocking: Call original function if condition does match

If you need just replace behavior without care of mock’s calls assert function you can use new argument; otherwise you can use side_effect that take a callable.

I guess that some_method is a object method (instead of a staticmethod) so you need a reference its object to call it. Your wrapper should declare as first argument the object and your patch use autospec=True to use the correct signature for side_effect case.

Final trick is save the original method reference and use it to make the call.

orig = mylib.foo.some_method
def mocked_some_method(self, bar):
    if bar=='x':
        return 'fake'
    return orig(self, bar)

#Just replace:
with mock.patch('mylib.foo.some_method', new=mocked_some_method):
    do_some_stuff()

#Replace by mock
with mock.patch('mylib.foo.some_method', side_effect=mocked_some_method, autospec=True) as mock_some_method:
    do_some_stuff()
    assert mock_some_method.called

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)