Created
November 9, 2022 23:16
-
-
Save davydany/8ba1199e55499078b738bbcb01a514dd to your computer and use it in GitHub Desktop.
Go - Capture Stdout from your tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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