-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathshellwords_test.go
85 lines (77 loc) · 2.31 KB
/
shellwords_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
package shellwords
import (
"os/exec"
"testing"
"github.com/stretchr/testify/assert"
)
type testCase struct {
expected []string
message string
}
func TestSplitString(t *testing.T) {
testCases := map[string]testCase{
`a "b b" a`: {[]string{"a", "b b", "a"}, "quoted strings"},
`a "'b' c" d`: {[]string{"a", "'b' c", "d"}, "escaped double quotes"},
`a '"b" c' d`: {[]string{"a", `"b" c`, "d"}, "escaped single quotes"},
`a b\ c d`: {[]string{"a", "b c", "d"}, "escaped spaces"},
`a b\ c d`: {[]string{"a", "b c", "d"}, "extra spaces in separator"},
` a b\ c d`: {[]string{"a", "b c", "d"}, "extra leading spaces"},
`a b\ c d `: {[]string{"a", "b c", "d"}, "extra tailing spaces"},
"a 'aa\nbb\ncc'": {[]string{"a", "aa\nbb\ncc"}, "multi-line"},
"echo 1 | cat > 'test 1.txt'": {[]string{"echo", "1", "|", "cat", ">", "test 1.txt"}, "pipe"},
`cat > a.txt <<EOH
abc
123
EOH`: {[]string{"cat", ">", "a.txt", "<<EOH", "abc", "123", "EOH"}, "heredoc"},
}
errorCases := []string{
`a "b c d e`,
`a 'b c d e`,
`"a "'b' c" d`,
}
for input, res := range testCases {
t.Run(res.message, func(t *testing.T) {
actual, err := Split(input)
assert.NoError(t, err)
assert.Equal(t, res.expected, actual, res.message)
})
}
for _, input := range errorCases {
t.Run(input, func(t *testing.T) {
_, err := Split(input)
assert.Error(t, err)
})
}
}
func TestEscape(t *testing.T) {
testCases := []string{
``,
`abc`,
`a b c`,
`a b `,
`a\nb`,
"a\nb",
"a\n\nb",
`a $HOME`,
`sh -c 'pwd'`,
`a"b'`,
}
for _, expected := range testCases {
escaped := Escape(expected)
actual, err := exec.Command("sh", "-c", "printf %s "+escaped).Output()
assert.NoError(t, err)
assert.Equal(t, expected, string(actual), "input: [%s], escaped: [%s], actual: [%s]", expected, escaped, actual)
}
}
func TestJoin(t *testing.T) {
testCases := map[string][]string{
"": {},
"a b c": {"a", "b", "c"},
`a\ b c`: {"a b", "c"},
`sh -c echo\ foo`: {"sh", "-c", "echo foo"},
}
for expected, input := range testCases {
actual := Join(input)
assert.Equal(t, expected, actual, "input: %#v, expected: (%s), actual: (%s)", input, expected, actual)
}
}