diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index a157ae8a14bcbe..867589809dd549 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -1238,6 +1238,11 @@ def assertCountEqual(self, first, second, msg=None): msg = self._formatMessage(msg, standardMsg) self.fail(msg) + def addTrailingNewLine(self, line): + if line != '' and line[-1] != '\n': + line = line + '\n' + return line + def assertMultiLineEqual(self, first, second, msg=None): """Assert that two multi-line strings are equal.""" self.assertIsInstance(first, str, 'First argument is not a string') @@ -1254,7 +1259,10 @@ def assertMultiLineEqual(self, first, second, msg=None): firstlines = [first + '\n'] secondlines = [second + '\n'] standardMsg = '%s != %s' % _common_shorten_repr(first, second) - diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines)) + difflines = list(difflib.ndiff(firstlines, secondlines)) + if len(difflines) > 1: + difflines = [self.addTrailingNewLine(line) for line in difflines] + diff = '\n' + ''.join(difflines) 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 687fe5b65f109e..0b834bc4fa7083 100644 --- a/Lib/unittest/test/test_case.py +++ b/Lib/unittest/test/test_case.py @@ -1839,5 +1839,20 @@ def test2(self): self.assertEqual(MyException.ninstance, 0) +class testAssertEqualSingleLine(unittest.TestCase): + + def test_trailing_new_line_at_end(self): + self.assertEqual("abc\n", "abc\n") + def test_trailing_space_at_end(self): + self.assertEqual("abc ", "abc ") + def test_no_trailing_new_line(self): + self.assertEqual("abc", "abc") + def test_new_line_at_beginning(self): + self.assertEqual("\nabc", "\nabc") + def test_new_line_at_start_and_end(self): + self.assertEqual("\nabc\n", "\nabc\n") + def test_with_space_at_start_and_end(self): + self.assertEqual(" abc ", " abc ") + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2019-01-16-09-11-29.bpo-24780.69AB4h.rst b/Misc/NEWS.d/next/Library/2019-01-16-09-11-29.bpo-24780.69AB4h.rst new file mode 100644 index 00000000000000..4a796eb92caab6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-01-16-09-11-29.bpo-24780.69AB4h.rst @@ -0,0 +1 @@ +unittest assertEqual difference output now not foiled by newlines. \ No newline at end of file