Skip to content

Commit d8c0060

Browse files
committed
Add commander for excuting commands
1 parent 5dc257c commit d8c0060

File tree

3 files changed

+108
-0
lines changed

3 files changed

+108
-0
lines changed

pkg/commander/commander.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package commander
2+
3+
import (
4+
"os"
5+
"os/exec"
6+
)
7+
8+
// Commander is an interface to execute commands
9+
type Commander interface {
10+
Execute(cmd string, args []string) ([]string, error)
11+
}
12+
13+
// Default is a Commander implementation that
14+
// can execute commands on a actual machine
15+
type Default struct{}
16+
17+
// Execute executes a command on the actual machine
18+
func (Default) Execute(cmdStr string, args []string, envs []string) (string, error) {
19+
cmd := exec.Command(cmdStr, args...)
20+
cmd.Env = os.Environ()
21+
cmd.Env = append(cmd.Env, envs...)
22+
out, err := cmd.Output()
23+
if err != nil {
24+
return string(out), err
25+
}
26+
27+
return string(out), nil
28+
}

pkg/commander/commander_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package commander_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/arunvelsriram/kube-tmuxp/pkg/commander"
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestExecute(t *testing.T) {
11+
t.Run("should execute command on the machine", func(t *testing.T) {
12+
cmdr := commander.Default{}
13+
out, err := cmdr.Execute("echo", []string{"-n", "test"}, []string{})
14+
15+
assert.Nil(t, err)
16+
assert.Equal(t, "test", out)
17+
})
18+
19+
t.Run("should be able to set env variables for a command", func(t *testing.T) {
20+
cmdr := commander.Default{}
21+
out, err := cmdr.Execute("env", []string{}, []string{"TEST_ENV=test"})
22+
23+
assert.Nil(t, err)
24+
assert.Contains(t, out, "TEST_ENV=test")
25+
})
26+
27+
t.Run("should return error if execution fails", func(t *testing.T) {
28+
cmdr := commander.Default{}
29+
out, err := cmdr.Execute("invalid-cmd", []string{}, []string{})
30+
31+
assert.NotNil(t, err)
32+
assert.Equal(t, "", out)
33+
})
34+
}

pkg/internal/mock/commander.go

+46
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)