utils_test.go raw
1 package utils
2
3 import (
4 "testing"
5
6 "github.com/stretchr/testify/assert"
7 )
8
9 func TestParseCommandLine(t *testing.T) {
10 t.Parallel()
11
12 type testCase struct {
13 name string
14 input string
15 expectedSuccess []string
16 expectedError string
17 }
18
19 // When called by the API, the first argument of the command input is actually the command name
20 testCases := []testCase{
21 {
22 name: "empty input",
23 input: "",
24 expectedSuccess: []string{},
25 expectedError: "",
26 },
27 {
28 name: "single argument",
29 input: "arg1",
30 expectedSuccess: []string{"arg1"},
31 expectedError: "",
32 },
33 {
34 name: "multiple arguments",
35 input: "arg1 arg2 arg3",
36 expectedSuccess: []string{"arg1", "arg2", "arg3"},
37 expectedError: "",
38 },
39 {
40 name: "multiple arguments with extra whitespace",
41 input: " arg1\targ2 arg3 ",
42 expectedSuccess: []string{"arg1", "arg2", "arg3"},
43 expectedError: "",
44 },
45 {
46 name: "multiple arguments with quotes and escaping",
47 input: `"arg 1" arg2 "arg\"3"`,
48 expectedSuccess: []string{"arg 1", "arg2", `arg"3`},
49 expectedError: "",
50 },
51 {
52 name: "unquoted escaped whitespace",
53 input: `arg\ 1 arg2`,
54 expectedSuccess: []string{"arg 1", "arg2"},
55 expectedError: "",
56 },
57 {
58 name: "escaped JSON",
59 input: `{\"hello\":\"world\"}`,
60 expectedSuccess: []string{`{"hello":"world"}`},
61 expectedError: "",
62 },
63 {
64 name: "escaped JSON with space",
65 input: `"{\"hello\": \"world\"}"`,
66 expectedSuccess: []string{`{"hello": "world"}`},
67 expectedError: "",
68 },
69 {
70 name: "unclosed quote",
71 input: `"arg 1", "arg2", "arg\"3`,
72 expectedSuccess: nil,
73 expectedError: "unexpected end of string",
74 },
75 {
76 name: "three quotes",
77 input: `"""`,
78 expectedSuccess: nil,
79 expectedError: "unexpected end of string",
80 },
81 {
82 name: "unfinished escape",
83 input: `arg\`,
84 expectedSuccess: nil,
85 expectedError: "unexpected end of string",
86 },
87 }
88
89 for _, tc := range testCases {
90 t.Run(tc.name, func(t *testing.T) {
91 t.Parallel()
92 parsedArgs, err := ParseCommandLine(tc.input)
93 if tc.expectedError == "" {
94 assert.NoError(t, err)
95 assert.Equal(t, tc.expectedSuccess, parsedArgs)
96 } else {
97 assert.EqualError(t, err, tc.expectedError)
98 assert.Empty(t, parsedArgs)
99 }
100 })
101 }
102 }
103