Go: Wrong coverage when there is no tests for a package
Asked Answered
R

2

14

I have a Go project with the following structure:

foo/foo.go
foo/foo_test.go
main.go

As you notice, there is no test for main.go.

I collect the coverage report using the following command:

go test ./foo ./ -coverprofile=coverage.txt -covermode=atomic

Here ./foo and ./ show where to look for packages.

Problem: I send the coverage report to codecov.io which shows that my code is 100% covered with tests. But this is not true as my main.go has no tests at all.

It seems like the system only counts those packages that explicitly specify test files.

Question: How to fix the coverage report in the way that it will count information about untested packages?

Note: You can find my project on GitHub and the real statistic is here. The project has a different structure, but the issue persists (wrong coverage).

Raquel answered 24/1, 2020 at 20:18 Comment(1)
Does this solve your issue? go test -coverpkg=.,./foo -coverprofile=coverage.txt -covermode=atomic . ./fooTentation
T
13

The -coverpkg flag may be used to specify the packages that are used as the basis of coverage analyis.

Quoting from Command go: Testing flags:

-coverpkg pattern1,pattern2,pattern3
    Apply coverage analysis in each test to packages matching the patterns.
    The default is for each test to analyze only the package being tested.
    See 'go help packages' for a description of package patterns.
    Sets -cover.

So in your specific example this will do it:

go test -coverpkg=.,./foo -coverprofile=coverage.txt -covermode=atomic . ./foo

To apply it for a complete module / project, you may use:

go test -coverpkg=./... -coverprofile=coverage.txt -covermode=atomic ./...

Another option is to place an "empty" test file into the folders of packages that do not currently have a test file. That way they will be naturally included in default coverage analysis, but obviously nothing will be covered from them.

See related discussion on github:

cmd/go: go test -cover & go test -coverprofile should always output a coverage #24570

Tentation answered 25/1, 2020 at 7:8 Comment(1)
There are problems with the coverpkg method unfortunately. If you want accurate coverage you have to place empty test files everywhere you don't have tests. I have a repo that demonstrates the pros and cons of available workarounds hereUltramicrochemistry
V
1

try this one:

go test -coverpkg=./... -race -coverprofile=coverage.txt -covermode=atomic ./..

enter image description here

Variolite answered 24/1, 2020 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.