You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为cargo test生成测试覆盖率?kcov/cargo-kcov报错如何解决?

kcov报错原因及Rust覆盖率解决方案

kcov相关问题根源

  • 参数顺序错误:cargo-kcov的参数规则为cargo kcov [kcov配置项] -- [cargo test配置项],你之前执行的命令没有加--分隔符,--package、--test等参数被识别为kcov的配置,没有传递给cargo test,因此会提示找不到failpoints测试目标。
  • Mac设备kcov阻塞原因:macOS默认开启的系统完整性保护(SIP)会拦截kcov的动态插桩操作,kcov无法向测试二进制注入跟踪代码,因此会永久阻塞。如果要正常使用kcov需要手动关闭SIP,该操作会降低系统安全性,不推荐使用。

可行的kcov调用格式(仅适用于已关闭SIP的Mac或Linux设备)

将cargo test参数放在--后即可:

cargo kcov -- --package tests --test failpoints cases::test_normal
cargo kcov -- --package tests --test failpoints cases::test_bootstrap
cargo kcov -- --package tests --test failpoints cases::test_compact_log

更适合Mac设备的grcov解决方案(无需关闭SIP)

前置依赖安装

# 安装llvm工具链组件
rustup component add llvm-tools-preview
# 安装grcov
cargo install grcov

覆盖率采集步骤

  1. 配置覆盖率编译参数和输出路径
export RUSTFLAGS="-C instrument-coverage"
export LLVM_PROFILE_FILE="target/coverage/%p-%m.profraw"
mkdir -p target/coverage
  1. 按原有逻辑执行所有测试用例
cargo test --package tests --test failpoints cases::test_normal
cargo test --package tests --test failpoints cases::test_bootstrap
cargo test --package tests --test failpoints cases::test_compact_log
  1. 生成仅包含components/raftstore路径的覆盖率报告
grcov target/coverage \
  --binary-path target/debug/ \
  -s . \
  -t html \
  --ignore "*" \
  --include "components/raftstore/*" \
  -o target/coverage/report

执行完成后打开target/coverage/report/index.html即可查看对应的覆盖率结果。


内容的提问来源于stack exchange,提问作者calvin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:24:03