ยปCore Development>Code coverage>Lib/test/test_textwrap.py

Python code coverage for Lib/test/test_textwrap.py

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