As part of a Go unit testing CI job, we can generate code coverage statistics. For Gitlab to display them, we must provide appropriate output from the job’s script commands (stdout). Below is a sample CI test job:

1
2
3
4
5
6
unit-tests:
  image: golang:1.12
  stage: test
  script:
    - go test -race $(go list ./... | grep -v /vendor/) -v -coverprofile=coverage.out
    - go tool cover -func=coverage.out

On line 5 we run the go test command and specify that we would like to generate coverage profile and save it in a file called coverage.out

On line 6 we use the go tool cover command to generate (stdout) output broken down by function. Example output is shown below:

1
2
3
4
5
6
7
$ go tool cover -func=coverage.out
gitlab.com/myuser/myproject/file1.go:30:	exampleFunc1	100.0%
gitlab.com/myuser/myproject/file2.go:45:	exampleFunc2	100.0%
gitlab.com/myuser/myproject/pkg1/file3.go:89:	exampleFunc3	100.0%
gitlab.com/myuser/myproject/pkg2/file4.go:23:	exampleFunc4	95.0%
gitlab.com/myuser/myproject/pkg2/file5.go:134:	exampleFunc5	0.0%
total:						(statements)	65.3%

After the script commands are executed, we can tell Gitlab how to parse the output and extract the test coverage value.

The value we want to display as code coverage percentage is 65.3%. The regular expression to use for that is:

1
total:\s+\(statements\)\s+(\d+.\d+\%)

The regular expression can be set in Settings >> CI/CD >> General Pipelines >> Test coverage parsing. For more complete information, check the Gitlab guide.