A quick overview of some of the code coverage tools available for use with Rust lang today.
JetBrains CLion
Before we get into terminal tools that provide coverage, tools like CLion IDE provide a way to see code coverage right in the editor:
To run the coverage select the directory that has your tests and using the context menu and use the “with Coverage” option:
grcov
Another tool for code coverage is called grcov
. It is available at https://github.com/mozilla/grcov.
To produce HTML reports with grcov you can either use the built-in way or using the lcov package. The workflow for grcov is as follows:
# Install the tool
cargo install grcov
# Enable the required Rust flags to generate the coverage files
export CARGO_INCREMENTAL=0
export RUSTFLAGS="-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Coverflow-checks=off -Zno-landing-pads"
# grcov requires rust nightly at this time
cargo +nightly test
# generate the html report
grcov ./target/debug/ -s . -t html --llvm --branch --ignore-not-existing -o ./target/debug/coverage/
# open the report
open target/debug/coverage/index.html
It should produce a report like this for you:
Tarpaulin
You can find cargo tarpaulin
at https://github.com/xd009642/tarpaulin.
Installable like the rest of Rust utilities via cargo install cargo-tarpaulin
. Keep in mind “Tarpaulin only supports x86_64 processors running Linux.” at this time. There’s a work in progress on macOS support, but at this time the best you can do in a non-Linux environment is to use the Docker image that tarpaulin provides. In my case, I had to modify the Dockerfile to add extra dependencies that are required for the project.
In your project run cargo tarpaulin -v
and everything goes well you should get some code coverage results right away:
In some cases (in other projects) this can also sadly fail with a segfault
!
To generate the HTML report use the following:
# generate the Html report
cargo tarpaulin -o Html
# this will generate the tarpaulin-report.html in your root
open tarpaulin-report.html
kcov
Found at https://github.com/kennytm/cargo-kcov, install via cargo install cargo-kcov
. Besides installing the package from crates.io, you will probably be required extra dependencies for this to work. Follow the prompts when you first run cargo kcov
. After you install the dependencies and cargo kcov
runs successfully the coverage should be generated. There was no output in my case, but you can open target/cov/index.html
and the report should be there:
Your mileage may vary
These tools may not work out of the box for your projects. Sadly sometimes the coverage fails either fails to generate or the project might even fail to build. If you find something that works really well for you please share it with me, I’d be happy to add more detail to this list!