16

I have a method, which calls another method twice, with different arguments.

class A(object):
    def helper(self, arg_one, arg_two):
        """Return something which depends on arguments."""

    def caller(self):
        value_1 = self.helper(foo, bar)  # First call.
        value_2 = self.helper(foo_bar, bar_foo)  # Second call!

Using assert_called_with helps me asserting just the first call, and not the second one. Even assert_called_once_with doesn't seem to be helpful. What am I missing here? Is there any way to test such calls?

2 Answers 2

19

You can use mock_calls which contains all calls made to a method. This list contains the first call, the second call and all subsequent calls as well. So you can write assertions with mock_calls[1] to state something about the second call.


For example, if m = mock.Mock() and the code does m.method(123) then you write:

assert m.method.mock_calls == [mock.call(123)]

which asserts that the list of calls to m.method is exactly one call, namely a call with the argument 123.

Sign up to request clarification or add additional context in comments.

2 Comments

The example in their documentation doesn't make very much sense. Could you show a better example?
@BrandonIbbotson I have added an example to my answer above.
4

To add to Simon Visser's answer, you can use the unittest.TestCase self.assertEqual() method instead of the assert syntax, which I'd say is a better practise in the Unit Test context since you can also add comments to it that will be displayed whenever something goes wrong.

So for example:

self.assertEqual(
    [
        mock.call(1, 'ValueA', True)),
        mock.call(2, 'ValueB', False)),
        mock.call(3, 'ValueC', False))
    ],
    mock_cur.execute.mock_calls,
    "The method was not called with the correct arguments."
) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.