Golang测试标准

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?

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