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
|
package command
import (
"errors"
"os/exec"
"testing"
"github.com/stretchr/testify/require"
)
type ErrorWithExitCode struct {
exitCode int
}
func (e ErrorWithExitCode) Error() string {
return "Error that responds to ExitCode()"
}
func (e ErrorWithExitCode) ExitCode() int {
return e.exitCode
}
func TestExitStatus(t *testing.T) {
tests := []struct {
name string
err error
exitCode int
ok bool
}{
{
name: "error responds to ExitCode()",
err: ErrorWithExitCode{exitCode: 0},
exitCode: 0,
ok: true,
},
{
name: "error is not nil",
err: errors.New("some generic error"),
exitCode: -1,
ok: false,
},
{
name: "else",
err: nil,
exitCode: 0,
ok: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
exitCode, ok := ExitStatus(tt.err)
require.Equal(t, tt.exitCode, exitCode)
require.Equal(t, tt.ok, ok)
})
}
}
func TestKillProcessGroup(t *testing.T) {
tests := []struct {
name string
cmd *exec.Cmd
start bool
err error
}{
{
name: "command is nil",
cmd: nil,
start: false,
err: nil,
},
{
name: "command not started",
cmd: exec.Command("sleep"),
start: false,
err: errors.New(""),
},
{
name: "command started",
cmd: exec.Command("sleep"),
start: true,
err: &exec.ExitError{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.start == true {
tt.cmd.Start()
}
err := KillProcessGroup(tt.cmd)
require.IsType(t, tt.err, err)
})
}
}
|