...
1 package utils
2
3 import (
4 "bytes"
5 "strings"
6 "testing"
7 )
8
9 func TestPosFinderLine2(t *testing.T) {
10 testval := `
11 line1
12 line2
13 line3
14 line4
15 `
16 new_testval := `
17 line1
18 line2
19 line2b
20 line3
21 line4
22 `
23
24 ct := []byte(testval)
25 nct := []byte(new_testval)
26 pf := NewTextPositionFinder(ct).(*textPositionFinder)
27 x := pf.Content()
28 if !bytes.Equal(x, ct) {
29 t.Fatalf("content mismatch before any modification")
30 }
31 if !pf.FindLineContaining("line2") {
32 t.Fatalf("failed to find pattern")
33 }
34 pf.AddLine("line2b")
35 expect_content(t, nct, pf)
36 }
37
38 func TestPosFinderLine0(t *testing.T) {
39 testval := `
40 line1
41 line2
42 line3
43 line4
44 `
45 new_testval := `
46 line0
47 line1
48 line2
49 line3
50 line4
51 `
52
53 ct := []byte(testval)
54 nct := []byte(new_testval)
55 pf := NewTextPositionFinder(ct).(*textPositionFinder)
56 x := pf.Content()
57 if !bytes.Equal(x, ct) {
58 t.Fatalf("content mismatch before any modification")
59 }
60 pf.AddLine("line0")
61 expect_content(t, nct, pf)
62 }
63
64 func TestPosFinderLine5(t *testing.T) {
65 testval := `
66 line1
67 line2
68 line3
69 line4
70 `
71 new_testval := `
72 line1
73 line2
74 line3
75 line4
76 line4b
77 `
78
79 ct := []byte(testval)
80 nct := []byte(new_testval)
81 pf := NewTextPositionFinder(ct).(*textPositionFinder)
82 x := pf.Content()
83 if !bytes.Equal(x, ct) {
84 t.Fatalf("content mismatch before any modification")
85 }
86 if !pf.FindLineContaining("line4") {
87 t.Fatalf("failed to find pattern")
88 }
89 pf.AddLine("line4b")
90 expect_content(t, nct, pf)
91 }
92
93 func TestPosFinderMultiLine(t *testing.T) {
94 testval := `
95 line1
96 line2
97 line3
98 line4
99 `
100 new_testval := `
101 line1
102 line2
103 line2b
104 line3
105 line4
106 `
107
108 ct := []byte(testval)
109 nct := []byte(new_testval)
110 pf := NewTextPositionFinder(ct).(*textPositionFinder)
111 x := pf.Content()
112 if !bytes.Equal(x, ct) {
113 t.Fatalf("content mismatch before any modification")
114 }
115 pf.FindLineContaining("line")
116 pf.FindLineContaining("line")
117 pf.AddLine("line2b")
118 expect_content(t, nct, pf)
119 }
120
121 func expect_content(t *testing.T, ct []byte, pf *textPositionFinder) {
122 if bytes.Equal(ct, pf.Content()) {
123 return
124 }
125 lines_expected := strings.Split(string(ct), "\n")
126 lines_got := strings.Split(string(pf.Content()), "\n")
127 max_lines := len(lines_expected)
128 if len(lines_got) > max_lines {
129 max_lines = len(lines_got)
130 }
131 ta := &Table{}
132 ta.AddHeaders("got", "expected")
133 for i := 0; i < max_lines; i++ {
134 l1 := ""
135 l2 := ""
136 if i < len(lines_got) {
137 l1 = lines_got[i]
138 }
139 if i < len(lines_expected) {
140 l2 = lines_expected[i]
141 }
142 ta.AddString(l1)
143 ta.AddString(l2)
144 ta.NewRow()
145 }
146 t.Errorf("modification produced incorrect result")
147 t.Logf("\n%s", ta.ToPrettyString())
148
149 }
150
View as plain text