rss resume / curriculum vitae linkedin linkedin gitlab github twitter mastodon instagram
Go Tip: Code Coverage
Jun 20, 2018

Code coverage in Go is included in the toolchain and it is as simple as appending -coverprofile to the usual go test command, kind of like using:

go test -coverprofile=cover.out <package-name>

Assuming all tests pass, then you should get an output similar to:

ok  	<package-name>	0.046s	coverage: <XY.Z>% of statements

Where XY.Z is the actual code coverage percentage. Notice that the coverprofile file, cover.out, can be used for generating a more human friendly output, like HTML, with:

go tool cover -html=cover.out -o coverage/index.html

This workflow is perfect when you’re only working on one package, but if you’re working on a monorepo getting the total code coverage requires a bit extra work.

Enter gocovmerge a tool written in Go that merges multiple coverprofiles into one, for example assuming you generated two coverprofiles: cover1.out and cover2.out, you would use:

gocovmerge cover*out > profiles_merged

Which then we can use to properly generate one single HTML file, with:

go tool cover -html=profiles_merged -o coverage/index.html

But more importantly generate a total percentage with:

go tool cover -func=profiles_merged > coverage_output

With that you could actually get the real final coverage using something like:

tail -n 1 coverage_output | tr -s '\t' ' ' | sed -n 's/.*\([0-9][0-9]\).*/\1/p'

Back to posts