Skip to content

Commit

Permalink
Add exec package tests
Browse files Browse the repository at this point in the history
Signed-off-by: Tobias Brumhard <[email protected]>
  • Loading branch information
brumhard committed Oct 30, 2021
1 parent 38fd02f commit 80efc94
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
77 changes: 77 additions & 0 deletions pkg/exec/command_group_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package exec_test

import (
"errors"
"os/exec"
"testing"

ownexec "github.com/schwarzit/go-template/pkg/exec"
"github.com/stretchr/testify/require"
)

func Test_CommandGroup_RunWith(t *testing.T) {
t.Run("no command is executed if prerun fails", func(t *testing.T) {
cg := ownexec.CommandGroup{
PreRun: func() error {
return errors.New("dummy")
},
Commands: []*exec.Cmd{
exec.Command("anything"),
},
}

anyCommandExecuted := false
err := cg.RunWith(ownexec.CmdRunnerFunc(func(cmd *exec.Cmd) (string, error) {
anyCommandExecuted = true
return "", nil
}))

require.Error(t, err)
require.False(t, anyCommandExecuted)
})
t.Run("all commands are executed if there's no error", func(t *testing.T) {
cg := ownexec.CommandGroup{
Commands: []*exec.Cmd{
exec.Command("anything"),
exec.Command("sthelse"),
},
}

anythingExecuted, sthelseExecuted := false, false
err := cg.RunWith(ownexec.CmdRunnerFunc(func(cmd *exec.Cmd) (string, error) {
switch cmd.Path {
case "anything":
anythingExecuted = true
case "sthelse":
sthelseExecuted = true
}
return "", nil
}))

require.NoError(t, err)
require.True(t, anythingExecuted)
require.True(t, sthelseExecuted)
})
t.Run("no commands are executed after the first one fails", func(t *testing.T) {
cg := ownexec.CommandGroup{
Commands: []*exec.Cmd{
exec.Command("anything"),
exec.Command("sthelse"),
},
}

sthelseExecuted := false
err := cg.RunWith(ownexec.CmdRunnerFunc(func(cmd *exec.Cmd) (string, error) {
switch cmd.Path {
case "anything":
return "", errors.New("dummy")
case "sthelse":
sthelseExecuted = true
}
return "", nil
}))

require.Error(t, err)
require.False(t, sthelseExecuted)
})
}
24 changes: 24 additions & 0 deletions pkg/exec/runner_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package exec_test

import (
"os/exec"
"runtime"
"testing"

ownexec "github.com/schwarzit/go-template/pkg/exec"
"github.com/stretchr/testify/require"
)

func Test_execCmdRunner_Run(t *testing.T) {
t.Run("error if command not found", func(t *testing.T) {
_, err := ownexec.NewExecCmdRunner().Run(exec.Command("does-not-exist"))
var errWithStderr *ownexec.ErrWithStderr
require.ErrorAs(t, err, &errWithStderr)
require.ErrorIs(t, err, exec.ErrNotFound)
})
t.Run("returns command's stdout", func(t *testing.T) {
output, err := ownexec.NewExecCmdRunner().Run(exec.Command("go", "version"))
require.NoError(t, err)
require.Contains(t, output, runtime.Version())
})
}

0 comments on commit 80efc94

Please sign in to comment.