How to measure test coverage in Go
Asked Answered
P

16

215

Has anyone succeeded in generating code coverage for Go unit tests? I can't find a tool for that on the web.

Packing answered 9/5, 2012 at 12:59 Comment(1)
For VSCode users: github.com/golang/vscode-go/blob/master/docs/…Danielson
B
230

Note that Go 1.2 (Q4 2013, rc1 is available) will now display test coverage results:

One major new feature of go test is that it can now compute and, with help from a new, separately installed "go tool cover" program, display test coverage results.

The cover tool is part of the go.tools subrepository. It can be installed by running

$ go get golang.org/x/tools/cmd/cover

The cover tool does two things.

  • First, when "go test" is given the -cover flag, it is run automatically to rewrite the source for the package and insert instrumentation statements. The test is then compiled and run as usual, and basic coverage statistics are reported:

    $ go test -coverprofile fmtcoverage.html fmt ok fmt 0.060s coverage: 91.4% of statements $

  • Second, for more detailed reports, different flags to "go test" can create a coverage profile file, which the cover program, invoked with "go tool cover", can then analyze.

Frank Shearar mentions:

The latest versions of Go (2013/09/19) use:

go test -coverprofile <filename> <package name>

Details on how to generate and analyze coverage statistics can be found by running the commands

$ go help testflag
$ go tool cover -help

Ivan Black mentions in the comments:

go test -coverprofile cover.out and then
go tool cover -html=cover.out opens cover.out in your default browser

I don't even want to wait for the browser to open, so I defined this alias:

alias gc=grep -v -e " 1$" cover.out

That I just type gc, and have a list of all the lines not yet covered (here: with a coverage.out line not ending with " 1").


Update 2022, possibly for Go 1.19

proposal: extend Go's code coverage testing to include applications

While the existing "go test" based coverage workflow will continue to be supported, the proposal is to add coverage as a new build mode for "go build".

In the same way that users can build a race-detector instrumented executable using "go build -race", it will be possible to build a coverage-instrumented executable using "go build -cover".

Merging coverage profiles produced in different GOOS/GOARCH environments will be supported.


Update March 2023, Go 1.20: "Code coverage for Go integration tests" shows that you can now build coverage-instrumented programs using “go build -cover”, then feed these instrumented binaries into an integration test to extend the scope of coverage testing.

Ballet answered 20/9, 2013 at 7:54 Comment(9)
Note that the latest versions of Go (2013/09/19) use go test -coverprofile <filename> <package name>Sumer
@FrankShearar Ok. I have included your comment in the answer for more visibility.Ballet
go test -coverprofile cover.out and then go tool cover -html=cover.out -o cover.html open cover.html in browserHussar
@IvanBlack good point. I have included it in the answer for more visibility. I also added an alias I use to quickly see non-covered lines.Ballet
@Ballet go tool cover -html=cover.out will automatically opens a browser, but it doesn't work for my system. I prefer to keep a browser open and refresh the page if necessary.Hussar
@IvanBlack true. I guess I am more a command-line person myself ;)Ballet
go tool cover has moved to new URL, so please use command go get golang.org/x/tools/cmd/cover instead.Somersault
It's worth mentioning that if you have multiple packages in your project, generating a coverage profile is not quite so easy. If you run something like go test ./... -coverprofile=cover.out you get the following error: cannot use test profile flag with multiple packages. There's still an open issue to add support for this.Marchetti
@SamJones For that, you have github.com/mattn/goveralls and github.com/haya14busa/goverage (mentioned in medium.com/@haya14busa/…)Ballet
C
73

In addition to the good answers above, I find these three lines to be the simplest way to get it (which includes all packages):

go test -v -coverprofile cover.out ./YOUR_CODE_FOLDER/...
go tool cover -html cover.out -o cover.html
open cover.html

Note that in the HTML file you will find a dropdown button that will direct you to all files.

See go tool cover -help for additional options.

Creon answered 1/8, 2018 at 13:32 Comment(3)
I was getting errors as "too many arguments. For usage information, run "go tool cover -help"". That is solved by removing "=" after -html tag go tool cover -html cover.out -o cover.htmlLimb
open cover.html works fine but it generates unwanted listener logs in the same terminal in ubuntu as follows bash Gtk-Message: 00:03:41.903: Failed to load module "canberra-gtk-module" Gtk-Message: 00:03:41.904: Failed to load module "canberra-gtk-module"Withhold
Great help! you might want to mention the ... is used for recursively search for inner folders.Tansy
U
70

