/Lib/test/test_textwrap.py

http://unladen-swallow.googlecode.com/ · Python · 609 lines · 444 code · 94 blank · 71 comment · 5 complexity · 9fc216fd4d151ffa6b3428b21ab9e3de MD5 · raw file

  1. #
  2. # Test suite for the textwrap module.
  3. #
  4. # Original tests written by Greg Ward <gward@python.net>.
  5. # Converted to PyUnit by Peter Hansen <peter@engcorp.com>.
  6. # Currently maintained by Greg Ward.
  7. #
  8. # $Id: test_textwrap.py 67896 2008-12-21 17:01:26Z benjamin.peterson $
  9. #
  10. import unittest
  11. from test import test_support
  12. from textwrap import TextWrapper, wrap, fill, dedent
  13. class BaseTestCase(unittest.TestCase):
  14. '''Parent class with utility methods for textwrap tests.'''
  15. def show(self, textin):
  16. if isinstance(textin, list):
  17. result = []
  18. for i in range(len(textin)):
  19. result.append(" %d: %r" % (i, textin[i]))
  20. result = '\n'.join(result)
  21. elif isinstance(textin, basestring):
  22. result = " %s\n" % repr(textin)
  23. return result
  24. def check(self, result, expect):
  25. self.assertEquals(result, expect,
  26. 'expected:\n%s\nbut got:\n%s' % (
  27. self.show(expect), self.show(result)))
  28. def check_wrap(self, text, width, expect, **kwargs):
  29. result = wrap(text, width, **kwargs)
  30. self.check(result, expect)
  31. def check_split(self, text, expect):
  32. result = self.wrapper._split(text)
  33. self.assertEquals(result, expect,
  34. "\nexpected %r\n"
  35. "but got %r" % (expect, result))
  36. class WrapTestCase(BaseTestCase):
  37. def setUp(self):
  38. self.wrapper = TextWrapper(width=45)
  39. def test_simple(self):
  40. # Simple case: just words, spaces, and a bit of punctuation
  41. text = "Hello there, how are you this fine day? I'm glad to hear it!"
  42. self.check_wrap(text, 12,
  43. ["Hello there,",
  44. "how are you",
  45. "this fine",
  46. "day? I'm",
  47. "glad to hear",
  48. "it!"])
  49. self.check_wrap(text, 42,
  50. ["Hello there, how are you this fine day?",
  51. "I'm glad to hear it!"])
  52. self.check_wrap(text, 80, [text])
  53. def test_whitespace(self):
  54. # Whitespace munging and end-of-sentence detection
  55. text = """\
  56. This is a paragraph that already has
  57. line breaks. But some of its lines are much longer than the others,
  58. so it needs to be wrapped.
  59. Some lines are \ttabbed too.
  60. What a mess!
  61. """
  62. expect = ["This is a paragraph that already has line",
  63. "breaks. But some of its lines are much",
  64. "longer than the others, so it needs to be",
  65. "wrapped. Some lines are tabbed too. What a",
  66. "mess!"]
  67. wrapper = TextWrapper(45, fix_sentence_endings=True)
  68. result = wrapper.wrap(text)
  69. self.check(result, expect)
  70. result = wrapper.fill(text)
  71. self.check(result, '\n'.join(expect))
  72. def test_fix_sentence_endings(self):
  73. wrapper = TextWrapper(60, fix_sentence_endings=True)
  74. # SF #847346: ensure that fix_sentence_endings=True does the
  75. # right thing even on input short enough that it doesn't need to
  76. # be wrapped.
  77. text = "A short line. Note the single space."
  78. expect = ["A short line. Note the single space."]
  79. self.check(wrapper.wrap(text), expect)
  80. # Test some of the hairy end cases that _fix_sentence_endings()
  81. # is supposed to handle (the easy stuff is tested in
  82. # test_whitespace() above).
  83. text = "Well, Doctor? What do you think?"
  84. expect = ["Well, Doctor? What do you think?"]
  85. self.check(wrapper.wrap(text), expect)
  86. text = "Well, Doctor?\nWhat do you think?"
  87. self.check(wrapper.wrap(text), expect)
  88. text = 'I say, chaps! Anyone for "tennis?"\nHmmph!'
  89. expect = ['I say, chaps! Anyone for "tennis?" Hmmph!']
  90. self.check(wrapper.wrap(text), expect)
  91. wrapper.width = 20
  92. expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!']
  93. self.check(wrapper.wrap(text), expect)
  94. text = 'And she said, "Go to hell!"\nCan you believe that?'
  95. expect = ['And she said, "Go to',
  96. 'hell!" Can you',
  97. 'believe that?']
  98. self.check(wrapper.wrap(text), expect)
  99. wrapper.width = 60
  100. expect = ['And she said, "Go to hell!" Can you believe that?']
  101. self.check(wrapper.wrap(text), expect)
  102. text = 'File stdio.h is nice.'
  103. expect = ['File stdio.h is nice.']
  104. self.check(wrapper.wrap(text), expect)
  105. def test_wrap_short(self):
  106. # Wrapping to make short lines longer
  107. text = "This is a\nshort paragraph."
  108. self.check_wrap(text, 20, ["This is a short",
  109. "paragraph."])
  110. self.check_wrap(text, 40, ["This is a short paragraph."])
  111. def test_wrap_short_1line(self):
  112. # Test endcases
  113. text = "This is a short line."
  114. self.check_wrap(text, 30, ["This is a short line."])
  115. self.check_wrap(text, 30, ["(1) This is a short line."],
  116. initial_indent="(1) ")
  117. def test_hyphenated(self):
  118. # Test breaking hyphenated words
  119. text = ("this-is-a-useful-feature-for-"
  120. "reformatting-posts-from-tim-peters'ly")
  121. self.check_wrap(text, 40,
  122. ["this-is-a-useful-feature-for-",
  123. "reformatting-posts-from-tim-peters'ly"])
  124. self.check_wrap(text, 41,
  125. ["this-is-a-useful-feature-for-",
  126. "reformatting-posts-from-tim-peters'ly"])
  127. self.check_wrap(text, 42,
  128. ["this-is-a-useful-feature-for-reformatting-",
  129. "posts-from-tim-peters'ly"])
  130. def test_hyphenated_numbers(self):
  131. # Test that hyphenated numbers (eg. dates) are not broken like words.
  132. text = ("Python 1.0.0 was released on 1994-01-26. Python 1.0.1 was\n"
  133. "released on 1994-02-15.")
  134. self.check_wrap(text, 35, ['Python 1.0.0 was released on',
  135. '1994-01-26. Python 1.0.1 was',
  136. 'released on 1994-02-15.'])
  137. self.check_wrap(text, 40, ['Python 1.0.0 was released on 1994-01-26.',
  138. 'Python 1.0.1 was released on 1994-02-15.'])
  139. text = "I do all my shopping at 7-11."
  140. self.check_wrap(text, 25, ["I do all my shopping at",
  141. "7-11."])
  142. self.check_wrap(text, 27, ["I do all my shopping at",
  143. "7-11."])
  144. self.check_wrap(text, 29, ["I do all my shopping at 7-11."])
  145. def test_em_dash(self):
  146. # Test text with em-dashes
  147. text = "Em-dashes should be written -- thus."
  148. self.check_wrap(text, 25,
  149. ["Em-dashes should be",
  150. "written -- thus."])
  151. # Probe the boundaries of the properly written em-dash,
  152. # ie. " -- ".
  153. self.check_wrap(text, 29,
  154. ["Em-dashes should be written",
  155. "-- thus."])
  156. expect = ["Em-dashes should be written --",
  157. "thus."]
  158. self.check_wrap(text, 30, expect)
  159. self.check_wrap(text, 35, expect)
  160. self.check_wrap(text, 36,
  161. ["Em-dashes should be written -- thus."])
  162. # The improperly written em-dash is handled too, because
  163. # it's adjacent to non-whitespace on both sides.
  164. text = "You can also do--this or even---this."
  165. expect = ["You can also do",
  166. "--this or even",
  167. "---this."]
  168. self.check_wrap(text, 15, expect)
  169. self.check_wrap(text, 16, expect)
  170. expect = ["You can also do--",
  171. "this or even---",
  172. "this."]
  173. self.check_wrap(text, 17, expect)
  174. self.check_wrap(text, 19, expect)
  175. expect = ["You can also do--this or even",
  176. "---this."]
  177. self.check_wrap(text, 29, expect)
  178. self.check_wrap(text, 31, expect)
  179. expect = ["You can also do--this or even---",
  180. "this."]
  181. self.check_wrap(text, 32, expect)
  182. self.check_wrap(text, 35, expect)
  183. # All of the above behaviour could be deduced by probing the
  184. # _split() method.
  185. text = "Here's an -- em-dash and--here's another---and another!"
  186. expect = ["Here's", " ", "an", " ", "--", " ", "em-", "dash", " ",
  187. "and", "--", "here's", " ", "another", "---",
  188. "and", " ", "another!"]
  189. self.check_split(text, expect)
  190. text = "and then--bam!--he was gone"
  191. expect = ["and", " ", "then", "--", "bam!", "--",
  192. "he", " ", "was", " ", "gone"]
  193. self.check_split(text, expect)
  194. def test_unix_options (self):
  195. # Test that Unix-style command-line options are wrapped correctly.
  196. # Both Optik (OptionParser) and Docutils rely on this behaviour!
  197. text = "You should use the -n option, or --dry-run in its long form."
  198. self.check_wrap(text, 20,
  199. ["You should use the",
  200. "-n option, or --dry-",
  201. "run in its long",
  202. "form."])
  203. self.check_wrap(text, 21,
  204. ["You should use the -n",
  205. "option, or --dry-run",
  206. "in its long form."])
  207. expect = ["You should use the -n option, or",
  208. "--dry-run in its long form."]
  209. self.check_wrap(text, 32, expect)
  210. self.check_wrap(text, 34, expect)
  211. self.check_wrap(text, 35, expect)
  212. self.check_wrap(text, 38, expect)
  213. expect = ["You should use the -n option, or --dry-",
  214. "run in its long form."]
  215. self.check_wrap(text, 39, expect)
  216. self.check_wrap(text, 41, expect)
  217. expect = ["You should use the -n option, or --dry-run",
  218. "in its long form."]
  219. self.check_wrap(text, 42, expect)
  220. # Again, all of the above can be deduced from _split().
  221. text = "the -n option, or --dry-run or --dryrun"
  222. expect = ["the", " ", "-n", " ", "option,", " ", "or", " ",
  223. "--dry-", "run", " ", "or", " ", "--dryrun"]
  224. self.check_split(text, expect)
  225. def test_funky_hyphens (self):
  226. # Screwy edge cases cooked up by David Goodger. All reported
  227. # in SF bug #596434.
  228. self.check_split("what the--hey!", ["what", " ", "the", "--", "hey!"])
  229. self.check_split("what the--", ["what", " ", "the--"])
  230. self.check_split("what the--.", ["what", " ", "the--."])
  231. self.check_split("--text--.", ["--text--."])
  232. # When I first read bug #596434, this is what I thought David
  233. # was talking about. I was wrong; these have always worked
  234. # fine. The real problem is tested in test_funky_parens()
  235. # below...
  236. self.check_split("--option", ["--option"])
  237. self.check_split("--option-opt", ["--option-", "opt"])
  238. self.check_split("foo --option-opt bar",
  239. ["foo", " ", "--option-", "opt", " ", "bar"])
  240. def test_punct_hyphens(self):
  241. # Oh bother, SF #965425 found another problem with hyphens --
  242. # hyphenated words in single quotes weren't handled correctly.
  243. # In fact, the bug is that *any* punctuation around a hyphenated
  244. # word was handled incorrectly, except for a leading "--", which
  245. # was special-cased for Optik and Docutils. So test a variety
  246. # of styles of punctuation around a hyphenated word.
  247. # (Actually this is based on an Optik bug report, #813077).
  248. self.check_split("the 'wibble-wobble' widget",
  249. ['the', ' ', "'wibble-", "wobble'", ' ', 'widget'])
  250. self.check_split('the "wibble-wobble" widget',
  251. ['the', ' ', '"wibble-', 'wobble"', ' ', 'widget'])
  252. self.check_split("the (wibble-wobble) widget",
  253. ['the', ' ', "(wibble-", "wobble)", ' ', 'widget'])
  254. self.check_split("the ['wibble-wobble'] widget",
  255. ['the', ' ', "['wibble-", "wobble']", ' ', 'widget'])
  256. def test_funky_parens (self):
  257. # Second part of SF bug #596434: long option strings inside
  258. # parentheses.
  259. self.check_split("foo (--option) bar",
  260. ["foo", " ", "(--option)", " ", "bar"])
  261. # Related stuff -- make sure parens work in simpler contexts.
  262. self.check_split("foo (bar) baz",
  263. ["foo", " ", "(bar)", " ", "baz"])
  264. self.check_split("blah (ding dong), wubba",
  265. ["blah", " ", "(ding", " ", "dong),",
  266. " ", "wubba"])
  267. def test_initial_whitespace(self):
  268. # SF bug #622849 reported inconsistent handling of leading
  269. # whitespace; let's test that a bit, shall we?
  270. text = " This is a sentence with leading whitespace."
  271. self.check_wrap(text, 50,
  272. [" This is a sentence with leading whitespace."])
  273. self.check_wrap(text, 30,
  274. [" This is a sentence with", "leading whitespace."])
  275. def test_no_drop_whitespace(self):
  276. # SF patch #1581073
  277. text = " This is a sentence with much whitespace."
  278. self.check_wrap(text, 10,
  279. [" This is a", " ", "sentence ",
  280. "with ", "much white", "space."],
  281. drop_whitespace=False)
  282. if test_support.have_unicode:
  283. def test_unicode(self):
  284. # *Very* simple test of wrapping Unicode strings. I'm sure
  285. # there's more to it than this, but let's at least make
  286. # sure textwrap doesn't crash on Unicode input!
  287. text = u"Hello there, how are you today?"
  288. self.check_wrap(text, 50, [u"Hello there, how are you today?"])
  289. self.check_wrap(text, 20, [u"Hello there, how are", "you today?"])
  290. olines = self.wrapper.wrap(text)
  291. assert isinstance(olines, list) and isinstance(olines[0], unicode)
  292. otext = self.wrapper.fill(text)
  293. assert isinstance(otext, unicode)
  294. def test_no_split_at_umlaut(self):
  295. text = u"Die Empf\xe4nger-Auswahl"
  296. self.check_wrap(text, 13, [u"Die", u"Empf\xe4nger-", u"Auswahl"])
  297. def test_umlaut_followed_by_dash(self):
  298. text = u"aa \xe4\xe4-\xe4\xe4"
  299. self.check_wrap(text, 7, [u"aa \xe4\xe4-", u"\xe4\xe4"])
  300. def test_split(self):
  301. # Ensure that the standard _split() method works as advertised
  302. # in the comments
  303. text = "Hello there -- you goof-ball, use the -b option!"
  304. result = self.wrapper._split(text)
  305. self.check(result,
  306. ["Hello", " ", "there", " ", "--", " ", "you", " ", "goof-",
  307. "ball,", " ", "use", " ", "the", " ", "-b", " ", "option!"])
  308. def test_break_on_hyphens(self):
  309. # Ensure that the break_on_hyphens attributes work
  310. text = "yaba daba-doo"
  311. self.check_wrap(text, 10, ["yaba daba-", "doo"],
  312. break_on_hyphens=True)
  313. self.check_wrap(text, 10, ["yaba", "daba-doo"],
  314. break_on_hyphens=False)
  315. def test_bad_width(self):
  316. # Ensure that width <= 0 is caught.
  317. text = "Whatever, it doesn't matter."
  318. self.assertRaises(ValueError, wrap, text, 0)
  319. self.assertRaises(ValueError, wrap, text, -1)
  320. class LongWordTestCase (BaseTestCase):
  321. def setUp(self):
  322. self.wrapper = TextWrapper()
  323. self.text = '''\
  324. Did you say "supercalifragilisticexpialidocious?"
  325. How *do* you spell that odd word, anyways?
  326. '''
  327. def test_break_long(self):
  328. # Wrap text with long words and lots of punctuation
  329. self.check_wrap(self.text, 30,
  330. ['Did you say "supercalifragilis',
  331. 'ticexpialidocious?" How *do*',
  332. 'you spell that odd word,',
  333. 'anyways?'])
  334. self.check_wrap(self.text, 50,
  335. ['Did you say "supercalifragilisticexpialidocious?"',
  336. 'How *do* you spell that odd word, anyways?'])
  337. # SF bug 797650. Prevent an infinite loop by making sure that at
  338. # least one character gets split off on every pass.
  339. self.check_wrap('-'*10+'hello', 10,
  340. ['----------',
  341. ' h',
  342. ' e',
  343. ' l',
  344. ' l',
  345. ' o'],
  346. subsequent_indent = ' '*15)
  347. # bug 1146. Prevent a long word to be wrongly wrapped when the
  348. # preceding word is exactly one character shorter than the width
  349. self.check_wrap(self.text, 12,
  350. ['Did you say ',
  351. '"supercalifr',
  352. 'agilisticexp',
  353. 'ialidocious?',
  354. '" How *do*',
  355. 'you spell',
  356. 'that odd',
  357. 'word,',
  358. 'anyways?'])
  359. def test_nobreak_long(self):
  360. # Test with break_long_words disabled
  361. self.wrapper.break_long_words = 0
  362. self.wrapper.width = 30
  363. expect = ['Did you say',
  364. '"supercalifragilisticexpialidocious?"',
  365. 'How *do* you spell that odd',
  366. 'word, anyways?'
  367. ]
  368. result = self.wrapper.wrap(self.text)
  369. self.check(result, expect)
  370. # Same thing with kwargs passed to standalone wrap() function.
  371. result = wrap(self.text, width=30, break_long_words=0)
  372. self.check(result, expect)
  373. class IndentTestCases(BaseTestCase):
  374. # called before each test method
  375. def setUp(self):
  376. self.text = '''\
  377. This paragraph will be filled, first without any indentation,
  378. and then with some (including a hanging indent).'''
  379. def test_fill(self):
  380. # Test the fill() method
  381. expect = '''\
  382. This paragraph will be filled, first
  383. without any indentation, and then with
  384. some (including a hanging indent).'''
  385. result = fill(self.text, 40)
  386. self.check(result, expect)
  387. def test_initial_indent(self):
  388. # Test initial_indent parameter
  389. expect = [" This paragraph will be filled,",
  390. "first without any indentation, and then",
  391. "with some (including a hanging indent)."]
  392. result = wrap(self.text, 40, initial_indent=" ")
  393. self.check(result, expect)
  394. expect = "\n".join(expect)
  395. result = fill(self.text, 40, initial_indent=" ")
  396. self.check(result, expect)
  397. def test_subsequent_indent(self):
  398. # Test subsequent_indent parameter
  399. expect = '''\
  400. * This paragraph will be filled, first
  401. without any indentation, and then
  402. with some (including a hanging
  403. indent).'''
  404. result = fill(self.text, 40,
  405. initial_indent=" * ", subsequent_indent=" ")
  406. self.check(result, expect)
  407. # Despite the similar names, DedentTestCase is *not* the inverse
  408. # of IndentTestCase!
  409. class DedentTestCase(unittest.TestCase):
  410. def assertUnchanged(self, text):
  411. """assert that dedent() has no effect on 'text'"""
  412. self.assertEquals(text, dedent(text))
  413. def test_dedent_nomargin(self):
  414. # No lines indented.
  415. text = "Hello there.\nHow are you?\nOh good, I'm glad."
  416. self.assertUnchanged(text)
  417. # Similar, with a blank line.
  418. text = "Hello there.\n\nBoo!"
  419. self.assertUnchanged(text)
  420. # Some lines indented, but overall margin is still zero.
  421. text = "Hello there.\n This is indented."
  422. self.assertUnchanged(text)
  423. # Again, add a blank line.
  424. text = "Hello there.\n\n Boo!\n"
  425. self.assertUnchanged(text)
  426. def test_dedent_even(self):
  427. # All lines indented by two spaces.
  428. text = " Hello there.\n How are ya?\n Oh good."
  429. expect = "Hello there.\nHow are ya?\nOh good."
  430. self.assertEquals(expect, dedent(text))
  431. # Same, with blank lines.
  432. text = " Hello there.\n\n How are ya?\n Oh good.\n"
  433. expect = "Hello there.\n\nHow are ya?\nOh good.\n"
  434. self.assertEquals(expect, dedent(text))
  435. # Now indent one of the blank lines.
  436. text = " Hello there.\n \n How are ya?\n Oh good.\n"
  437. expect = "Hello there.\n\nHow are ya?\nOh good.\n"
  438. self.assertEquals(expect, dedent(text))
  439. def test_dedent_uneven(self):
  440. # Lines indented unevenly.
  441. text = '''\
  442. def foo():
  443. while 1:
  444. return foo
  445. '''
  446. expect = '''\
  447. def foo():
  448. while 1:
  449. return foo
  450. '''
  451. self.assertEquals(expect, dedent(text))
  452. # Uneven indentation with a blank line.
  453. text = " Foo\n Bar\n\n Baz\n"
  454. expect = "Foo\n Bar\n\n Baz\n"
  455. self.assertEquals(expect, dedent(text))
  456. # Uneven indentation with a whitespace-only line.
  457. text = " Foo\n Bar\n \n Baz\n"
  458. expect = "Foo\n Bar\n\n Baz\n"
  459. self.assertEquals(expect, dedent(text))
  460. # dedent() should not mangle internal tabs
  461. def test_dedent_preserve_internal_tabs(self):
  462. text = " hello\tthere\n how are\tyou?"
  463. expect = "hello\tthere\nhow are\tyou?"
  464. self.assertEquals(expect, dedent(text))
  465. # make sure that it preserves tabs when it's not making any
  466. # changes at all
  467. self.assertEquals(expect, dedent(expect))
  468. # dedent() should not mangle tabs in the margin (i.e.
  469. # tabs and spaces both count as margin, but are *not*
  470. # considered equivalent)
  471. def test_dedent_preserve_margin_tabs(self):
  472. text = " hello there\n\thow are you?"
  473. self.assertUnchanged(text)
  474. # same effect even if we have 8 spaces
  475. text = " hello there\n\thow are you?"
  476. self.assertUnchanged(text)
  477. # dedent() only removes whitespace that can be uniformly removed!
  478. text = "\thello there\n\thow are you?"
  479. expect = "hello there\nhow are you?"
  480. self.assertEquals(expect, dedent(text))
  481. text = " \thello there\n \thow are you?"
  482. self.assertEquals(expect, dedent(text))
  483. text = " \t hello there\n \t how are you?"
  484. self.assertEquals(expect, dedent(text))
  485. text = " \thello there\n \t how are you?"
  486. expect = "hello there\n how are you?"
  487. self.assertEquals(expect, dedent(text))
  488. def test_main():
  489. test_support.run_unittest(WrapTestCase,
  490. LongWordTestCase,
  491. IndentTestCases,
  492. DedentTestCase)
  493. if __name__ == '__main__':
  494. test_main()