Golang测试标准输出(Golang test stdout)

编程入门 行业动态 更新时间:2024-10-13 04:18:49
Golang测试标准输出(Golang test stdout)

我试图测试打印ANSI转义码的一些函数。 例如

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

我尝试使用示例来做到这一点,但他们似乎不喜欢转义码。

有什么方法可以测试写入stdout的内容吗?

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

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

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?

最满意答案

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

var out io.Writer = os.Stdout func main() { // write to Stdout PrintlnColor("foo") buf := &bytes.Buffer{} out = buf // write to buffer PrintlnColor("foo") fmt.Println(buf.String()) } // Print a line in a color func PrintlnColor(a ...interface{}) { fmt.Fprint(out, "\x1b[31m") fmt.Fprint(out, a...) fmt.Fprintln(out, "\x1b[0m") }

去玩

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

var out io.Writer = os.Stdout func main() { // write to Stdout PrintlnColor("foo") buf := &bytes.Buffer{} out = buf // write to buffer PrintlnColor("foo") fmt.Println(buf.String()) } // Print a line in a color func PrintlnColor(a ...interface{}) { fmt.Fprint(out, "\x1b[31m") fmt.Fprint(out, a...) fmt.Fprintln(out, "\x1b[0m") }

Go play

更多推荐

本文发布于:2023-04-29 03:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   标准   Golang   test   stdout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!