產生涵蓋範圍資料
您可以要求執行器從標記為 #[wasm_bindgen_test]
的函式產生 .profraw
格式的涵蓋範圍資料。
涵蓋範圍仍處於實驗性狀態,需要 Rust Nightly,可能不可靠,並且隨時可能發生重大變更。
啟用此功能
若要啟用此功能,您需要啟用 cfg(wasm_bindgen_unstable_test_coverage)
。
產生資料
需要存在的 RUSTFLAGS
請確保您使用 RUSTFLAGS=-Cinstrument-coverage -Zno-profiler-runtime
。
由於 llvm-cov
目前的限制,我們無法從產生的 .wasm
檔案收集分析符號。相反地,我們可以藉由使用 Clang,從帶有 --emit=llvm-ir
的 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