Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang test stdout [duplicate]

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?

like image 379
giodamelio Avatar asked Nov 14 '14 19:11

giodamelio


1 Answers

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

like image 61
jmaloney Avatar answered Oct 15 '22 23:10

jmaloney