github.com/NeowayLabs/nash@v0.2.2-0.20200127205349-a227041ffd50/tests/internal/sh/shell.go (about) 1 // Package shell makes it easier to run nash scripts for test purposes 2 package sh 3 4 import ( 5 "bytes" 6 "io" 7 "io/ioutil" 8 "os" 9 "os/exec" 10 "testing" 11 12 "github.com/madlambda/nash/tests/internal/assert" 13 ) 14 15 // Exec runs the script code and returns the result of it. 16 func Exec( 17 t *testing.T, 18 nashpath string, 19 scriptcode string, 20 scriptargs ...string, 21 ) (string, string, error) { 22 scriptfile, err := ioutil.TempFile("", "testshell") 23 assert.NoError(t, err, "creating tmp file") 24 25 defer func() { 26 err := scriptfile.Close() 27 assert.NoError(t, err, "closing tmp file") 28 err = os.Remove(scriptfile.Name()) 29 assert.NoError(t, err, "deleting tmp file") 30 }() 31 32 _, err = io.Copy(scriptfile, bytes.NewBufferString(scriptcode)) 33 assert.NoError(t, err, "writing script code to tmp file") 34 35 scriptargs = append([]string{scriptfile.Name()}, scriptargs...) 36 cmd := exec.Command(nashpath, scriptargs...) 37 38 stdout := bytes.Buffer{} 39 stderr := bytes.Buffer{} 40 41 cmd.Stdout = &stdout 42 cmd.Stderr = &stderr 43 44 err = cmd.Run() 45 return stdout.String(), stderr.String(), err 46 }