Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Coverage not including functions in other package

Tags:

go

I have a project like this:

app/
    api/
        foo.go
        test_foo.go
src/
    db/
        bar.go

In foo.go, a call is made to a function in bar.go. However, when running the coverage report, it shows that 0 lines of bar.go are covered.

Is there a way to get coverage to include function call to other packages?

In my case, I do not want to make separate tests for db and for api, since all calls through db will always go through api, and it would be redundant to write two tests.

I'm running the coverage like this:

go clean -testcache
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
like image 937
Matthew Moisen Avatar asked Mar 16 '19 19:03

Matthew Moisen


2 Answers

You need to include the coverpkg flag so:

 go test -coverpkg=./... coverprofile=coverage.out ./...

Would calculate the coverage on all of your packages.

https://golang.org/cmd/go/#hdr-Testing_flags

like image 119
Iain Duncan Avatar answered Oct 05 '22 19:10

Iain Duncan


Short answer. To see correct coverages run:

go test ./... -coverprofile=coverage.out -coverpkg=./...
go tool cover -html=coverage.out

And then see percentages in dropdown inside browser.


Longer answer with explanation why other ways not worked. So, I also have a project with api and store (in this question it is called db) packages, where store is used in api, and I have tests in api.

go test -cover ./...

Says that api is covered, store - "[no test files]".

When I run it like

go test -cover -coverpkg=./... ./...

It decreases coverage in api because now that number means how testcases in api package cover all the packages, which is not very useful number.

But there is a way to know how given package is covered by tests in all the packages (eg, how store is covered by tests from api and other places).

First, you generate coverage profile:

go test ./... -coverprofile=coverage.out -coverpkg=./... 

Above command will still give you wrong percents in output, but it will create coverage.out file that will list all the lines in all packages covered by tests in all packages.

Then you could view this report in the browser with the command:

go tool cover -html=coverage.out

Then in the dropdown that allows you to select files to browse coverage for, you will get correct per file coverages.

like image 30
Bunyk Avatar answered Oct 05 '22 21:10

Bunyk