Reputation: 9617
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?
Upvotes: 4
Views: 2064
Reputation: 430
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()
Upvotes: 3