diff --git a/testing/mocks/executor.go b/testing/mocks/executor.go new file mode 100644 index 00000000..2881b554 --- /dev/null +++ b/testing/mocks/executor.go @@ -0,0 +1,46 @@ +package mocks + +import ( + "os/exec" + + "github.com/stretchr/testify/assert" + "github.com/untangle/golang-shared/util" +) + +// MockExecutorNoErr is a struct used for tests, where Run, Output, and CombinedOutput all return with no errors +type MockExecutorNoErr struct{} + +// type enforcement +var _ util.ExecutorInterface = (*MockExecutorNoErr)(nil) + +func (m *MockExecutorNoErr) Run(cmd *exec.Cmd) error { + return nil +} + +func (*MockExecutorNoErr) Output(cmd *exec.Cmd) ([]byte, error) { + return []byte{}, nil +} + +func (*MockExecutorNoErr) CombinedOutput(cmd *exec.Cmd) ([]byte, error) { + return []byte{}, nil +} + +// MockExecutorRunErr is a struct used for tests where Run returns an error, but Output and CombinedOutput do not +type MockExecutorRunErr struct{ MockExecutorNoErr } + +// type enforcement +var _ util.ExecutorInterface = (*MockExecutorRunErr)(nil) + +func (*MockExecutorRunErr) Run(cmd *exec.Cmd) error { + return assert.AnError +} + +// MockExecutorCombinedOutputErr is a struct used for tetss where CombinedOutput returns an error, but Run and Output do not +type MockExecutorCombinedOutputErr struct{ MockExecutorNoErr } + +// type enforcement +var _ util.ExecutorInterface = (*MockExecutorCombinedOutputErr)(nil) + +func (*MockExecutorCombinedOutputErr) CombinedOutput(cmd *exec.Cmd) ([]byte, error) { + return []byte{}, assert.AnError +} diff --git a/util/executor.go b/util/executor.go new file mode 100644 index 00000000..387ae52c --- /dev/null +++ b/util/executor.go @@ -0,0 +1,32 @@ +package util + +import ( + "os/exec" +) + +// ExecutorInterface allows us to mock calls to exec.Cmd +type ExecutorInterface interface { + Run(cmd *exec.Cmd) error + Output(cmd *exec.Cmd) ([]byte, error) + CombinedOutput(cmd *exec.Cmd) ([]byte, error) +} + +// Executor is the struct used by most of the code: handlerResourceProvider, dynamic_lists, and system +type Executor struct{} + +var _ ExecutorInterface = (*Executor)(nil) // type enforcement + +// Run will run the passed cmd command in the terminal +func (*Executor) Run(cmd *exec.Cmd) error { + return cmd.Run() +} + +// Output runs the cmd command in the terminal and returns its standard output +func (*Executor) Output(cmd *exec.Cmd) ([]byte, error) { + return cmd.Output() +} + +// CombinedOutput runs the cmd command in the terminal and returns its combined standard output and standard error +func (*Executor) CombinedOutput(cmd *exec.Cmd) ([]byte, error) { + return cmd.CombinedOutput() +}