From c653ce313f6781d27852a3f3552a0295c1a1fa6a Mon Sep 17 00:00:00 2001 From: Michael Foord Date: Sat, 10 Jul 2010 13:52:22 +0000 Subject: [PATCH] Fix error message for comparing single line strings in unittest.TestCase.assertEqual. Issue 9174. --- Lib/unittest/case.py | 11 ++++++++--- Lib/unittest/test/test_case.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index 3bc2b3d1edc..03346a158c2 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -940,9 +940,14 @@ class TestCase(object): 'Second argument is not a string')) if first != second: - standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True)) - diff = '\n' + ''.join(difflib.ndiff(first.splitlines(True), - second.splitlines(True))) + firstlines = first.splitlines(True) + secondlines = second.splitlines(True) + if len(firstlines) == 1 and first.strip('\r\n') == first: + firstlines = [first + '\n'] + secondlines = [second + '\n'] + standardMsg = '%s != %s' % (safe_repr(first, True), + safe_repr(second, True)) + diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) diff --git a/Lib/unittest/test/test_case.py b/Lib/unittest/test/test_case.py index 00883c9bd2d..1800f2e5df1 100644 --- a/Lib/unittest/test/test_case.py +++ b/Lib/unittest/test/test_case.py @@ -841,6 +841,21 @@ test case # so can't use assertEqual either. Just use assertTrue. self.assertTrue(sample_text_error == error) + def testAsertEqualSingleLine(self): + sample_text = "laden swallows fly slowly" + revised_sample_text = "unladen swallows fly quickly" + sample_text_error = """\ +- laden swallows fly slowly +? ^^^^ ++ unladen swallows fly quickly +? ++ ^^^^^ +""" + try: + self.assertEqual(sample_text, revised_sample_text) + except self.failureException as e: + error = str(e).split('\n', 1)[1] + self.assertTrue(sample_text_error == error) + def testAssertIsNone(self): self.assertIsNone(None) self.assertRaises(self.failureException, self.assertIsNone, False)