Search code examples
gotestingconsoleprintln

How to print from go test to console without using verbose option


I want to print an informative message to console from a test, but not have the verbose test output.

I have tried printing from the test using:

  • fmt.Println("my message") // STDOUT
  • fmt.Fprintln(os.Stderr, "my message") // STDERR
  • t.Log("my message\n") // testing.T log

which all produce the same effect of showing in the console if go test -v is used, but not showing if just go test is used.

However, with go test -v, I also get all the verbose test output like:

=== RUN   My_Test
--- PASS: My_Test (0.07s)

go help testflag says:

-v
    Verbose output: log all tests as they are run. Also print all
    text from Log and Logf calls even if the test succeeds.

but what I want is to not log all tests as they are run, but still print all text from Log and Logf calls even if the test succeeds

Is there a way to print a visible message from within a test, but not see the RUN and PASS messages?


Solution

  • Although this doesn't print during the test, it prints straight after, which is better than not printing at all.

    Define an os.File in your test file to write messages to:

    var messagesFile *os.File
    
    func messages() *os.File {
        if messagesFile == nil {
            messagesFile, _ = os.Create("tests.out")
        }
        return messagesFile
    }
    

    os.Create creates a new file if one doesn't exist, otherwise truncates the existing file.

    Within your tests, write messages to that file:

    messages().WriteString("my message")
    

    Run your tests using go test, then cat the file. In my case, I use make:

    test:
        go test .
        @cat tests.out
    

    Output looks like:

    ok  <path to tests>
    my message