github.com/bhameyie/otto@v0.2.1-0.20160406174117-16052efa52ec/helper/exec/stub.go (about) 1 package exec 2 3 import ( 4 "io" 5 "os/exec" 6 "strings" 7 ) 8 9 // Runner is the function that is called to run a command. This can be 10 // overridden for tests. This is a low-level replacement but we use it in 11 // various helper libraries for unit testing. 12 var Runner func(*exec.Cmd) error = RealRunner 13 14 // TestChrunner is a helper function that can be used to temporarily change 15 // the runner. This returns a function call that should be defered to restore 16 // the runner. Example: 17 // 18 // defer TestChrunner(newRunner)() 19 // 20 func TestChrunner(r func(*exec.Cmd) error) func() { 21 oldRunner := Runner 22 Runner = r 23 return func() { 24 Runner = oldRunner 25 } 26 } 27 28 // RealRunner is the default value of Runner and actually executes a command. 29 func RealRunner(cmd *exec.Cmd) error { 30 return cmd.Run() 31 } 32 33 // MockRunner is a Runner implementation that records the calls. The 34 // Runner can be set to the MockRunner's Run function. 35 type MockRunner struct { 36 // This will record the commands that are executed 37 Commands []*exec.Cmd 38 39 // This will be the return values of the errors for the commands 40 // that are executed, in the order they're called. If this is empty 41 // or shorter than the command, a nil error is returned. 42 CommandErrs []error 43 44 // This will be written to the stdout when this command runs 45 CommandOutput []string 46 } 47 48 func (r *MockRunner) Run(cmd *exec.Cmd) error { 49 r.Commands = append(r.Commands, cmd) 50 if len(r.CommandOutput) >= len(r.Commands) { 51 output := strings.NewReader(r.CommandOutput[len(r.Commands)-1]) 52 if _, err := io.Copy(cmd.Stdout, output); err != nil { 53 return err 54 } 55 } 56 if len(r.CommandErrs) < len(r.Commands) { 57 return nil 58 } 59 60 return r.CommandErrs[len(r.Commands)-1] 61 }