Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is assert_called_with failing to pass?

I am having a lot of difficulty setting my unit test. I have been using patch but it is not behaving entirely as expected.

I have a decorator at the top of my test function: @mock.patch('WarningFactory.WarningAPIUpdate') @mock.patch('WarningFactory.SomethingElse') def test_send_tc_update(self, other_mock, api_mock):

However when at the end of my function when I try to make the following assertion:

api_mock.send_warning.assert_called_with('IDQ20026', 'IDQ20026')

It fails

I know that is should pass because I run

print api_mock.mock_calls

giving

[call(u'test_api'), call().send_warning('IDQ20026', 'IDQ20026'), call().send_warning('IDQ24500', 'IDQ24500')]

I can clearly see the send_warning method being called with the correct values, so why is my assertion failing?

like image 526
user3559247 Avatar asked Dec 06 '16 03:12

user3559247


1 Answers

Looking back now the problem was that assert_called_with only checks the most recent call.

assert_any_call(*args, **kwargs)¶ assert the mock has been called with the specified arguments.

The assert passes if the mock has ever been called, unlike assert_called_with() and assert_called_once_with() that only pass if the call is the most recent one, and in the case of assert_called_once_with() it must also be the only call.

  • from https://docs.python.org/3/library/unittest.mock.html

The docs are a little dodgy as they don't mention this under the assert_called_with method.

I ended up using the assert_any_call method for my tests.

like image 110
user3559247 Avatar answered Dec 19 '22 10:12

user3559247