3

I am setting up a MagicMock instance, calling the same method twice with different arguments, and setting my assertion to only validate for one set of arguments.

Python: 3.5.2

from unittest.mock import MagicMock

my_mock = MagicMock()
my_mock.some_method()
my_mock.some_method(123)

my_mock.some_method.assert_called_once_with(123)

AssertionError: Expected 'some_method' to be called once. Called 2 times.

I would expect this to pass. Why does it ignore the arguments?

djm
  • 119
  • 1
  • 5

2 Answers2

4

We have discovered that assert_called_with is actually what we want.

It seems confusing and I think it should be called assert_called_only_once_with.

djm
  • 119
  • 1
  • 5
3

From the unittest.mock docs:

assert_called_once_with(*args, **kwargs)

Assert that the mock was called exactly once and that that call was with the specified arguments.

Since you are calling the method twice, this should fail.

In this specific case, you might use:

expected_calls = [call(), call(123)]
my_mock.some_method.assert_has_calls(expected_calls, any_order=False)

Which will assert the expected calls have been used in the order specified in expected_calls

Community
  • 1
  • 1
Wes Doyle
  • 2,199
  • 3
  • 17
  • 32