Skip to content

Commit 72751fe

Browse files
author
Michael Foord
committed
unittest.TestCase.assertDictEqual and assertMultilineEqual provide better default failure messages in the event of long diffs.
1 parent fc6db1d commit 72751fe

2 files changed

Lines changed: 12 additions & 6 deletions

File tree

Lib/unittest/case.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -800,10 +800,11 @@ def assertDictEqual(self, d1, d2, msg=None):
800800
self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
801801

802802
if d1 != d2:
803+
standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
803804
diff = ('\n' + '\n'.join(difflib.ndiff(
804805
pprint.pformat(d1).splitlines(),
805806
pprint.pformat(d2).splitlines())))
806-
standardMsg = self._truncateMessage('', diff)
807+
standardMsg = self._truncateMessage(standardMsg, diff)
807808
self.fail(self._formatMessage(msg, standardMsg))
808809

809810
def assertDictContainsSubset(self, expected, actual, msg=None):
@@ -886,9 +887,10 @@ def assertMultiLineEqual(self, first, second, msg=None):
886887
'Second argument is not a string'))
887888

888889
if first != second:
890+
standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
889891
diff = '\n' + ''.join(difflib.ndiff(first.splitlines(True),
890892
second.splitlines(True)))
891-
standardMsg = self._truncateMessage('', diff)
893+
standardMsg = self._truncateMessage(standardMsg, diff)
892894
self.fail(self._formatMessage(msg, standardMsg))
893895

894896
def assertLess(self, a, b, msg=None):

Lib/unittest/util.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@
22

33
__unittest = True
44

5-
6-
def safe_repr(obj):
5+
_MAX_LENGTH = 80
6+
def safe_repr(obj, short=False):
77
try:
8-
return repr(obj)
8+
result = repr(obj)
99
except Exception:
10-
return object.__repr__(obj)
10+
result = object.__repr__(obj)
11+
if not short or len(result) < _MAX_LENGTH:
12+
return result
13+
return result[:_MAX_LENGTH] + ' [truncated]...'
14+
1115

1216
def strclass(cls):
1317
return "%s.%s" % (cls.__module__, cls.__name__)

0 commit comments

Comments
 (0)