-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplace_test.go
126 lines (117 loc) · 2.69 KB
/
replace_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import "testing"
func TestReplace(t *testing.T) {
cases := []struct {
content, search, replace, expected string
}{
{"foobar", "foo", "bar", "barbar"},
}
for _, c := range cases {
actual := (&Replace{Search: c.search, Replace: c.replace}).Execute(c.content, nil)
if actual != c.expected {
t.Errorf(
"Replace{Search: %v, Replace: %v}.Execute(%v) == %v, expected %v",
c.search, c.replace, c.content, actual, c.expected)
}
}
}
func TestReplaceRegexp(t *testing.T) {
cases := []struct {
content, search, replace, expected string
}{
{
content: "foobar",
search: "fo+",
replace: "bar",
expected: "barbar",
},
{
content: "foobar",
search: "(...)(...)",
replace: "$2$1",
expected: "barfoo",
},
}
for index, c := range cases {
replace := Replace{Search: c.search, Replace: c.replace, Regexp: true}
actual := replace.Execute(c.content, nil)
if actual != c.expected {
t.Errorf(
"Case: #%d - content: %s, search: %s, replace: %s\n"+
" actual: %#v\n"+
"expected: %#v\n",
index, c.content, c.search, c.replace, actual, c.expected)
}
}
}
func TestReplaceCallback(t *testing.T) {
cases := []struct {
callbackResult bool
expected string
}{
{false, "foobar"},
{true, "barbar"},
}
for _, c := range cases {
actual := (&Replace{Search: "foo", Replace: "bar"}).Execute("foobar", func(info ReplacementInfo) bool {
return c.callbackResult
})
if actual != c.expected {
t.Errorf(
"callbackResult: %v, expected: %v, actual: %v",
c.callbackResult, c.expected, actual)
}
}
}
func TestReplacementInfoContextLines(t *testing.T) {
cases := []struct {
content string
expectedLinesBeforeMatch string
expectedLinesAfterMatch string
}{
{"foo", "", ""},
{
"line1\n" +
"line2\n" +
"line3\n" +
"line4\n" +
"line5 foo\n" +
"line6\n" +
"line7\n" +
"line8\n" +
"line9\n",
"line2\n" +
"line3\n" +
"line4\n",
"line6\n" +
"line7\n" +
"line8\n",
},
{
"line1\n" +
"line2 foo\n" +
"line3\n",
"line1\n",
"line3\n",
},
}
for index, c := range cases {
(&Replace{Search: "foo", Replace: "bar"}).Execute(c.content, func(info ReplacementInfo) bool {
if info.LinesBeforeMatch != c.expectedLinesBeforeMatch {
t.Errorf(
"Case: #%d - LinesBeforeMatch\n"+
" actual: %#v\n"+
"expected: %#v\n",
index, info.LinesBeforeMatch, c.expectedLinesBeforeMatch)
}
if info.LinesAfterMatch != c.expectedLinesAfterMatch {
t.Errorf(
"Case: #%d - LinesAfterMatch\n"+
" actual: %#v\n"+
"expected: %#v\n",
index, info.LinesAfterMatch, c.expectedLinesAfterMatch)
}
return true
})
}
}