1package util
2
3import (
4 "strings"
5 "testing"
6)
7
8func TestTextWrap(t *testing.T) {
9 cases := []struct {
10 Input, Output string
11 Lim int
12 }{
13 // A simple word passes through.
14 {
15 "foo",
16 "foo",
17 4,
18 },
19 // Word breaking
20 {
21 "foobarbaz",
22 "foob\narba\nz",
23 4,
24 },
25 // Lines are broken at whitespace.
26 {
27 "foo bar baz",
28 "foo\nbar\nbaz",
29 4,
30 },
31 // Word breaking
32 {
33 "foo bars bazzes",
34 "foo\nbars\nbazz\nes",
35 4,
36 },
37 // A word that would run beyond the width is wrapped.
38 {
39 "fo sop",
40 "fo\nsop",
41 4,
42 },
43 // A tab counts as 4 characters.
44 {
45 "foo\nb\t r\n baz",
46 "foo\nb\n r\n baz",
47 4,
48 },
49 // Trailing whitespace is removed after used for wrapping.
50 // Runs of whitespace on which a line is broken are removed.
51 {
52 "foo \nb ar ",
53 "foo\n\nb\nar\n",
54 4,
55 },
56 // An explicit line break at the end of the input is preserved.
57 {
58 "foo bar baz\n",
59 "foo\nbar\nbaz\n",
60 4,
61 },
62 // Explicit break are always preserved.
63 {
64 "\nfoo bar\n\n\nbaz\n",
65 "\nfoo\nbar\n\n\nbaz\n",
66 4,
67 },
68 // Ignore complete words with terminal color sequence
69 {
70 "foo \x1b[31mbar\x1b[0m baz",
71 "foo\n\x1b[31mbar\x1b[0m\nbaz",
72 4,
73 },
74 // Complete example:
75 {
76 " This is a list: \n\n\t* foo\n\t* bar\n\n\n\t* baz \nBAM ",
77 " This\nis a\nlist:\n\n *\nfoo\n *\nbar\n\n\n *\nbaz\nBAM\n",
78 6,
79 },
80 }
81
82 for i, tc := range cases {
83 actual, lines := TextWrap(tc.Input, tc.Lim)
84 if actual != tc.Output {
85 t.Fatalf("Case %d Input:\n\n`%s`\n\nExpected Output:\n\n`%s`\n\nActual Output:\n\n`%s`",
86 i, tc.Input, tc.Output, actual)
87 }
88
89 expected := len(strings.Split(tc.Output, "\n"))
90 if expected != lines {
91 t.Fatalf("Nb lines mismatch\nExpected:%d\nActual:%d",
92 expected, lines)
93 }
94 }
95}