Skip to content

Instantly share code, notes, and snippets.

@buzztaiki
Last active February 12, 2024 11:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzztaiki/6579a14cbf18dcfebec550ebe531c5cf to your computer and use it in GitHub Desktop.
Save buzztaiki/6579a14cbf18dcfebec550ebe531c5cf to your computer and use it in GitHub Desktop.
Rust の Source-based code coverage をお手軽に使う

Rust の Source-based code coverage をお手軽に使う

1.60 で Source-based code coverage が安定化した (stable で使えるようになった)。

どうやって使うのかといった話は リリースノート に書いてある通り。なんだけど、ちょっと面倒くさい。

簡単に使うには https://github.com/taiki-e/cargo-llvm-cov の力を借りる。

まずは、llvm-tools-previewcargo-llvm-cov を入れておく:

% rustup component add llvm-tools-preview
% cargo install cargo-llvm-cov

cargo llvm-cov でテストを実行してカバレジを出す (カバレジ率には test attribute が付いた関数も含まれる):

% cargo llvm-cov
   Compiling hello v0.1.0 (/tmp/hello)
    Finished test [unoptimized + debuginfo] target(s) in 0.34s
     Running unittests src/main.rs (target/llvm-cov-target/debug/deps/hello-2b124e0e25e940c7)

running 1 test
test tests::test_hello ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Filename                      Regions    Missed Regions     Cover   Functions  Missed Functions  Executed       Lines      Missed Lines     Cover    Branches   Missed Branches     Cover
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/tmp/hello/src/main.rs              6                 1    83.33%           5                 1    80.00%          11                 3    72.73%           0                 0         -
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
TOTAL                               6                 1    83.33%           5                 1    80.00%          11                 3    72.73%           0                 0         -

--lcov オプションを指定すると lcov フォーマットで出力できる。また --open を指定すると HTML を出力してからブラウザで開いたりできる。便利。ちゃんとした使い方は README を読む。

https://github.com/mozilla/grcov も Source-based code coverage に対応してるみたいなので、こっちが好みの場合はそれでも良いと思う (cargo-llvm-cov よりは面倒)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment