[issue28054] Diff for visually comparing actual with expected in mock.assert_called_with.

Karthikeyan Singaravelan report at bugs.python.org
Sat Nov 10 13:46:40 EST 2018


Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:

I think this can be useful for keyword arguments as in the original suggestion. I tried an initial implementation as below to use difflib to get the difference like unittest if there are keyword args to be checked against the caller list since the absence of one or other generates a diff with empty {} which I find little distracting during my initial iterations. I would like to know if there is still sufficient interest in getting this to core only for keyword arguments given that there is pytest-mock with specialized error reporting handling more cases : https://github.com/pytest-dev/pytest-mock#improved-reporting-of-mock-call-assertion-errors


$ ./python.exe -q
>>> from unittest.mock import Mock
>>> m = Mock()
>>>
>>> m(foo='bar', bar='baz')
<Mock name='mock()' id='4484887184'>
>>>
>>> m.assert_called_with(bar='baz', foo='car')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/karthikeyansingaravelan/stuff/python/cpython/Lib/unittest/mock.py", line 838, in assert_called_with
    raise AssertionError(_error_message()) from cause
AssertionError: Expected call: mock(bar='baz', foo='car')
Actual call: mock(bar='baz', foo='bar')
- {'bar': 'baz', 'foo': 'car'}
?                        ^

+ {'bar': 'baz', 'foo': 'bar'}
?                        ^


diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index a9c82dcb5d..8603b4ac4c 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -749,6 +749,20 @@ class NonCallableMock(Base):
         call_args = self.call_args
         if len(call_args) == 3:
             call_args = call_args[1:]
+
+        diffMsg = ''
+        if kwargs and self.call_args[1]:
+            import difflib
+
+            seq1 = kwargs
+            seq2 = self.call_args[1]
+            diffMsg = '\n' + '\n'.join(
+                difflib.ndiff(pprint.pformat(seq1).splitlines(),
+                              pprint.pformat(seq2).splitlines()))
+
+        if diffMsg:
+            message += diffMsg
+
         actual_string = self._format_mock_call_signature(*call_args)
         return message % (expected_string, actual_string)

----------
nosy: +xtreak

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue28054>
_______________________________________


More information about the Python-bugs-list mailing list