Skip to content

Commit

Permalink
Create helper type to better override streams in command tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Katrina Owen committed Dec 30, 2018
1 parent 24da940 commit b055290
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions cmd/cmd_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"io"
"io/ioutil"
"os"
"testing"
Expand Down Expand Up @@ -90,3 +91,30 @@ func (test *CommandTest) Teardown(t *testing.T) {
t.Fatal(err)
}
}

// capturedOutput lets us more easily redirect streams in the tests.
type capturedOutput struct {
oldOut, oldErr, newOut, newErr io.Writer
}

// newCapturedOutput creates a new value to override the streams.
func newCapturedOutput() capturedOutput {
return capturedOutput{
oldOut: Out,
oldErr: Err,
newOut: ioutil.Discard,
newErr: ioutil.Discard,
}
}

// override sets the package variables to the fake streams.
func (co capturedOutput) override() {
Out = co.newOut
Err = co.newErr
}

// reset puts back the original streams for the commands to write to.
func (co capturedOutput) reset() {
Out = co.oldOut
Err = co.oldErr
}

0 comments on commit b055290

Please sign in to comment.