Go comes with awesome tool for testing and coverage. Although all Go tools are well documented go tool cover -help I would suggest reading The cover story article on the official Go blog. It has plenty of examples and I strongly recommend it!

I have this function in my ~/.bash_profile. (you can just paste it in the terminal to give it a try).

cover () { 
    t="/tmp/go-cover.$$.tmp"
    go test -coverprofile=$t $@ && go tool cover -html=$t && unlink $t
}

Then just cd into a go project/package folder and type cover. This opens a visual tool in browser which shows you the tested and untested code for each file in the current package. Very useful command! I strongly recommend it for finding what is not 100% tested yet! The shown results are per file. From a drop down in top-left you can see results for all files.

With this command you can also check the coverage of any package for example:

cover fmt

The output in terminal from this command would be:

ok      fmt 0.031s  coverage: 91.9% of statements

In addition to that in your browser you will see this tool showing in red all lines of code which are not covered with tests:

enter image description here

It is also possible to just save the html coverage file instead of opening it in a browser. This is very useful in cases when your tests + coverage is run by CI tool like Jenkins. That way you can serve the coverage files from a central server and the whole team will be able to see the coverage results for each build.

Untaught answered 4/12, 2014 at 1:0 Comment(4)
Snippet copied from here coderwall.com/p/rh-v5a/get-coverage-of-golang-testUntaught
Interesting, I will test it. +1Ballet
This is awesome! Thanks for sharing. Ended up moving into a test script as I wanted to test a main package in my program. CheersEntrap
If you want the per file percentage as a list you can use cat cover.out.html | grep '<option value="file' | sed -E 's/.*>(.*) \((.*)%\)<.*/\2 \1/' | sort -rnMag
M
37

Simply run

go test -cover

or

go test -cover ./...

or

go test -coverprofile=coverage.out ./... ;    go tool cover -func=coverage.out

or to check the source code

go test -coverprofile=coverage.out ./... ;    go tool cover -html=coverage.out
Maximalist answered 26/12, 2020 at 7:17 Comment(3)
doesn't work on Windows11Maryettamaryjane
@RezaTaba it doesn't seem true, these commands are platform independent, what exactly is your problem? (why do you say it doesn't work?)Durmast
I'm not sure what the problem was at the time. However I found a better solution through the VSCode's Command Pallete which is already integrated. Provided my solution here.Maryettamaryjane
B
17

I can't find a tool for that on the web.

Actually... there is now (2022) such a tool on the web, from Nikolay Dubina's project go-cover-treemap-web:

https://go-cover-treemap.io/

Nothing it uploaded (the processing remains local), but by dragging/dropping your coverprofile, the Web UI (using Go WASM) will run go-cover-treemap and display:

https://static.mcmap.net/file/mcmap/ZG-AbGLDKwfnZ7-ocV9QWRft/nikolaydubina/go-cover-treemap/raw/main/docs/hugo.svg
(gocovergage for https://github.com/gohugoio/hugo)

Ballet answered 7/5, 2022 at 13:20 Comment(0)
M
17

Already built-in in VSCode

  1. Ctrl+Shift+P to Open Command Palette
  2. Go: Toggle Test Coverage ...

The Green part is tested and Red is not

enter image description here

Maryettamaryjane answered 19/11, 2022 at 16:53 Comment(2)
Thank you! Was wondering why I couldn't find a good custom solution for viewing test coverage in VS Code, as apparently it already existed natively.Soothsay
For some reason the commands mentioned in answer above doesn't work for me. I keep getting "No required module provides package .out; to add it: go get .out". But this worked for me.Conceal
M
14

Coverage Report:

a) Run all the tests and enable coverage --> go test ./... -coverprofile coverage.out

b) Get coverage for individual functions as well as overall coverage → go tool cover -func coverage.out

c) See the lines covered and the ones not covered by your tests → go tool cover -html=coverage.out -o coverage.html. Open the coverage.html file hereby generated in the browser and analyze the detailed coverage info.

Munt answered 26/9, 2019 at 17:19 Comment(0)
L
5

