4

I'm trying to display an accurate coverage badge for my gitlab project.

Thing is I have several packages, in gitlab-ci.yml, I run

go test $(go list ./... | grep -v /vendor/) -v -coverprofile .testCoverage.txt

and my output is something like that:

$ go test -coverprofile=coverage.txt -covermode=atomic ./...
 ok     gitlab.com/[MASKED]/pam 10.333s coverage: 17.2% of statements
 ok     gitlab.com/[MASKED]/pam/acquisition 0.004s  coverage: 57.7% of statements
 ok     gitlab.com/[MASKED]/pam/acquisition/api 0.005s  coverage: 72.1% of statements
 ok     gitlab.com/[MASKED]/pam/acquisition/ftp 24.936s coverage: 73.1% of statements
 ok     gitlab.com/[MASKED]/pam/repartition 0.004s  coverage: 90.1% of statements

And my Test coverage parsing regex in Gitlab is:

^coverage:\s(\d+(?:\.\d+)?%)

If I check the .testCoverage, I get a lot of lines like that:

 gitlab.com/[MASKED]/pam/repartition/repartition.go:54.33,56.5 1 1

So, it gives me a result of 90.1% when it is only the coverage of the last package.

How should I do it ?

Juliatzin
  • 18,455
  • 40
  • 166
  • 325

1 Answers1

10

According to this answer,

I just needed another command:

go tool cover -func profile.cov

That will give you the result:

✗ go tool cover -func profile.cov

gitlab.com/[MASKED]/pam/acquisition/acquisition.go:17:                       FetchAll                        0.0%
gitlab.com/[MASKED]/pam/acquisition/acquisition.go:32:                       TransformData                   100.0%
gitlab.com/[MASKED]/pam/acquisition/acquisition_mocks.go:13:                 FetchMeters                     0.0%
gitlab.com/[MASKED]/pam/repartition/repartition.go:102:                      GroupMetersByOperation          100.0%
gitlab.com/[MASKED]/pam/repartition/repartition.go:111:                      SetProrataRedistributed         71.4%
total:                                                                          (statements)                    68.7%

In gitlab, you can change the regex:

^coverage:\s(\d+(?:\.\d+)?%)

By

\(statements\)(?:\s+)?(\d+(?:\.\d+)?%)

Now, if you have mocks, coverage will include them, so you must remove them following this answer:

go test . -coverprofile profile.cov.tmp
cat profile.cov.tmp | grep -v "_mocks.go" > cover.out
tool cover -func profile.cov

Off course, all your mocks should be in files with suffix : _mocks.go

And it should work.

Hope it helps others!

Juliatzin
  • 18,455
  • 40
  • 166
  • 325