[TIP] Testing multiple calls of the same method

Michael Foord michael at voidspace.org.uk
Tue Jun 21 07:57:50 PDT 2011

On 21/06/2011 09:56, Jean-Yves LEBLEU wrote:
> Hi all,
> First thanks for the mock library, coming from the java world were I
> used to test everything I find it very usefull and very easy to use.
> I came across the pb to test a method calling many times the same
> method of another object and I did not find any very good solution to
> this problem, except poping out the last call and checking the call in
> reverse order as in
> http://www.voidspace.org.uk/python/mock/examples.html#checking-multiple-calls-with-mock
> An other solution is to check if the call was made with arguments
> without any assertion of the order of the call, so I have implemented
> another assert_called_with  checking the call  was done once with the
> correct arguments.
>      def assert_was_called_with(self, *args, **kwargs):
>          '''
>          assert that the mock was called with the specified arguments.
>          Raises an AssertionError if the args and keyword args passed in are
>          different to the last call to the mock.
>          '''

So you would want to update the docstring to reflect the new functionality.

>          if self.call_args is None:
>              raise AssertionError('Expected: %s\nNot called' % ((args, kwargs),))
>          for xargs in self.call_args_list:
>              print xargs

Extra print here.

Why not just:

if (args, kwargs) in self.call_args_list:

>              if xargs == (args, kwargs):
>                  return
>          raise AssertionError(
>              'Expected: %s\nCalled with: %s' % ((args, kwargs), self.call_args)
>          )
You'll also want a different failure message.

All the best,


> Hope this will help.
> Jean-Yves
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html

More information about the testing-in-python mailing list