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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
// Copyright 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package exec_test
import (
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/utils/exec"
)
// 0 is thrown by linux because RunParams.Wait
// only sets the code if the process exits cleanly
const cancelErrCode = 0
func (*execSuite) TestRunCommands(c *gc.C) {
newDir := c.MkDir()
for i, test := range []struct {
message string
commands string
workingDir string
environment []string
stdout string
stderr string
code int
}{
{
message: "test stdout capture",
commands: "echo testing stdout",
stdout: "testing stdout\n",
}, {
message: "test stderr capture",
commands: "echo testing stderr >&2",
stderr: "testing stderr\n",
}, {
message: "test return code",
commands: "exit 42",
code: 42,
}, {
message: "test working dir",
commands: "pwd",
workingDir: newDir,
stdout: newDir + "\n",
}, {
message: "test environment",
commands: "echo $OMG_IT_WORKS",
environment: []string{"OMG_IT_WORKS=like magic"},
stdout: "like magic\n",
}, {
message: "multiple commands",
commands: "cat\necho 123",
stdout: "123\n",
},
} {
c.Logf("%v: %s", i, test.message)
params := exec.RunParams{
Commands: test.commands,
WorkingDir: test.workingDir,
Environment: test.environment,
}
result, err := exec.RunCommands(params)
c.Assert(err, gc.IsNil)
c.Assert(string(result.Stdout), gc.Equals, test.stdout)
c.Assert(string(result.Stderr), gc.Equals, test.stderr)
c.Assert(result.Code, gc.Equals, test.code)
err = params.Run()
c.Assert(err, gc.IsNil)
c.Assert(params.Process(), gc.Not(gc.IsNil))
result, err = params.Wait()
c.Assert(err, gc.IsNil)
c.Assert(string(result.Stdout), gc.Equals, test.stdout)
c.Assert(string(result.Stderr), gc.Equals, test.stderr)
c.Assert(result.Code, gc.Equals, test.code)
err = params.Run()
c.Assert(err, gc.IsNil)
c.Assert(params.Process(), gc.Not(gc.IsNil))
result, err = params.WaitWithCancel(nil)
c.Assert(err, gc.IsNil)
c.Assert(string(result.Stdout), gc.Equals, test.stdout)
c.Assert(string(result.Stderr), gc.Equals, test.stderr)
c.Assert(result.Code, gc.Equals, test.code)
}
}
func (*execSuite) TestExecUnknownCommand(c *gc.C) {
result, err := exec.RunCommands(
exec.RunParams{
Commands: "unknown-command",
},
)
c.Assert(err, gc.IsNil)
c.Assert(result.Stdout, gc.HasLen, 0)
c.Assert(string(result.Stderr), jc.Contains, "unknown-command: command not found")
// 127 is a special bash return code meaning command not found.
c.Assert(result.Code, gc.Equals, 127)
}
|