Message 331433 - Python tracker (original) (raw)
It seems that TestCase in unittest.case accepts failureException attribute that is raised on assertion failure. My initial approach is to subclass TestCase and add a custom failure exception like MockException that is caught to add the diff to the original message. I am adding @cjw296 and @mariocj89 for feedback since I hope this can reuse unittest.case.TestCase implementation for diffs. I think this is better done with a flag like verbose=True to display the difference and defaulting to False since sometimes the message can be long depending on args and kwargs. Also I find args (tuple) comparison to be little distracting. Since this is an enhancement I am adding 3.8.
Sample file
from unittest.mock import Mock
m = Mock() m(1, 2, foo='bar', bar='baz') m.assert_called_with(2, 3, bar='baz', foo='car')
On 3.7
$ python3.7 /tmp/foo_4.py Traceback (most recent call last): File "/tmp/foo_4.py", line 5, in m.assert_called_with(2, 3, bar='baz', foo='car') File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 820, in assert_called_with raise AssertionError(_error_message()) from cause AssertionError: Expected call: mock(2, 3, bar='baz', foo='car')
With patch
$ ./python.exe /tmp/foo_4.py Traceback (most recent call last): File "/tmp/foo_4.py", line 5, in m.assert_called_with(2, 3, bar='baz', foo='car') File "/Users/karthikeyansingaravelan/stuff/python/cpython/Lib/unittest/mock.py", line 844, in assert_called_with raise AssertionError(_error_message()) from cause AssertionError: Expected call: mock(2, 3, bar='baz', foo='car') Actual call: mock(1, 2, bar='baz', foo='bar') args: Tuples differ: (2, 3) != (1, 2)
First differing element 0: 2 1
- (2, 3)
- (1, 2) kwargs: {'bar': 'baz', 'foo': 'car'} != {'foo': 'bar', 'bar': 'baz'}
- {'bar': 'baz', 'foo': 'car'} ? ^
- {'bar': 'baz', 'foo': 'bar'} ? ^