I like it when terminal/console test runs actually show their output in either red or green text. It seems like a lot of the testing libraries available for Go have this. However, I'd like to just use the default testing package that comes with Go. Is there a way to colorize it's output with red and green?
You can create a wrapper shell script for this and color it using color escape sequence. Here's a simple example on Linux (I'm not sure how this would look on windows, but I guess there is a way.. :) )
go test -v . | sed ''/PASS/s//$(printf "\033[32mPASS\033[0m")/'' | sed ''/FAIL/s//$(printf "\033[31mFAIL\033[0m")/''
You would still need a library to add color escape code like:
mattn/go-colorable
or shiena/ansicolor
fatih/color
or kortschak/ct
logrusorgru/aurora
(mentioned by Ivan Black in the comments)From there, you specify what you want to color (StdOut or StdErr, like in this example)
BoltDB has some test methods that look like this:
func assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
if !condition {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m
", append([]interface{}{filepath.Base(file), line}, v...)...)
tb.FailNow()
}
}
Here are the rest. I added the green dots here.
You can use grc, a generic colourizer, to colourize anything.
On Debian/Ubuntu, install with apt-get install grc
. On a Mac with , brew install grc
.
Create a config directory in your home directory:
mkdir ~/.grc
Then create your personal grc config in ~/.grc/grc.conf
:
# Go
\bgo.* test\b
conf.gotest
Then create a Go test colourization config in ~/.grc/conf.gotest
, such as:
regexp==== RUN .*
colour=blue
-
regexp=--- PASS: .*
colour=green
-
regexp=^PASS$
colour=green
-
regexp=^(ok|\?) .*
colour=magenta
-
regexp=--- FAIL: .*
colour=red
-
regexp=[^\s]+\.go(:\d+)?
colour=cyan
Now you can run Go tests with:
grc go test -v ./..
Sample output:
To avoid typing grc
all the time, add an alias to your shell (if using Bash, either ~/.bashrc
or ~/.bash_profile
or both, depending on your OS):
alias go=grc go
Now you get colourization simply by running:
go test -v ./..
There's also a tool called richgo that does exactly this, in a user-friendly way.