Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can stdout be captured or suppressed for Go(lang) testing?

Tags:

go

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())

}
like image 815
golliher Avatar asked Jul 27 '15 21:07

golliher


People also ask

Which command is used to run the tests in go?

Running subtests in Go The t. Run() command takes two arguments — the first matches against parameters passed to go test , and the second is the name of a test function.

How do you test a method in go?

At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.

How do I run a specific test in Golang?

Go provides the go test command for running the unit tests in a project. Running this command will ordinarily run the whole test suite, but you can limit it to only a specific file or test. If you run go test , it will run both the TestFactorial and TestSquare functions.


2 Answers

os.Stdout which is used by the fmt.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-variables

like image 86
Alex Netkachov Avatar answered Oct 19 '22 01:10

Alex Netkachov


To 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.

func TestStartStowWrongCommand(t *testing.T) {
 defer quiet()()   
 ...                      
}

func quiet() func() {
 null, _ := os.Open(os.DevNull)
 sout := os.Stdout
 serr := os.Stderr
 os.Stdout = null
 os.Stderr = null
 log.SetOutput(null)
 return func() {
  defer null.Close()
  os.Stdout = sout
  os.Stderr = serr
  log.SetOutput(os.Stderr)
 }
}
like image 34
Grzegorz Żur Avatar answered Oct 19 '22 02:10

Grzegorz Żur