Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions program.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
package wrapper

import (
"errors"
"fmt"
"os/exec"
)

type Program struct {
executable string
params map[string]interface{}
getCombinedOutputFunc func(cmd *exec.Cmd) ([]byte, error)
executable string
params map[string]interface{}
}

func NewProgram(executable string) *Program {
program := &Program{
executable: executable,
params: make(map[string]interface{}),
}
program.getCombinedOutputFunc = program.getCombinedOutput
return program
}

Expand All @@ -25,7 +24,9 @@ func (p *Program) WithParam(name string, value interface{}) *Program {
return p
}

func (p *Program) getCombinedOutput(cmd *exec.Cmd) ([]byte, error) {
var getCombinedOutputFunc = getCombinedOutput

func getCombinedOutput(cmd *exec.Cmd) ([]byte, error) {
return cmd.CombinedOutput()
}

Expand All @@ -37,9 +38,22 @@ func (p *Program) Run() (string, error) {
}

cmd := exec.Command(p.executable, params...)
output, err := p.getCombinedOutputFunc(cmd)
output, err := getCombinedOutputFunc(cmd)
if err != nil {
return "", err
}
return string(output), nil
}

func (p *Program) Compile(mainPath string) error {
cmd := exec.Command("go", "build", "-o", p.executable, mainPath)
output, err := getCombinedOutputFunc(cmd)
if err != nil {
return err
}
outputStr := string(output)
if outputStr != "" {
return errors.New("Error compiling: " + outputStr)
}
return nil
}
22 changes: 22 additions & 0 deletions program_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package wrapper

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

"github.com/stretchr/testify/require"
)

func Test_program_cmdError(t *testing.T) {

cmdErr := errors.New("test error")

program := NewProgram("")
getCombinedOutputFunc = func(cmd *exec.Cmd) ([]byte, error) {
return nil, cmdErr
}
defer func() { getCombinedOutputFunc = getCombinedOutput }()
_, err := program.Run()
require.Equal(t, cmdErr, err)
}
3 changes: 3 additions & 0 deletions test/program_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ func Test_program(t *testing.T) {
path := filepath.Join(wd, "../testProgram.exe")

program := wrapper.NewProgram(path)
err = program.Compile("../testProgram/main.go")
require.NoError(t, err)

output, err := program.Run()
require.NoError(t, err)
require.Contains(t, output, "default message")
Expand Down