github.com/alloyci/alloy-runner@v1.0.1-0.20180222164613-925503ccafd6/shells/cmd_test.go (about) 1 package shells 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 type testCase struct { 11 in string 12 out string 13 } 14 15 type outputColor struct { 16 fn func(string, ...interface{}) 17 color string 18 } 19 20 func TestCMD_EchoShellEscapes(t *testing.T) { 21 for i, tc := range []testCase{ 22 {`abcdefghijklmnopqrstuvwxyz`, `abcdefghijklmnopqrstuvwxyz`}, 23 {`^ & < > |`, `^^ ^& ^< ^> ^|`}, 24 // FIXME: this currently escapes to ^! when it doesn't need to 25 // {`!`, `!`}, 26 {`( )`, `^( ^)`}, 27 } { 28 writer := &CmdWriter{} 29 for j, functionsToTest := range []outputColor{ 30 {writer.Notice, "\x1b[32;1m"}, 31 {writer.Warning, "\x1b[0;33m"}, 32 {writer.Error, "\x1b[31;1m"}, 33 {writer.Print, "\x1b[0;m"}, 34 } { 35 functionsToTest.fn(tc.in) 36 expected := fmt.Sprintf("echo %s%s\x1b[0;m\r\n", functionsToTest.color, tc.out) 37 assert.Equal(t, expected, writer.String(), "case %d : %d", i, j) 38 writer.Reset() 39 } 40 } 41 } 42 43 func TestCMD_CDShellEscapes(t *testing.T) { 44 for i, tc := range []testCase{ 45 {`c:\`, `c:\`}, 46 {`c:/`, `c:\`}, 47 {`c:\Program Files`, `c:\Program Files`}, 48 {`c:\Program Files (x86)`, `c:\Program Files (x86)`}, // Don't escape the parens 49 {`c: | rd Windows\System32`, `c: ^| rd Windows\System32`}, // Escape the | 50 } { 51 writer := &CmdWriter{} 52 writer.Cd(tc.in) 53 expected := fmt.Sprintf("cd /D \"%s\"\r\nIF %%errorlevel%% NEQ 0 exit /b %%errorlevel%%\r\n\r\n", tc.out) 54 assert.Equal(t, expected, writer.String(), "case %d", i) 55 } 56 } 57 58 func TestCMD_CommandShellEscapes(t *testing.T) { 59 writer := &CmdWriter{} 60 writer.Command("foo", "x&(y)") 61 62 assert.Equal(t, "\"foo\" \"x^&(y)\"\r\nIF %errorlevel% NEQ 0 exit /b %errorlevel%\r\n\r\n", writer.String()) 63 } 64 65 func TestCMD_IfCmdShellEscapes(t *testing.T) { 66 writer := &CmdWriter{} 67 writer.IfCmd("foo", "x&(y)") 68 69 assert.Equal(t, "\"foo\" \"x^&(y)\" 2>NUL 1>NUL\r\nIF %errorlevel% EQU 0 (\r\n", writer.String()) 70 }