Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
djm Avatar asked Oct 20 '25 04:10

djm


2 Answers

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.

like image 94
djm Avatar answered Oct 21 '25 17:10

djm


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

like image 35
Wes Doyle Avatar answered Oct 21 '25 17:10

Wes Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!