djm
djm

Reputation: 129

Python MagicMock assert_called_once_with not taking into account arguments?

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?

Upvotes: 4

Views: 5485

Answers (2)

Wes Doyle
Wes Doyle

Reputation: 2287

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

Upvotes: 3

djm
djm

Reputation: 129

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.

Upvotes: 4

Related Questions