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

后端 未结 4 2261
梦如初夏
梦如初夏 2021-02-20 04:32

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

相关标签:
4条回答
  • 2021-02-20 05:18

    The output can be suppressed by running the tests with go test .:

    $ go help test

    Go test runs in two different modes: local directory mode when invoked with no package arguments (for example, 'go test'), and package list mode when invoked with package arguments (for example 'go test math', 'go test ./...', and even 'go test .').

    In local directory mode, go test compiles and tests the package sources found in the current directory and then runs the resulting test binary. In this mode, caching (discussed below) is disabled. After the package test finishes, go test prints a summary line showing the test status ('ok' or 'FAIL'), package name, and elapsed time.

    In package list mode, go test compiles and tests each of the packages listed on the command line. If a package test passes, go test prints only the final 'ok' summary line. If a package test fails, go test prints the full test output. If invoked with the -bench or -v flag, go test prints the full output even for passing package tests, in order to display the requested benchmark results or verbose logging.

    0 讨论(0)
  • 2021-02-20 05:26

    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)
     }
    }
    
    0 讨论(0)
  • 2021-02-20 05:26

    Not exactly what you are asking for but still might be helpful.

    You can use t.Log (http://golang.org/pkg/testing/#T.Log) and t.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 in myshow.LoadPath. Then you can disable (or capture) the output in the test by setting custom writer using log.SetOutput

    0 讨论(0)
  • 2021-02-20 05:30

    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

    0 讨论(0)
提交回复
热议问题