Skip to content

Commit b055290

Browse files
author
Katrina Owen
committed
Create helper type to better override streams in command tests
1 parent 24da940 commit b055290

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

cmd/cmd_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cmd
22

33
import (
4+
"io"
45
"io/ioutil"
56
"os"
67
"testing"
@@ -90,3 +91,30 @@ func (test *CommandTest) Teardown(t *testing.T) {
9091
t.Fatal(err)
9192
}
9293
}
94+
95+
// capturedOutput lets us more easily redirect streams in the tests.
96+
type capturedOutput struct {
97+
oldOut, oldErr, newOut, newErr io.Writer
98+
}
99+
100+
// newCapturedOutput creates a new value to override the streams.
101+
func newCapturedOutput() capturedOutput {
102+
return capturedOutput{
103+
oldOut: Out,
104+
oldErr: Err,
105+
newOut: ioutil.Discard,
106+
newErr: ioutil.Discard,
107+
}
108+
}
109+
110+
// override sets the package variables to the fake streams.
111+
func (co capturedOutput) override() {
112+
Out = co.newOut
113+
Err = co.newErr
114+
}
115+
116+
// reset puts back the original streams for the commands to write to.
117+
func (co capturedOutput) reset() {
118+
Out = co.oldOut
119+
Err = co.oldErr
120+
}

0 commit comments

Comments
 (0)