dongrong5189 2015-10-17 18:15
浏览 32

如何检查stdout是否已写入?

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.

  • 写回答

1条回答 默认 最新

  • duanlaofu4108 2015-10-17 21:49
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?