test_textwrap.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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$
  9. #
  10. import unittest
  11. from textwrap import TextWrapper, wrap, fill, dedent, indent, shorten
  12. class BaseTestCase(unittest.TestCase):
  13. '''Parent class with utility methods for textwrap tests.'''
  14. def show(self, textin):
  15. if isinstance(textin, list):
  16. result = []
  17. for i in range(len(textin)):
  18. result.append(" %d: %r" % (i, textin[i]))
  19. result = "\n".join(result) if result else " no lines"
  20. elif isinstance(textin, str):
  21. result = " %s\n" % repr(textin)
  22. return result
  23. def check(self, result, expect):
  24. self.assertEqual(result, expect,
  25. 'expected:\n%s\nbut got:\n%s' % (
  26. self.show(expect), self.show(result)))
  27. def check_wrap(self, text, width, expect, **kwargs):
  28. result = wrap(text, width, **kwargs)
  29. self.check(result, expect)
  30. def check_split(self, text, expect):
  31. result = self.wrapper._split(text)
  32. self.assertEqual(result, expect,
  33. "\nexpected %r\n"
  34. "but got %r" % (expect, result))
  35. class WrapTestCase(BaseTestCase):
  36. def setUp(self):
  37. self.wrapper = TextWrapper(width=45)
  38. def test_simple(self):
  39. # Simple case: just words, spaces, and a bit of punctuation
  40. text = "Hello there, how are you this fine day? I'm glad to hear it!"
  41. self.check_wrap(text, 12,
  42. ["Hello there,",
  43. "how are you",
  44. "this fine",
  45. "day? I'm",
  46. "glad to hear",
  47. "it!"])
  48. self.check_wrap(text, 42,
  49. ["Hello there, how are you this fine day?",
  50. "I'm glad to hear it!"])
  51. self.check_wrap(text, 80, [text])
  52. def test_empty_string(self):
  53. # Check that wrapping the empty string returns an empty list.
  54. self.check_wrap("", 6, [])
  55. self.check_wrap("", 6, [], drop_whitespace=False)
  56. def test_empty_string_with_initial_indent(self):
  57. # Check that the empty string is not indented.
  58. self.check_wrap("", 6, [], initial_indent="++")
  59. self.check_wrap("", 6, [], initial_indent="++", drop_whitespace=False)
  60. def test_whitespace(self):
  61. # Whitespace munging and end-of-sentence detection
  62. text = """\
  63. This is a paragraph that already has
  64. line breaks. But some of its lines are much longer than the others,
  65. so it needs to be wrapped.
  66. Some lines are \ttabbed too.
  67. What a mess!
  68. """
  69. expect = ["This is a paragraph that already has line",
  70. "breaks. But some of its lines are much",
  71. "longer than the others, so it needs to be",
  72. "wrapped. Some lines are tabbed too. What a",
  73. "mess!"]
  74. wrapper = TextWrapper(45, fix_sentence_endings=True)
  75. result = wrapper.wrap(text)
  76. self.check(result, expect)
  77. result = wrapper.fill(text)
  78. self.check(result, '\n'.join(expect))
  79. text = "\tTest\tdefault\t\ttabsize."
  80. expect = [" Test default tabsize."]
  81. self.check_wrap(text, 80, expect)
  82. text = "\tTest\tcustom\t\ttabsize."
  83. expect = [" Test custom tabsize."]
  84. self.check_wrap(text, 80, expect, tabsize=4)
  85. def test_fix_sentence_endings(self):
  86. wrapper = TextWrapper(60, fix_sentence_endings=True)
  87. # SF #847346: ensure that fix_sentence_endings=True does the
  88. # right thing even on input short enough that it doesn't need to
  89. # be wrapped.
  90. text = "A short line. Note the single space."
  91. expect = ["A short line. Note the single space."]
  92. self.check(wrapper.wrap(text), expect)
  93. # Test some of the hairy end cases that _fix_sentence_endings()
  94. # is supposed to handle (the easy stuff is tested in
  95. # test_whitespace() above).
  96. text = "Well, Doctor? What do you think?"
  97. expect = ["Well, Doctor? What do you think?"]
  98. self.check(wrapper.wrap(text), expect)
  99. text = "Well, Doctor?\nWhat do you think?"
  100. self.check(wrapper.wrap(text), expect)
  101. text = 'I say, chaps! Anyone for "tennis?"\nHmmph!'
  102. expect = ['I say, chaps! Anyone for "tennis?" Hmmph!']
  103. self.check(wrapper.wrap(text), expect)
  104. wrapper.width = 20
  105. expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!']
  106. self.check(wrapper.wrap(text), expect)
  107. text = 'And she said, "Go to hell!"\nCan you believe that?'
  108. expect = ['And she said, "Go to',
  109. 'hell!" Can you',
  110. 'believe that?']
  111. self.check(wrapper.wrap(text), expect)
  112. wrapper.width = 60
  113. expect = ['And she said, "Go to hell!" Can you believe that?']
  114. self.check(wrapper.wrap(text), expect)
  115. text = 'File stdio.h is nice.'
  116. expect = ['File stdio.h is nice.']
  117. self.check(wrapper.wrap(text), expect)
  118. def test_wrap_short(self):
  119. # Wrapping to make short lines longer
  120. text = "This is a\nshort paragraph."
  121. self.check_wrap(text, 20, ["This is a short",
  122. "paragraph."])
  123. self.check_wrap(text, 40, ["This is a short paragraph."])
  124. def test_wrap_short_1line(self):
  125. # Test endcases
  126. text = "This is a short line."
  127. self.check_wrap(text, 30, ["This is a short line."])
  128. self.check_wrap(text, 30, ["(1) This is a short line."],
  129. initial_indent="(1) ")
  130. def test_hyphenated(self):
  131. # Test breaking hyphenated words
  132. text = ("this-is-a-useful-feature-for-"
  133. "reformatting-posts-from-tim-peters'ly")
  134. self.check_wrap(text, 40,
  135. ["this-is-a-useful-feature-for-",
  136. "reformatting-posts-from-tim-peters'ly"])
  137. self.check_wrap(text, 41,
  138. ["this-is-a-useful-feature-for-",
  139. "reformatting-posts-from-tim-peters'ly"])
  140. self.check_wrap(text, 42,
  141. ["this-is-a-useful-feature-for-reformatting-",
  142. "posts-from-tim-peters'ly"])
  143. # The test tests current behavior but is not testing parts of the API.
  144. expect = ("this-|is-|a-|useful-|feature-|for-|"
  145. "reformatting-|posts-|from-|tim-|peters'ly").split('|')
  146. self.check_wrap(text, 1, expect, break_long_words=False)
  147. self.check_split(text, expect)
  148. self.check_split('e-mail', ['e-mail'])
  149. self.check_split('Jelly-O', ['Jelly-O'])
  150. # The test tests current behavior but is not testing parts of the API.
  151. self.check_split('half-a-crown', 'half-|a-|crown'.split('|'))
  152. def test_hyphenated_numbers(self):
  153. # Test that hyphenated numbers (eg. dates) are not broken like words.
  154. text = ("Python 1.0.0 was released on 1994-01-26. Python 1.0.1 was\n"
  155. "released on 1994-02-15.")
  156. self.check_wrap(text, 30, ['Python 1.0.0 was released on',
  157. '1994-01-26. Python 1.0.1 was',
  158. 'released on 1994-02-15.'])
  159. self.check_wrap(text, 40, ['Python 1.0.0 was released on 1994-01-26.',
  160. 'Python 1.0.1 was released on 1994-02-15.'])
  161. self.check_wrap(text, 1, text.split(), break_long_words=False)
  162. text = "I do all my shopping at 7-11."
  163. self.check_wrap(text, 25, ["I do all my shopping at",
  164. "7-11."])
  165. self.check_wrap(text, 27, ["I do all my shopping at",
  166. "7-11."])
  167. self.check_wrap(text, 29, ["I do all my shopping at 7-11."])
  168. self.check_wrap(text, 1, text.split(), break_long_words=False)
  169. def test_em_dash(self):
  170. # Test text with em-dashes
  171. text = "Em-dashes should be written -- thus."
  172. self.check_wrap(text, 25,
  173. ["Em-dashes should be",
  174. "written -- thus."])
  175. # Probe the boundaries of the properly written em-dash,
  176. # ie. " -- ".
  177. self.check_wrap(text, 29,
  178. ["Em-dashes should be written",
  179. "-- thus."])
  180. expect = ["Em-dashes should be written --",
  181. "thus."]
  182. self.check_wrap(text, 30, expect)
  183. self.check_wrap(text, 35, expect)
  184. self.check_wrap(text, 36,
  185. ["Em-dashes should be written -- thus."])
  186. # The improperly written em-dash is handled too, because
  187. # it's adjacent to non-whitespace on both sides.
  188. text = "You can also do--this or even---this."
  189. expect = ["You can also do",
  190. "--this or even",
  191. "---this."]
  192. self.check_wrap(text, 15, expect)
  193. self.check_wrap(text, 16, expect)
  194. expect = ["You can also do--",
  195. "this or even---",
  196. "this."]
  197. self.check_wrap(text, 17, expect)
  198. self.check_wrap(text, 19, expect)
  199. expect = ["You can also do--this or even",
  200. "---this."]
  201. self.check_wrap(text, 29, expect)
  202. self.check_wrap(text, 31, expect)
  203. expect = ["You can also do--this or even---",
  204. "this."]
  205. self.check_wrap(text, 32, expect)
  206. self.check_wrap(text, 35, expect)
  207. # All of the above behaviour could be deduced by probing the
  208. # _split() method.
  209. text = "Here's an -- em-dash and--here's another---and another!"
  210. expect = ["Here's", " ", "an", " ", "--", " ", "em-", "dash", " ",
  211. "and", "--", "here's", " ", "another", "---",
  212. "and", " ", "another!"]
  213. self.check_split(text, expect)
  214. text = "and then--bam!--he was gone"
  215. expect = ["and", " ", "then", "--", "bam!", "--",
  216. "he", " ", "was", " ", "gone"]
  217. self.check_split(text, expect)
  218. def test_unix_options (self):
  219. # Test that Unix-style command-line options are wrapped correctly.
  220. # Both Optik (OptionParser) and Docutils rely on this behaviour!
  221. text = "You should use the -n option, or --dry-run in its long form."
  222. self.check_wrap(text, 20,
  223. ["You should use the",
  224. "-n option, or --dry-",
  225. "run in its long",
  226. "form."])
  227. self.check_wrap(text, 21,
  228. ["You should use the -n",
  229. "option, or --dry-run",
  230. "in its long form."])
  231. expect = ["You should use the -n option, or",
  232. "--dry-run in its long form."]
  233. self.check_wrap(text, 32, expect)
  234. self.check_wrap(text, 34, expect)
  235. self.check_wrap(text, 35, expect)
  236. self.check_wrap(text, 38, expect)
  237. expect = ["You should use the -n option, or --dry-",
  238. "run in its long form."]
  239. self.check_wrap(text, 39, expect)
  240. self.check_wrap(text, 41, expect)
  241. expect = ["You should use the -n option, or --dry-run",
  242. "in its long form."]
  243. self.check_wrap(text, 42, expect)
  244. # Again, all of the above can be deduced from _split().
  245. text = "the -n option, or --dry-run or --dryrun"
  246. expect = ["the", " ", "-n", " ", "option,", " ", "or", " ",
  247. "--dry-", "run", " ", "or", " ", "--dryrun"]
  248. self.check_split(text, expect)
  249. def test_funky_hyphens (self):
  250. # Screwy edge cases cooked up by David Goodger. All reported
  251. # in SF bug #596434.
  252. self.check_split("what the--hey!", ["what", " ", "the", "--", "hey!"])
  253. self.check_split("what the--", ["what", " ", "the--"])
  254. self.check_split("what the--.", ["what", " ", "the--."])
  255. self.check_split("--text--.", ["--text--."])
  256. # When I first read bug #596434, this is what I thought David
  257. # was talking about. I was wrong; these have always worked
  258. # fine. The real problem is tested in test_funky_parens()
  259. # below...
  260. self.check_split("--option", ["--option"])
  261. self.check_split("--option-opt", ["--option-", "opt"])
  262. self.check_split("foo --option-opt bar",
  263. ["foo", " ", "--option-", "opt", " ", "bar"])
  264. def test_punct_hyphens(self):
  265. # Oh bother, SF #965425 found another problem with hyphens --
  266. # hyphenated words in single quotes weren't handled correctly.
  267. # In fact, the bug is that *any* punctuation around a hyphenated
  268. # word was handled incorrectly, except for a leading "--", which
  269. # was special-cased for Optik and Docutils. So test a variety
  270. # of styles of punctuation around a hyphenated word.
  271. # (Actually this is based on an Optik bug report, #813077).
  272. self.check_split("the 'wibble-wobble' widget",
  273. ['the', ' ', "'wibble-", "wobble'", ' ', 'widget'])
  274. self.check_split('the "wibble-wobble" widget',
  275. ['the', ' ', '"wibble-', 'wobble"', ' ', 'widget'])
  276. self.check_split("the (wibble-wobble) widget",
  277. ['the', ' ', "(wibble-", "wobble)", ' ', 'widget'])
  278. self.check_split("the ['wibble-wobble'] widget",
  279. ['the', ' ', "['wibble-", "wobble']", ' ', 'widget'])
  280. # The test tests current behavior but is not testing parts of the API.
  281. self.check_split("what-d'you-call-it.",
  282. "what-d'you-|call-|it.".split('|'))
  283. def test_funky_parens (self):
  284. # Second part of SF bug #596434: long option strings inside
  285. # parentheses.
  286. self.check_split("foo (--option) bar",
  287. ["foo", " ", "(--option)", " ", "bar"])
  288. # Related stuff -- make sure parens work in simpler contexts.
  289. self.check_split("foo (bar) baz",
  290. ["foo", " ", "(bar)", " ", "baz"])
  291. self.check_split("blah (ding dong), wubba",
  292. ["blah", " ", "(ding", " ", "dong),",
  293. " ", "wubba"])
  294. def test_drop_whitespace_false(self):
  295. # Check that drop_whitespace=False preserves whitespace.
  296. # SF patch #1581073
  297. text = " This is a sentence with much whitespace."
  298. self.check_wrap(text, 10,
  299. [" This is a", " ", "sentence ",
  300. "with ", "much white", "space."],
  301. drop_whitespace=False)
  302. def test_drop_whitespace_false_whitespace_only(self):
  303. # Check that drop_whitespace=False preserves a whitespace-only string.
  304. self.check_wrap(" ", 6, [" "], drop_whitespace=False)
  305. def test_drop_whitespace_false_whitespace_only_with_indent(self):
  306. # Check that a whitespace-only string gets indented (when
  307. # drop_whitespace is False).
  308. self.check_wrap(" ", 6, [" "], drop_whitespace=False,
  309. initial_indent=" ")
  310. def test_drop_whitespace_whitespace_only(self):
  311. # Check drop_whitespace on a whitespace-only string.
  312. self.check_wrap(" ", 6, [])
  313. def test_drop_whitespace_leading_whitespace(self):
  314. # Check that drop_whitespace does not drop leading whitespace (if
  315. # followed by non-whitespace).
  316. # SF bug #622849 reported inconsistent handling of leading
  317. # whitespace; let's test that a bit, shall we?
  318. text = " This is a sentence with leading whitespace."
  319. self.check_wrap(text, 50,
  320. [" This is a sentence with leading whitespace."])
  321. self.check_wrap(text, 30,
  322. [" This is a sentence with", "leading whitespace."])
  323. def test_drop_whitespace_whitespace_line(self):
  324. # Check that drop_whitespace skips the whole line if a non-leading
  325. # line consists only of whitespace.
  326. text = "abcd efgh"
  327. # Include the result for drop_whitespace=False for comparison.
  328. self.check_wrap(text, 6, ["abcd", " ", "efgh"],
  329. drop_whitespace=False)
  330. self.check_wrap(text, 6, ["abcd", "efgh"])
  331. def test_drop_whitespace_whitespace_only_with_indent(self):
  332. # Check that initial_indent is not applied to a whitespace-only
  333. # string. This checks a special case of the fact that dropping
  334. # whitespace occurs before indenting.
  335. self.check_wrap(" ", 6, [], initial_indent="++")
  336. def test_drop_whitespace_whitespace_indent(self):
  337. # Check that drop_whitespace does not drop whitespace indents.
  338. # This checks a special case of the fact that dropping whitespace
  339. # occurs before indenting.
  340. self.check_wrap("abcd efgh", 6, [" abcd", " efgh"],
  341. initial_indent=" ", subsequent_indent=" ")
  342. def test_split(self):
  343. # Ensure that the standard _split() method works as advertised
  344. # in the comments
  345. text = "Hello there -- you goof-ball, use the -b option!"
  346. result = self.wrapper._split(text)
  347. self.check(result,
  348. ["Hello", " ", "there", " ", "--", " ", "you", " ", "goof-",
  349. "ball,", " ", "use", " ", "the", " ", "-b", " ", "option!"])
  350. def test_break_on_hyphens(self):
  351. # Ensure that the break_on_hyphens attributes work
  352. text = "yaba daba-doo"
  353. self.check_wrap(text, 10, ["yaba daba-", "doo"],
  354. break_on_hyphens=True)
  355. self.check_wrap(text, 10, ["yaba", "daba-doo"],
  356. break_on_hyphens=False)
  357. def test_bad_width(self):
  358. # Ensure that width <= 0 is caught.
  359. text = "Whatever, it doesn't matter."
  360. self.assertRaises(ValueError, wrap, text, 0)
  361. self.assertRaises(ValueError, wrap, text, -1)
  362. def test_no_split_at_umlaut(self):
  363. text = "Die Empf\xe4nger-Auswahl"
  364. self.check_wrap(text, 13, ["Die", "Empf\xe4nger-", "Auswahl"])
  365. def test_umlaut_followed_by_dash(self):
  366. text = "aa \xe4\xe4-\xe4\xe4"
  367. self.check_wrap(text, 7, ["aa \xe4\xe4-", "\xe4\xe4"])
  368. def test_non_breaking_space(self):
  369. text = 'This is a sentence with non-breaking\N{NO-BREAK SPACE}space.'
  370. self.check_wrap(text, 20,
  371. ['This is a sentence',
  372. 'with non-',
  373. 'breaking\N{NO-BREAK SPACE}space.'],
  374. break_on_hyphens=True)
  375. self.check_wrap(text, 20,
  376. ['This is a sentence',
  377. 'with',
  378. 'non-breaking\N{NO-BREAK SPACE}space.'],
  379. break_on_hyphens=False)
  380. def test_narrow_non_breaking_space(self):
  381. text = ('This is a sentence with non-breaking'
  382. '\N{NARROW NO-BREAK SPACE}space.')
  383. self.check_wrap(text, 20,
  384. ['This is a sentence',
  385. 'with non-',
  386. 'breaking\N{NARROW NO-BREAK SPACE}space.'],
  387. break_on_hyphens=True)
  388. self.check_wrap(text, 20,
  389. ['This is a sentence',
  390. 'with',
  391. 'non-breaking\N{NARROW NO-BREAK SPACE}space.'],
  392. break_on_hyphens=False)
  393. class MaxLinesTestCase(BaseTestCase):
  394. text = "Hello there, how are you this fine day? I'm glad to hear it!"
  395. def test_simple(self):
  396. self.check_wrap(self.text, 12,
  397. ["Hello [...]"],
  398. max_lines=0)
  399. self.check_wrap(self.text, 12,
  400. ["Hello [...]"],
  401. max_lines=1)
  402. self.check_wrap(self.text, 12,
  403. ["Hello there,",
  404. "how [...]"],
  405. max_lines=2)
  406. self.check_wrap(self.text, 13,
  407. ["Hello there,",
  408. "how are [...]"],
  409. max_lines=2)
  410. self.check_wrap(self.text, 80, [self.text], max_lines=1)
  411. self.check_wrap(self.text, 12,
  412. ["Hello there,",
  413. "how are you",
  414. "this fine",
  415. "day? I'm",
  416. "glad to hear",
  417. "it!"],
  418. max_lines=6)
  419. def test_spaces(self):
  420. # strip spaces before placeholder
  421. self.check_wrap(self.text, 12,
  422. ["Hello there,",
  423. "how are you",
  424. "this fine",
  425. "day? [...]"],
  426. max_lines=4)
  427. # placeholder at the start of line
  428. self.check_wrap(self.text, 6,
  429. ["Hello",
  430. "[...]"],
  431. max_lines=2)
  432. # final spaces
  433. self.check_wrap(self.text + ' ' * 10, 12,
  434. ["Hello there,",
  435. "how are you",
  436. "this fine",
  437. "day? I'm",
  438. "glad to hear",
  439. "it!"],
  440. max_lines=6)
  441. def test_placeholder(self):
  442. self.check_wrap(self.text, 12,
  443. ["Hello..."],
  444. max_lines=1,
  445. placeholder='...')
  446. self.check_wrap(self.text, 12,
  447. ["Hello there,",
  448. "how are..."],
  449. max_lines=2,
  450. placeholder='...')
  451. # long placeholder and indentation
  452. with self.assertRaises(ValueError):
  453. wrap(self.text, 16, initial_indent=' ',
  454. max_lines=1, placeholder=' [truncated]...')
  455. with self.assertRaises(ValueError):
  456. wrap(self.text, 16, subsequent_indent=' ',
  457. max_lines=2, placeholder=' [truncated]...')
  458. self.check_wrap(self.text, 16,
  459. [" Hello there,",
  460. " [truncated]..."],
  461. max_lines=2,
  462. initial_indent=' ',
  463. subsequent_indent=' ',
  464. placeholder=' [truncated]...')
  465. self.check_wrap(self.text, 16,
  466. [" [truncated]..."],
  467. max_lines=1,
  468. initial_indent=' ',
  469. subsequent_indent=' ',
  470. placeholder=' [truncated]...')
  471. self.check_wrap(self.text, 80, [self.text], placeholder='.' * 1000)
  472. def test_placeholder_backtrack(self):
  473. # Test special case when max_lines insufficient, but what
  474. # would be last wrapped line so long the placeholder cannot
  475. # be added there without violence. So, textwrap backtracks,
  476. # adding placeholder to the penultimate line.
  477. text = 'Good grief Python features are advancing quickly!'
  478. self.check_wrap(text, 12,
  479. ['Good grief', 'Python*****'],
  480. max_lines=3,
  481. placeholder='*****')
  482. class LongWordTestCase (BaseTestCase):
  483. def setUp(self):
  484. self.wrapper = TextWrapper()
  485. self.text = '''\
  486. Did you say "supercalifragilisticexpialidocious?"
  487. How *do* you spell that odd word, anyways?
  488. '''
  489. def test_break_long(self):
  490. # Wrap text with long words and lots of punctuation
  491. self.check_wrap(self.text, 30,
  492. ['Did you say "supercalifragilis',
  493. 'ticexpialidocious?" How *do*',
  494. 'you spell that odd word,',
  495. 'anyways?'])
  496. self.check_wrap(self.text, 50,
  497. ['Did you say "supercalifragilisticexpialidocious?"',
  498. 'How *do* you spell that odd word, anyways?'])
  499. # SF bug 797650. Prevent an infinite loop by making sure that at
  500. # least one character gets split off on every pass.
  501. self.check_wrap('-'*10+'hello', 10,
  502. ['----------',
  503. ' h',
  504. ' e',
  505. ' l',
  506. ' l',
  507. ' o'],
  508. subsequent_indent = ' '*15)
  509. # bug 1146. Prevent a long word to be wrongly wrapped when the
  510. # preceding word is exactly one character shorter than the width
  511. self.check_wrap(self.text, 12,
  512. ['Did you say ',
  513. '"supercalifr',
  514. 'agilisticexp',
  515. 'ialidocious?',
  516. '" How *do*',
  517. 'you spell',
  518. 'that odd',
  519. 'word,',
  520. 'anyways?'])
  521. def test_nobreak_long(self):
  522. # Test with break_long_words disabled
  523. self.wrapper.break_long_words = 0
  524. self.wrapper.width = 30
  525. expect = ['Did you say',
  526. '"supercalifragilisticexpialidocious?"',
  527. 'How *do* you spell that odd',
  528. 'word, anyways?'
  529. ]
  530. result = self.wrapper.wrap(self.text)
  531. self.check(result, expect)
  532. # Same thing with kwargs passed to standalone wrap() function.
  533. result = wrap(self.text, width=30, break_long_words=0)
  534. self.check(result, expect)
  535. def test_max_lines_long(self):
  536. self.check_wrap(self.text, 12,
  537. ['Did you say ',
  538. '"supercalifr',
  539. 'agilisticexp',
  540. '[...]'],
  541. max_lines=4)
  542. class LongWordWithHyphensTestCase(BaseTestCase):
  543. def setUp(self):
  544. self.wrapper = TextWrapper()
  545. self.text1 = '''\
  546. We used enyzme 2-succinyl-6-hydroxy-2,4-cyclohexadiene-1-carboxylate synthase.
  547. '''
  548. self.text2 = '''\
  549. 1234567890-1234567890--this_is_a_very_long_option_indeed-good-bye"
  550. '''
  551. def test_break_long_words_on_hyphen(self):
  552. expected = ['We used enyzme 2-succinyl-6-hydroxy-2,4-',
  553. 'cyclohexadiene-1-carboxylate synthase.']
  554. self.check_wrap(self.text1, 50, expected)
  555. expected = ['We used', 'enyzme 2-', 'succinyl-', '6-hydroxy-', '2,4-',
  556. 'cyclohexad', 'iene-1-', 'carboxylat', 'e', 'synthase.']
  557. self.check_wrap(self.text1, 10, expected)
  558. expected = ['1234567890', '-123456789', '0--this_is', '_a_very_lo',
  559. 'ng_option_', 'indeed-', 'good-bye"']
  560. self.check_wrap(self.text2, 10, expected)
  561. def test_break_long_words_not_on_hyphen(self):
  562. expected = ['We used enyzme 2-succinyl-6-hydroxy-2,4-cyclohexad',
  563. 'iene-1-carboxylate synthase.']
  564. self.check_wrap(self.text1, 50, expected, break_on_hyphens=False)
  565. expected = ['We used', 'enyzme 2-s', 'uccinyl-6-', 'hydroxy-2,',
  566. '4-cyclohex', 'adiene-1-c', 'arboxylate', 'synthase.']
  567. self.check_wrap(self.text1, 10, expected, break_on_hyphens=False)
  568. expected = ['1234567890', '-123456789', '0--this_is', '_a_very_lo',
  569. 'ng_option_', 'indeed-', 'good-bye"']
  570. self.check_wrap(self.text2, 10, expected)
  571. def test_break_on_hyphen_but_not_long_words(self):
  572. expected = ['We used enyzme',
  573. '2-succinyl-6-hydroxy-2,4-cyclohexadiene-1-carboxylate',
  574. 'synthase.']
  575. self.check_wrap(self.text1, 50, expected, break_long_words=False)
  576. expected = ['We used', 'enyzme',
  577. '2-succinyl-6-hydroxy-2,4-cyclohexadiene-1-carboxylate',
  578. 'synthase.']
  579. self.check_wrap(self.text1, 10, expected, break_long_words=False)
  580. expected = ['1234567890', '-123456789', '0--this_is', '_a_very_lo',
  581. 'ng_option_', 'indeed-', 'good-bye"']
  582. self.check_wrap(self.text2, 10, expected)
  583. def test_do_not_break_long_words_or_on_hyphens(self):
  584. expected = ['We used enyzme',
  585. '2-succinyl-6-hydroxy-2,4-cyclohexadiene-1-carboxylate',
  586. 'synthase.']
  587. self.check_wrap(self.text1, 50, expected,
  588. break_long_words=False,
  589. break_on_hyphens=False)
  590. expected = ['We used', 'enyzme',
  591. '2-succinyl-6-hydroxy-2,4-cyclohexadiene-1-carboxylate',
  592. 'synthase.']
  593. self.check_wrap(self.text1, 10, expected,
  594. break_long_words=False,
  595. break_on_hyphens=False)
  596. expected = ['1234567890', '-123456789', '0--this_is', '_a_very_lo',
  597. 'ng_option_', 'indeed-', 'good-bye"']
  598. self.check_wrap(self.text2, 10, expected)
  599. class IndentTestCases(BaseTestCase):
  600. # called before each test method
  601. def setUp(self):
  602. self.text = '''\
  603. This paragraph will be filled, first without any indentation,
  604. and then with some (including a hanging indent).'''
  605. def test_fill(self):
  606. # Test the fill() method
  607. expect = '''\
  608. This paragraph will be filled, first
  609. without any indentation, and then with
  610. some (including a hanging indent).'''
  611. result = fill(self.text, 40)
  612. self.check(result, expect)
  613. def test_initial_indent(self):
  614. # Test initial_indent parameter
  615. expect = [" This paragraph will be filled,",
  616. "first without any indentation, and then",
  617. "with some (including a hanging indent)."]
  618. result = wrap(self.text, 40, initial_indent=" ")
  619. self.check(result, expect)
  620. expect = "\n".join(expect)
  621. result = fill(self.text, 40, initial_indent=" ")
  622. self.check(result, expect)
  623. def test_subsequent_indent(self):
  624. # Test subsequent_indent parameter
  625. expect = '''\
  626. * This paragraph will be filled, first
  627. without any indentation, and then
  628. with some (including a hanging
  629. indent).'''
  630. result = fill(self.text, 40,
  631. initial_indent=" * ", subsequent_indent=" ")
  632. self.check(result, expect)
  633. # Despite the similar names, DedentTestCase is *not* the inverse
  634. # of IndentTestCase!
  635. class DedentTestCase(unittest.TestCase):
  636. def assertUnchanged(self, text):
  637. """assert that dedent() has no effect on 'text'"""
  638. self.assertEqual(text, dedent(text))
  639. def test_dedent_nomargin(self):
  640. # No lines indented.
  641. text = "Hello there.\nHow are you?\nOh good, I'm glad."
  642. self.assertUnchanged(text)
  643. # Similar, with a blank line.
  644. text = "Hello there.\n\nBoo!"
  645. self.assertUnchanged(text)
  646. # Some lines indented, but overall margin is still zero.
  647. text = "Hello there.\n This is indented."
  648. self.assertUnchanged(text)
  649. # Again, add a blank line.
  650. text = "Hello there.\n\n Boo!\n"
  651. self.assertUnchanged(text)
  652. def test_dedent_even(self):
  653. # All lines indented by two spaces.
  654. text = " Hello there.\n How are ya?\n Oh good."
  655. expect = "Hello there.\nHow are ya?\nOh good."
  656. self.assertEqual(expect, dedent(text))
  657. # Same, with blank lines.
  658. text = " Hello there.\n\n How are ya?\n Oh good.\n"
  659. expect = "Hello there.\n\nHow are ya?\nOh good.\n"
  660. self.assertEqual(expect, dedent(text))
  661. # Now indent one of the blank lines.
  662. text = " Hello there.\n \n How are ya?\n Oh good.\n"
  663. expect = "Hello there.\n\nHow are ya?\nOh good.\n"
  664. self.assertEqual(expect, dedent(text))
  665. def test_dedent_uneven(self):
  666. # Lines indented unevenly.
  667. text = '''\
  668. def foo():
  669. while 1:
  670. return foo
  671. '''
  672. expect = '''\
  673. def foo():
  674. while 1:
  675. return foo
  676. '''
  677. self.assertEqual(expect, dedent(text))
  678. # Uneven indentation with a blank line.
  679. text = " Foo\n Bar\n\n Baz\n"
  680. expect = "Foo\n Bar\n\n Baz\n"
  681. self.assertEqual(expect, dedent(text))
  682. # Uneven indentation with a whitespace-only line.
  683. text = " Foo\n Bar\n \n Baz\n"
  684. expect = "Foo\n Bar\n\n Baz\n"
  685. self.assertEqual(expect, dedent(text))
  686. def test_dedent_declining(self):
  687. # Uneven indentation with declining indent level.
  688. text = " Foo\n Bar\n" # 5 spaces, then 4
  689. expect = " Foo\nBar\n"
  690. self.assertEqual(expect, dedent(text))
  691. # Declining indent level with blank line.
  692. text = " Foo\n\n Bar\n" # 5 spaces, blank, then 4
  693. expect = " Foo\n\nBar\n"
  694. self.assertEqual(expect, dedent(text))
  695. # Declining indent level with whitespace only line.
  696. text = " Foo\n \n Bar\n" # 5 spaces, then 4, then 4
  697. expect = " Foo\n\nBar\n"
  698. self.assertEqual(expect, dedent(text))
  699. # dedent() should not mangle internal tabs
  700. def test_dedent_preserve_internal_tabs(self):
  701. text = " hello\tthere\n how are\tyou?"
  702. expect = "hello\tthere\nhow are\tyou?"
  703. self.assertEqual(expect, dedent(text))
  704. # make sure that it preserves tabs when it's not making any
  705. # changes at all
  706. self.assertEqual(expect, dedent(expect))
  707. # dedent() should not mangle tabs in the margin (i.e.
  708. # tabs and spaces both count as margin, but are *not*
  709. # considered equivalent)
  710. def test_dedent_preserve_margin_tabs(self):
  711. text = " hello there\n\thow are you?"
  712. self.assertUnchanged(text)
  713. # same effect even if we have 8 spaces
  714. text = " hello there\n\thow are you?"
  715. self.assertUnchanged(text)
  716. # dedent() only removes whitespace that can be uniformly removed!
  717. text = "\thello there\n\thow are you?"
  718. expect = "hello there\nhow are you?"
  719. self.assertEqual(expect, dedent(text))
  720. text = " \thello there\n \thow are you?"
  721. self.assertEqual(expect, dedent(text))
  722. text = " \t hello there\n \t how are you?"
  723. self.assertEqual(expect, dedent(text))
  724. text = " \thello there\n \t how are you?"
  725. expect = "hello there\n how are you?"
  726. self.assertEqual(expect, dedent(text))
  727. # test margin is smaller than smallest indent
  728. text = " \thello there\n \thow are you?\n \tI'm fine, thanks"
  729. expect = " \thello there\n \thow are you?\n\tI'm fine, thanks"
  730. self.assertEqual(expect, dedent(text))
  731. # Test textwrap.indent
  732. class IndentTestCase(unittest.TestCase):
  733. # The examples used for tests. If any of these change, the expected
  734. # results in the various test cases must also be updated.
  735. # The roundtrip cases are separate, because textwrap.dedent doesn't
  736. # handle Windows line endings
  737. ROUNDTRIP_CASES = (
  738. # Basic test case
  739. "Hi.\nThis is a test.\nTesting.",
  740. # Include a blank line
  741. "Hi.\nThis is a test.\n\nTesting.",
  742. # Include leading and trailing blank lines
  743. "\nHi.\nThis is a test.\nTesting.\n",
  744. )
  745. CASES = ROUNDTRIP_CASES + (
  746. # Use Windows line endings
  747. "Hi.\r\nThis is a test.\r\nTesting.\r\n",
  748. # Pathological case
  749. "\nHi.\r\nThis is a test.\n\r\nTesting.\r\n\n",
  750. )
  751. def test_indent_nomargin_default(self):
  752. # indent should do nothing if 'prefix' is empty.
  753. for text in self.CASES:
  754. self.assertEqual(indent(text, ''), text)
  755. def test_indent_nomargin_explicit_default(self):
  756. # The same as test_indent_nomargin, but explicitly requesting
  757. # the default behaviour by passing None as the predicate
  758. for text in self.CASES:
  759. self.assertEqual(indent(text, '', None), text)
  760. def test_indent_nomargin_all_lines(self):
  761. # The same as test_indent_nomargin, but using the optional
  762. # predicate argument
  763. predicate = lambda line: True
  764. for text in self.CASES:
  765. self.assertEqual(indent(text, '', predicate), text)
  766. def test_indent_no_lines(self):
  767. # Explicitly skip indenting any lines
  768. predicate = lambda line: False
  769. for text in self.CASES:
  770. self.assertEqual(indent(text, ' ', predicate), text)
  771. def test_roundtrip_spaces(self):
  772. # A whitespace prefix should roundtrip with dedent
  773. for text in self.ROUNDTRIP_CASES:
  774. self.assertEqual(dedent(indent(text, ' ')), text)
  775. def test_roundtrip_tabs(self):
  776. # A whitespace prefix should roundtrip with dedent
  777. for text in self.ROUNDTRIP_CASES:
  778. self.assertEqual(dedent(indent(text, '\t\t')), text)
  779. def test_roundtrip_mixed(self):
  780. # A whitespace prefix should roundtrip with dedent
  781. for text in self.ROUNDTRIP_CASES:
  782. self.assertEqual(dedent(indent(text, ' \t \t ')), text)
  783. def test_indent_default(self):
  784. # Test default indenting of lines that are not whitespace only
  785. prefix = ' '
  786. expected = (
  787. # Basic test case
  788. " Hi.\n This is a test.\n Testing.",
  789. # Include a blank line
  790. " Hi.\n This is a test.\n\n Testing.",
  791. # Include leading and trailing blank lines
  792. "\n Hi.\n This is a test.\n Testing.\n",
  793. # Use Windows line endings
  794. " Hi.\r\n This is a test.\r\n Testing.\r\n",
  795. # Pathological case
  796. "\n Hi.\r\n This is a test.\n\r\n Testing.\r\n\n",
  797. )
  798. for text, expect in zip(self.CASES, expected):
  799. self.assertEqual(indent(text, prefix), expect)
  800. def test_indent_explicit_default(self):
  801. # Test default indenting of lines that are not whitespace only
  802. prefix = ' '
  803. expected = (
  804. # Basic test case
  805. " Hi.\n This is a test.\n Testing.",
  806. # Include a blank line
  807. " Hi.\n This is a test.\n\n Testing.",
  808. # Include leading and trailing blank lines
  809. "\n Hi.\n This is a test.\n Testing.\n",
  810. # Use Windows line endings
  811. " Hi.\r\n This is a test.\r\n Testing.\r\n",
  812. # Pathological case
  813. "\n Hi.\r\n This is a test.\n\r\n Testing.\r\n\n",
  814. )
  815. for text, expect in zip(self.CASES, expected):
  816. self.assertEqual(indent(text, prefix, None), expect)
  817. def test_indent_all_lines(self):
  818. # Add 'prefix' to all lines, including whitespace-only ones.
  819. prefix = ' '
  820. expected = (
  821. # Basic test case
  822. " Hi.\n This is a test.\n Testing.",
  823. # Include a blank line
  824. " Hi.\n This is a test.\n \n Testing.",
  825. # Include leading and trailing blank lines
  826. " \n Hi.\n This is a test.\n Testing.\n",
  827. # Use Windows line endings
  828. " Hi.\r\n This is a test.\r\n Testing.\r\n",
  829. # Pathological case
  830. " \n Hi.\r\n This is a test.\n \r\n Testing.\r\n \n",
  831. )
  832. predicate = lambda line: True
  833. for text, expect in zip(self.CASES, expected):
  834. self.assertEqual(indent(text, prefix, predicate), expect)
  835. def test_indent_empty_lines(self):
  836. # Add 'prefix' solely to whitespace-only lines.
  837. prefix = ' '
  838. expected = (
  839. # Basic test case
  840. "Hi.\nThis is a test.\nTesting.",
  841. # Include a blank line
  842. "Hi.\nThis is a test.\n \nTesting.",
  843. # Include leading and trailing blank lines
  844. " \nHi.\nThis is a test.\nTesting.\n",
  845. # Use Windows line endings
  846. "Hi.\r\nThis is a test.\r\nTesting.\r\n",
  847. # Pathological case
  848. " \nHi.\r\nThis is a test.\n \r\nTesting.\r\n \n",
  849. )
  850. predicate = lambda line: not line.strip()
  851. for text, expect in zip(self.CASES, expected):
  852. self.assertEqual(indent(text, prefix, predicate), expect)
  853. class ShortenTestCase(BaseTestCase):
  854. def check_shorten(self, text, width, expect, **kwargs):
  855. result = shorten(text, width, **kwargs)
  856. self.check(result, expect)
  857. def test_simple(self):
  858. # Simple case: just words, spaces, and a bit of punctuation
  859. text = "Hello there, how are you this fine day? I'm glad to hear it!"
  860. self.check_shorten(text, 18, "Hello there, [...]")
  861. self.check_shorten(text, len(text), text)
  862. self.check_shorten(text, len(text) - 1,
  863. "Hello there, how are you this fine day? "
  864. "I'm glad to [...]")
  865. def test_placeholder(self):
  866. text = "Hello there, how are you this fine day? I'm glad to hear it!"
  867. self.check_shorten(text, 17, "Hello there,$$", placeholder='$$')
  868. self.check_shorten(text, 18, "Hello there, how$$", placeholder='$$')
  869. self.check_shorten(text, 18, "Hello there, $$", placeholder=' $$')
  870. self.check_shorten(text, len(text), text, placeholder='$$')
  871. self.check_shorten(text, len(text) - 1,
  872. "Hello there, how are you this fine day? "
  873. "I'm glad to hear$$", placeholder='$$')
  874. def test_empty_string(self):
  875. self.check_shorten("", 6, "")
  876. def test_whitespace(self):
  877. # Whitespace collapsing
  878. text = """
  879. This is a paragraph that already has
  880. line breaks and \t tabs too."""
  881. self.check_shorten(text, 62,
  882. "This is a paragraph that already has line "
  883. "breaks and tabs too.")
  884. self.check_shorten(text, 61,
  885. "This is a paragraph that already has line "
  886. "breaks and [...]")
  887. self.check_shorten("hello world! ", 12, "hello world!")
  888. self.check_shorten("hello world! ", 11, "hello [...]")
  889. # The leading space is trimmed from the placeholder
  890. # (it would be ugly otherwise).
  891. self.check_shorten("hello world! ", 10, "[...]")
  892. def test_width_too_small_for_placeholder(self):
  893. shorten("x" * 20, width=8, placeholder="(......)")
  894. with self.assertRaises(ValueError):
  895. shorten("x" * 20, width=8, placeholder="(.......)")
  896. def test_first_word_too_long_but_placeholder_fits(self):
  897. self.check_shorten("Helloo", 5, "[...]")
  898. if __name__ == '__main__':
  899. unittest.main()