Test coverage on GitLab CI in a rust-cargo project

This topic presents who to setup kcov with cargo to get a test coverage for a cargo project, so I just assume you got kcov working in your Linux distribution and you have a project with source code and tests that you can run. I also assume you have gitlab-ci-multi-runner installed. So I will just quickly present who to configure it to use with GitLab CI to get test coverage badge in your new project.

I use my own CI runner, I’m not using shared runners or docker for it. So it’s pretty straightforward, your configuration will differ a bit.

My .gitlab-ci.yml file defines two stages for GitLab pipeline system, one makes sure the projects builds correctly:

Cargo build:
  stage: build
  script:
  - cargo build

runs nothing more than cargo build.

The second stage runs cargo test, launches kcov to generate test coverage table from debug build file.
If both commands passed correctly there should be an index.json file in target/cov/ generated, which contains information about your coverage results, so it’s just enough to extract what we need and pass to GitLab CI in a nice human-readable format:

Cargo test:
  stage: test
  script:
  - cargo test
  - kcov target/cov target/debug/motion_of_confidence-*
  - COVERAGE=$(grep -Po 'covered":.*?[^\\]"' target/cov/index.json | grep "[0-9]*\.[0-9]" -o)
  - echo "Coverage:" $COVERAGE

Now just go to your project, CI/CD Piplelines settings and set this as `Test coverage parsing`

^Coverage+:\s(\d+(?:\.\d+)?)

gitlab ci test coverage parsing for carglo kcov

When execution is complete you can open the log and that’s what you should see the very bottom:
gitlab ci rust cargo test coverage

Run your build… and you should hopefully see that your test coverage was reported correctly:

gitlab test coverage

[Total: 1    Average: 5/5]