It's right here, some docs here.

$ go tool
6a
6c
6g
6l
addr2line
api
cgo
cov
dist
ebnflint
fix
gotype
nm
objdump
pack
pprof
prof
vet
yacc
$ go tool cov -h
usage: cov [-lsv] [-g substring] [-m minlines] [6.out args...]
-g specifies pattern of interesting functions or files
go tool cov: exit status 1
$

I haven't used it, this is all I know.

Landward answered 9/5, 2012 at 13:22 Comment(4)
do you have to install it manually? in my local go installation (go version go1) it is not there.Lautrec
I believe it gets build by ./all.bash. I cannot verify ATM, I'm not at release as I have a CL pending, but the cov binary time stamp I see in ~/go/pkg/tool/linux_amd64 matches my last Go build of yesterday.Landward
Yes, run ./all.bash and you will have it. Thanks for the help, jnml!Packing
I have some problems running it on my x86 machine. I tried changing main.c as mentioned in this thread: groups.google.com/group/golang-dev/browse_thread/thread/… But it generates a runtime error in another location. I will try it on a 64 bit machine.Packing
A
5

If you like to see the uncovered lines by function directly in a terminal I rewrote the cover tool for this purpose. It's available at https://github.com/gregoryv/uncover.

Usage

go get -u github.com/gregoryv/uncover/...
go test -coverprofile /tmp/c.out
uncover /tmp/c.out

Screenshot

enter image description here

Arrivederci answered 20/8, 2018 at 19:16 Comment(0)
L
5

If you are using VSCode this functionality is supported out the box ( But disabled by default )

Just turn on test on save + coverage reporting

https://github.com/microsoft/vscode-go/wiki/On-Save-features

It will even show in your editor which lines are not covered which is super handy.

Lobule answered 31/10, 2019 at 16:16 Comment(0)
P
3

If you want to find test coverage in Windows, just go to the desired folder in command prompt and type the following command:

go test -coverprofile=coverage.out && go tool cover -html=coverage.out

This is perfectly easy and works reliably.

Piloting answered 11/5, 2021 at 14:10 Comment(1)
I get this error >> no required module provides package .out; to add it: go get .outMaryettamaryjane
L
2

A quick and easy way is to use the coverage tool that comes with built-in go :

$ go test -coverprofile cp.out // Emits the coverage in one liner percentage wise

After you execute the above command, if you wish to visually see the code coverage (like covered statements and missed etc)

$ go tool cover -html=cp.out

Note : You need to execute the above commands in the folder where you wish to see coverage

Lizalizabeth answered 8/5, 2018 at 17:48 Comment(0)
C
2

Just run:

go test -v -cover ./...
Cobden answered 8/2 at 11:51 Comment(0)
A
0

Try using gaia-docker/base-go-build Docker Image.

This is a Docker image that contains all you need in order to build and test coverage. Running test coverage inside a Docker container creates .cover folder with test coverage results of your project.

docker run --rm -v "$PWD":$PROJECT_PATH -w $PROJECT_PATH $BUILDER_IMAGE_NAME /go/script/coverage.sh

The test coverage script running on all projects' folders and generates, inside .cover folder junit and coverage reports for each folder, and a combine coverage report of all projects' tests.

Codecov also suggests a script that collect coverage results: multiple files

Arroba answered 3/1, 2017 at 8:49 Comment(0)
M
-1

Test Coverage for Golang

go get github.com/axw/gocov/gocov go get -u gopkg.in/matm/v1/gocov-html

Check It is Installed Correctly And you have access from your Terminal

Run the Test Case

If you run the test case it will Reder the .json File Based on the file you will get the Code Coverage Report in .html file

gocov test >your_Coverage_report.json

Once Your Test case is done Generate a Report in .html File using .json

gocov-html your_Coverage_report.json >your_Coverage_report.html

Reference

GoTest Coverage Tool for go lang

Go Test Report Tool

Alternate Method

Go Native Test coverage

go test -coverprofile=coverage.out
go tool cover -html=coverage.out
Mayne answered 1/3, 2018 at 6:39 Comment(0)
T
-2

A better test coverage reporter than go tool cover:

https://github.com/JacksonTian/gocov

enter image description here

Tingle answered 22/11, 2023 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.