Skip to content

Instantly share code, notes, and snippets.

@davydany
Created November 9, 2022 23:16
Show Gist options
  • Save davydany/8ba1199e55499078b738bbcb01a514dd to your computer and use it in GitHub Desktop.
Save davydany/8ba1199e55499078b738bbcb01a514dd to your computer and use it in GitHub Desktop.
Go - Capture Stdout from your tests
func startCapturingStdout() {
// capture things from stdout
suite.Old = os.Stdout // keep backup of the real stdout
r, w, _ := os.Pipe()
suite.R = r
suite.W = w
os.Stdout = suite.W
suite.OutC = make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
suite.OutC <- buf.String()
}()
}
func stopCapturingStdout() string {
// bring thigns back to normal with stdout
suite.W.Close()
os.Stdout = suite.Old // restoring the real stdout
out := <-suite.OutC
return out
}
func main() {
startCapturingStdout();
fmt.Println("Hello World!")
captured := stopCapturingStdout()
fmt.Println(captured) // will print out "Hello World!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment