How can stdout be captured or suppressed for Go testing?
I am trying to teach myself go(lang) testing. In the code below, myshow.LoadPath prints lots of information to stdout (which is a normal side effect). It does however make for very noisy output when I run "go test" Is there a way to suppress or capture stdout?
For comparison, I'm thinking about something like this from the python world. http://pytest.org/latest/capture.html#captures
package slideshow_test
import (
"os"
"testing"
"github.com/golliher/go-hpf/slideshow"
)
func setupTest() {
myshow := slideshow.Slideshow{Name: "This is my show"}
myshow.LoadPath("..")
}
func TestStub(t *testing.T) {
if true == false {
t.Fail()
}
}
func TestMain(m *testing.M) {
setupTest()
os.Exit(m.Run())
}
Not exactly what you are asking for but still might be helpful.
You can use
t.Log
(http://golang.org/pkg/testing/#T.Log) andt.Logf
(http://golang.org/pkg/testing/#T.Logf) methods in the test method. The output will be printed only if the test fails or the-test.v
flag is set.I also would suggest to use
log
package to print to the console inmyshow.LoadPath
. Then you can disable (or capture) the output in the test by setting custom writer usinglog.SetOutput
os.Stdout
which is used by thefmt.Printf
and others is just a variable. So you can overwrite it at any time and restore it back when necessary. https://golang.org/pkg/os/#pkg-variablesTo suppress the output during the test I use the following code. I fixes output as well as logging. After test is done it resets the output streams.
The output can be suppressed by running the tests with
go test .
: