Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test: How to assert multiple calls of same method?

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?

like image 406
0xc0de Avatar asked Nov 28 '13 16:11

0xc0de


1 Answers

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.

like image 99
Simeon Visser Avatar answered Sep 21 '22 05:09

Simeon Visser