產生覆蓋率資料

您可以要求執行器從標記為 #[wasm_bindgen_test] 的函式產生 .profraw 格式的覆蓋率資料。

覆蓋率仍處於實驗階段,需要 Rust Nightly,可能不可靠,並且隨時可能發生重大變更。

啟用功能

若要啟用此功能,您需要啟用 cfg(wasm_bindgen_unstable_test_coverage)

產生資料

需要存在的 RUSTFLAGS

請確保您正在使用 RUSTFLAGS=-Cinstrument-coverage -Zno-profiler-runtime

由於目前 llvm-cov 的限制,我們無法從產生的 .wasm 檔案中收集分析符號。相反地,我們可以透過使用 Clang,從 LLVM IR 中使用 --emit=llvm-ir 來取得這些符號。Clang 或任何 LLVM 工具的使用必須符合 Rust 使用的 LLVM 版本。

測試執行器的引數

執行測試執行器 時,可以使用以下環境變數來控制覆蓋率輸出

  • WASM_BINDGEN_UNSTABLE_TEST_PROFRAW_OUT 用於控制 profraw 的檔案名稱或其放置的目錄。如果例如在工作區中執行測試,則可能需要提供完整路徑。
  • WASM_BINDGEN_UNSTABLE_TEST_PROFRAW_PREFIX 用於在 profraw 檔案中新增自訂前綴。如果您自動連續執行測試,這會很有用。

目標功能

此功能依賴 minicov crate,它為 WebAssembly 提供分析執行時間。它接著使用 cc 將執行時間編譯為 Wasm,而 它目前不支援考量目標功能。使用例如 CFLAGS_wasm32_unknown_unknown="-matomics -mbulk-memory" 來加以考量。

範例

這改編自 Rustc 書籍 中的程式碼,請參閱該書籍以取得更多範例和關於測試覆蓋率的一般資訊。

# Run the tests:
# `--tests` to not run documentation tests, which is currently not supported.
RUSTFLAGS="-Cinstrument-coverage -Zno-profiler-runtime --emit=llvm-ir --cfg=wasm_bindgen_unstable_test_coverage" \
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=wasm-bindgen-test-runner \
cargo +nightly test --tests
# Compile to object files:
# - Extract a list of compiled artifacts from Cargo and filter them with `jq`.
# - Figure out the path to the LLVM IR file corresponding to an artifact.
# - Compile to object file with Clang and store for later usage with `llvm-cov`.
crate_name=name_of_the_tested_crate_in_snake_case
objects=()
IFS=$'\n'
for file in $(
    RUSTFLAGS="-Cinstrument-coverage -Zno-profiler-runtime --emit=llvm-ir --cfg=wasm_bindgen_unstable_test_coverage" \
    cargo +nightly test --tests --no-run --message-format=json | \
    jq -r "select(.reason == \"compiler-artifact\") | (select(.target.kind == [\"test\"]) // select(.target.name == \"$crate_name\")) | .filenames[0]"
)
do
    if [[ ${file##*.} == "rlib" ]]; then
        base=$(basename $file .rlib)
        file=$(dirname $file)/${base#"lib"}.ll
    else
        file=$(dirname $file)/$(basename $file .wasm).ll
    fi

    output = $(basename $file .ll).o
    clang-19 $file -Wno-override-module -c -o $output
    objects+=(-object $output)
done
# Merge all generated raw profiling data.
llvm-profdata-19 merge -sparse *.profraw -o coverage.profdata
# Produce test coverage data in the HTML format and pass the object files we generated earlier.
llvm-cov-19 show -show-instantiations=false -Xdemangler=rustfilt -output-dir coverage -format=html -instr-profile=coverage.profdata ${objects[@]} -sources src

歸屬

這些方法最初由 Hacken OÜ 開創,另請參閱 他們的指南