Let's say I want to make sure that certain flags etc get dispatched properly so that deep within my library, a particular function gets called:
high_order_function_call(**kwargs)
deep down contains library_function_call()
and I want to make sure that it gets actually called.
The typical example given for this uses mock.patch
:
@mock.patch('library')
def test_that_stuff_gets_called(self, mock_library):
high_order_function_call(some_example_keyword='foo')
mock_library.library_function_call.assert_called_with(42)
Now in that case, I have to wait for the entire execution of all the stuff in high_order_function_call
. What if I want execution to stop and jump back to my unit test as soon as mock_library.library_function_call
gets reached?
You could try using an exception raising side effect on the call, and then catch that exception in your test.
from mock import Mock, patch
import os.path
class CallException(Exception):
pass
m = Mock(side_effect=CallException('Function called!'))
def caller_test():
os.path.curdir()
raise RuntimeError("This should not be called!")
@patch("os.path.curdir", m)
def test_called():
try:
os.path.curdir()
except CallException:
print "Called!"
return
assert "Exception not called!"
if __name__ == "__main__":
test_called()
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