Capture os.Stdout
and/or os.Stderr
in Go.
This package is useful for writing tests which print some outputs using fmt
package.
This package provides CaptureStdout()
, CaptureStderr()
and CaptureOutput()
functions to capture outputs.
package main
import (
"fmt"
"os"
"github.com/kami-zh/go-capturer"
)
func ExampleCaptureStdout() {
out := capturer.CaptureStdout(func() {
fmt.Fprint(os.Stdout, "foo")
})
fmt.Println(out)
// Output: foo
}
func ExampleCaptureStderr() {
out := capturer.CaptureStderr(func() {
fmt.Fprint(os.Stderr, "bar")
})
fmt.Println(out)
// Output: bar
}
func ExampleCaptureOutput() {
out := capturer.CaptureOutput(func() {
fmt.Fprint(os.Stdout, "foo")
fmt.Fprint(os.Stderr, "bar")
})
fmt.Println(out)
// Output: foobar
}
$ go get github.com/kami-zh/go-capturer
Bug reports and pull requests are welcome on GitHub at https://github.com/kami-zh/go-capturer.
The package is available as open source under the terms of the MIT License.