two new helpers in github.com/juju/testing
Nate Finch
nate.finch at canonical.com
Fri Apr 22 19:52:59 UTC 2016
I added a couple new helpers to the testing repo that I think will help us
avoid some of the contortions we have had to do in the past when testing
executables and output on stderr/stdout.
The first is a fairly simple function, CaptureOutput
<https://godoc.org/github.com/juju/testing#CaptureOutput>, which takes in a
func() and returns anything written to stderr or stdout while running that
function. It temporarily replaces os.Stderr and os.Stdout with files on
disk while running the function (necessary because those two values are
*os.File values, so, rather hard to mock out with anything in-memory).
The second is slightly more complicated - PatchExecHelper
<https://godoc.org/github.com/juju/testing#PatchExecHelper>
We had PatchExecutable, which creates gnarly bash/batch scripts on disk to
replace expected executables, but it has a few weaknesses - it doesn't
allow you to test the arguments passed to it *and* test stderr/stdout at
the same time, it assumed the thing you were patching out was on the PATH,
and I'm pretty sure it wouldn't work to patch out .exe files on Windows.
PatchExecHelper fixes all of those problems by approaching the problem in a
different way, it creates a function that is intended to mock out a call to
exec.Command. It's very easy to use, just embed PatchExecHelper in your
test suite, and then use its GetExecCommand() method to get a function that
can be used to mock out exec.Command.
The exact method of how it works is detailed in the godoc, and it's an
example implementation of something I blogged about a while back:
https://npf.io/2015/06/testing-exec-command/
Here's an example of how it can be used:
// production code
var execCommand = exec.Command
func Run(command string, args ...string) ([]byte, error) {
return execCommand(command, args...).CombinedOutput()
}
// test code
type RunSuite struct {
testing.CleanupSuite
// you *must* embed PatchExecHelper in your test suite.
testing.PatchExecHelper
}
func (s RunSuite) TestRun(c *gc.C) {
outArgs := make(chan []string, 1)
f := s.GetExecCommand(testing.PatchExecConfig{
Stderr: "this is stderr!",
Stdout: "this is stdout!",
ExitCode: 5,
Args: outArgs,
})
s.PatchValue(&execCommand, f)
output, err := Run("echo", "hello world!")
args := <-outArgs
// test output, args, etc.
}
Let me know if you have any questions or comments.
-Nate
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ubuntu.com/archives/juju-dev/attachments/20160422/f9c327e8/attachment.html>
More information about the Juju-dev
mailing list