Golang测试标准输出

huangapple go评论121阅读模式
英文:

Golang test stdout

问题

我正在尝试测试一些打印 ANSI 转义码的函数,例如:

  1. // 打印带颜色的行
  2. func PrintlnColor(color string, a ...interface{}) {
  3. fmt.Print("\x1b[31m")
  4. fmt.Print(a...)
  5. fmt.Println("\x1b[0m")
  6. }

我尝试使用 Examples 来测试,但它们似乎不支持转义码。

有没有办法测试输出到标准输出(stdout)的内容?

英文:

I am trying to test some functions that print ANSI escape codes. e.g.

  1. // Print a line in a color
  2. func PrintlnColor(color string, a ...interface{}) {
  3. fmt.Print("\x1b[31m")
  4. fmt.Print(a...)
  5. fmt.Println("\x1b[0m")
  6. }

I tried using Examples to do it, but they don't seem to like escape codes.

Is there any way to test what is written to stdout?

答案1

得分: 13

使用fmt.Fprint将内容打印到io.Writer可以控制输出的位置。

  1. var out io.Writer = os.Stdout
  2. func main() {
  3. // 输出到标准输出
  4. PrintlnColor("foo")
  5. buf := &bytes.Buffer{}
  6. out = buf
  7. // 输出到缓冲区
  8. PrintlnColor("foo")
  9. fmt.Println(buf.String())
  10. }
  11. // 以彩色打印一行
  12. func PrintlnColor(a ...interface{}) {
  13. fmt.Fprint(out, "\x1b[31m")
  14. fmt.Fprint(out, a...)
  15. fmt.Fprintln(out, "\x1b[0m")
  16. }

在此处运行代码

英文:

Using fmt.Fprint to print to io.Writer lets you control where the output is written.

  1. var out io.Writer = os.Stdout
  2. func main() {
  3. // write to Stdout
  4. PrintlnColor("foo")
  5. buf := &bytes.Buffer{}
  6. out = buf
  7. // write to buffer
  8. PrintlnColor("foo")
  9. fmt.Println(buf.String())
  10. }
  11. // Print a line in a color
  12. func PrintlnColor(a ...interface{}) {
  13. fmt.Fprint(out, "\x1b[31m")
  14. fmt.Fprint(out, a...)
  15. fmt.Fprintln(out, "\x1b[0m")
  16. }

Go play

huangapple
  • 本文由 发表于 2014年11月15日 03:50:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/26937770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定