github.com/verrazzano/verrazzano@v1.7.0/pkg/os/shell_test.go (about) 1 // Copyright (c) 2021, 2022, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package os 5 6 import ( 7 "errors" 8 "github.com/stretchr/testify/assert" 9 "os/exec" 10 "testing" 11 ) 12 13 // TestRunBash tests the exec RunBash command 14 // GIVEN a command 15 // 16 // WHEN I call Run 17 // THEN the value returned will have the correct stdout and stderr 18 func TestRunBash(t *testing.T) { 19 assert := assert.New(t) 20 21 // override cmd.Run function 22 cmdRunFunc = bashGoodCmdRunner 23 stdout, stderr, err := RunBash("fakecmd", "arg1", "arg2", "arg3") 24 assert.NoError(err, "Error should not be returned from exec") 25 assert.Len(stderr, 0, "stderr is incorrect") 26 assert.Equal("success", string(stdout), "stdout is incorrect") 27 assert.NoError(err, "Error should not be returned from exec") 28 } 29 30 // TestRunBashErr tests the exec Run error condition 31 // GIVEN a command and a fake runner that returns an error 32 // 33 // WHEN I call Run 34 // THEN the value returned will have and error status and the correct stdout and stderr 35 func TestRunBashErr(t *testing.T) { 36 assert := assert.New(t) 37 38 // override cmd.Run function 39 cmdRunFunc = bashBadCmdRunner 40 cmd := exec.Command("fakecmd", "arg1", "arg2", "arg3") 41 stdout, stderr, err := DefaultRunner{}.Run(cmd) 42 assert.Error(err, "Error should be returned from exec") 43 assert.Len(stdout, 0, "stdout is incorrect") 44 assert.Equal("err", string(stderr), "stderr is incorrect") 45 } 46 47 func bashGoodCmdRunner(cmd *exec.Cmd) error { 48 cmd.Stdout.Write([]byte("success")) 49 cmd.Stderr.Write([]byte("")) 50 return nil 51 } 52 53 func bashBadCmdRunner(cmd *exec.Cmd) error { 54 cmd.Stdout.Write([]byte("")) 55 cmd.Stderr.Write([]byte("err")) 56 return errors.New("error") 57 }