diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -4,17 +4,17 @@ import sys import functools import difflib import pprint import re import warnings import collections from . import result -from .util import (strclass, safe_repr, sorted_list_difference, +from .util import (strclass, safe_repr, truncate_str, sorted_list_difference, unorderable_list_difference, _count_diff_all_purpose, _count_diff_hashable) __unittest = True DIFF_OMITTED = ('\nDiff is %s characters long. ' 'Set self.maxDiff to None to see it.') @@ -645,17 +645,26 @@ class TestCase(object): if asserter is not None: return asserter return self._baseAssertEqual def _baseAssertEqual(self, first, second, msg=None): """The default assertEqual implementation, not type specific.""" if not first == second: - standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second)) + + firststring, secondstring = safe_repr(first), safe_repr(second) + + # check that standardMsg will be shorter than maxDiff + if (self.maxDiff is not None and + (len(firststring) + len(secondstring) + 8) > self.maxDiff): + standardMsg = '%s != %s' % (truncate_str(firststring, self.maxDiff), + truncate_str(secondstring, self.maxDiff)) + else: + standardMsg = '%s != %s' % (firststring, secondstring) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg) def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ assertion_func = self._getAssertEqualityFunc(first, second) diff --git a/Lib/unittest/util.py b/Lib/unittest/util.py --- a/Lib/unittest/util.py +++ b/Lib/unittest/util.py @@ -1,23 +1,27 @@ """Various utility functions.""" from collections import namedtuple, OrderedDict __unittest = True _MAX_LENGTH = 80 -def safe_repr(obj, short=False): +def safe_repr(obj, short=False, maxLength = _MAX_LENGTH): try: result = repr(obj) except Exception: result = object.__repr__(obj) - if not short or len(result) < _MAX_LENGTH: + if not short or len(result) < maxLength: return result - return result[:_MAX_LENGTH] + ' [truncated]...' + return truncate_str(result, maxLength) + +def truncate_str (obj, maxLength = _MAX_LENGTH): + #Truncate a string and add a message + return obj[:maxLength] + ' [truncated]...' def strclass(cls): return "%s.%s" % (cls.__module__, cls.__name__) def sorted_list_difference(expected, actual): """Finds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those