Issue 15323: Provide target name in output message when Mock.assert_called_once_with fails (original) (raw)

In Python 3.3.0b1, if the number of calls to a mock is, say, zero, and you call assert_called_once_with() on that mock, it will throw an exception which says "Expected to be called once. Called 0 times."

This is nice, but it would be nicer if the output message actually told the end user what it expected to be called once. I've supplied a patch and documentation update that makes this change by adding _mock_name to the output message using the variable interpolation method already being used in that message to output the call count.

The result looks like this (for the case in the documentation):

Python 3.3.0b1 (default:2ecdda96f970+, Jul 10 2012, 22:45:18) [GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin Type "help", "copyright", "credits" or "license" for more information.

from unittest.mock import Mock [103576 refs] mock = Mock(return_value=None) [103641 refs] mock('foo', bar='baz') [103679 refs] mock.assert_called_once_with('foo', bar='baz') [103680 refs] mock('foo', bar='baz') [103703 refs] mock.assert_called_once_with('foo', bar='baz') Traceback (most recent call last): File "", line 1, in File "/Users/brianj/Dropbox/Source/Python/cpython/Lib/unittest/mock.py", line 736, in assert_called_once_with raise AssertionError(msg) AssertionError: Expected 'mock' to be called once. Called 2 times. [103758 refs]

In the above case, the mock was never given a name, and wasn't instantiated with any particular target. Here's an example using a patch on 'time.time' to show the effect:

Python 3.3.0b1 (default:2ecdda96f970+, Jul 10 2012, 22:45:18) [GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin Type "help", "copyright", "credits" or "license" for more information.

from unittest.mock import patch [106009 refs] with patch('time.time') as foo: ... foo.assert_called_once_with() ... Traceback (most recent call last): File "", line 2, in File "/Users/brianj/Dropbox/Source/Python/cpython/Lib/unittest/mock.py", line 736, in assert_called_once_with raise AssertionError(msg) AssertionError: Expected 'time' to be called once. Called 0 times. [106621 refs]

Eric: yes, patch sets the name on the mock objects it creates. A mock only knows its direct name, not its full 'dotted' name (i.e. a mock knows it is called 'time' but not that it is 'time.time'). It is possible (but harder) to deduce that name (follow the chain of parents), so for the moment this change will do.