diff --git a/Lib/test/test_textwrap.py b/Lib/test/test_textwrap.py --- a/Lib/test/test_textwrap.py +++ b/Lib/test/test_textwrap.py @@ -22,7 +22,7 @@ result = [] for i in range(len(textin)): result.append(" %d: %r" % (i, textin[i])) - result = '\n'.join(result) + result = '\n'.join(result) if result else ' --' elif isinstance(textin, str): result = " %s\n" % repr(textin) return result @@ -66,6 +66,8 @@ "I'm glad to hear it!"]) self.check_wrap(text, 80, [text]) + def test_empty_string(self): + self.check_wrap('', 10, ['']) def test_whitespace(self): # Whitespace munging and end-of-sentence detection @@ -99,6 +101,11 @@ expect = [" Test custom tabsize."] self.check_wrap(text, 80, expect, tabsize=4) + def test_whitespace_trailing(self): + # Verify that whitespace left over at the end does not append an + # empty string to the end of the returned list. + self.check_wrap('foo ', 3, ['foo']) + def test_fix_sentence_endings(self): wrapper = TextWrapper(60, fix_sentence_endings=True) @@ -340,6 +347,12 @@ self.check_wrap(text, 30, [" This is a sentence with", "leading whitespace."]) + def test_drop_whitespace__all_whitespace(self): + # Check that drop_whitespace with all-whitespace input does not + # return an empty list. + self.check_wrap(' ', 10, [' '], drop_whitespace=False) + self.check_wrap(' ', 10, [''], drop_whitespace=True) + def test_no_drop_whitespace(self): # SF patch #1581073 text = " This is a sentence with much whitespace." @@ -477,6 +490,9 @@ result = fill(self.text, 40, initial_indent=" ") self.check(result, expect) + def test_initial_indent__empty_string(self): + # Check that initial_indent does not indent the empty string. + self.check_wrap('', 10, [''], initial_indent='-->') def test_subsequent_indent(self): # Test subsequent_indent parameter @@ -491,6 +507,17 @@ initial_indent=" * ", subsequent_indent=" ") self.check(result, expect) + def test_subsequent_indent__trailing_whitespace(self): + # Check that subsequent_indent with trailing whitespace in the + # input does not append an indented empty string to the end of + # the returned list. + self.check_wrap('hello ', 5, ['hello'], subsequent_indent='-->') + + def test_subsequent_indent__long_indent(self): + # Check that subsequent_indent with a long indent string does not + # append an indented empty string to the end of the returned list. + self.check_wrap('foo', 2, ['fo', '-->o'], subsequent_indent='-->') + # Despite the similar names, DedentTestCase is *not* the inverse # of IndentTestCase! diff --git a/Lib/textwrap.py b/Lib/textwrap.py --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -293,7 +293,8 @@ chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) - return self._wrap_chunks(chunks) + # wrap() should never return an empty list. See issue #15510. + return self._wrap_chunks(chunks) or [''] def fill(self, text): """fill(text : string) -> string