Dipen
Dipen

Reputation: 546

How can I check whether stdout has been written to?

I am trying to test whether a function, which is capable of printing to stdout using the "os" package's stdout variable, actually prints to stdout. I ran this function and I found that it does print to the stdout. Now I am trying to figure out how to prove that this function prints to stdout using golang code. Could I possibly use the "os" package's stdout variable to check whether stdout has been written to after calling one of the functions in the array?

I tried to figure out whether stdout had been written to by calling the Stat() method on the os.stdout variable in order to have access to the size and last modified time of stdout, but the size and last modified time did not reflect the fact that a function had written to the stdout.

Upvotes: 1

Views: 606

Answers (1)

Stephen Weinberg
Stephen Weinberg

Reputation: 53398

In my opinion, the correct way to handle this is to make your code take the io.Writer as a parameter in some way instead of using stdout directly. You really should avoid printing to stdout without a way for higher level code to redirect it. Nearly all of the stdlib takes this approach. Very little of the stdlib writes to stdout by default and most of the places that do have a more general form which takes a Writer. For example, fmt.Printf is simply a convenience function for fmt.Fprintf.

That being said, you can mock stdout. If your code is pushing to stdout, all you need to do is make a global variable for stdout and write to there instead. This is done in the stdlib tests to mock time.Now(). Instead of using time.Now, they use a package global now() and set that depending on if a test is being run.

As a last resort, assuming the previous two things are impossible, you can make a copy of the current os.Stdout and replace it with an os.Pipe. Then you need another goroutine to listen on that pipe and report whatever was returned.

Upvotes: 1

Related Questions