4

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?

1 Answer 1

3

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() 
Sign up to request clarification or add additional context in comments.

3 Comments

That is not a bad idea. I've implemented that and it does indeed work. I'll wait a bit to see if there'll be solutions that feel less hacky though? I just wonder if there's a more direct way to tell mock and/or unittest to just stop execution as soon as some condition is met. Thank you, in any case, for your answer!
Yeah, was kinda surprised there wasn't a version of this with nicer syntax in the library already. My best guess is that mock lets everything run through by default, so multiple tests can happen in one pass?
An alternative to try/except would be to use self.assertRaises(CallException)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.