如何递归测试目录下的所有板条箱?

How to recursively test all crates under a directory?

有些项目包含多个 crate,这使得 运行 在每个 crate 中手动进行所有测试很麻烦。

有没有方便的递归方式 运行 cargo test

您可以使用 shell 脚本。根据this answer,这个

find . -name Cargo.toml -printf '%h\n'

将打印出包含 Cargo.toml 的目录,因此,将其与标准 shell 实用程序的其余部分组合在一起会产生我们

for f in $(find . -name Cargo.toml -printf '%h\n' | sort -u); do
  pushd $f > /dev/null;
  cargo test;
  popd > /dev/null;
done

这将遍历所有包含 Cargo.toml(板条箱的好选择)和 运行 cargo test 的目录。

更新:由于添加此答案 1.15 已发布,添加 cargo test --all 会将其与自定义脚本进行比较。


此 shell-script 在 git 存储库上对包含 Cargo.toml 文件的所有目录递归运行测试(很容易为其他 VCS 编辑)。

  • 出现第一个错误时退出。
  • 使用nocapture所以显示标准输出
    (取决于个人喜好,易于调整).
  • 使用 RUST_BACKTRACE 集运行测试,以获得更有用的输出。
  • 分两步构建和运行
    (1.14 稳定版中 this bug 的解决方法)。
  • 可选 CARGO_BIN 环境变量来覆盖 cargo 命令
    (如果你想使用 cargo-wrapper 例如 cargo-out-of-source builder 就很方便)。

脚本:

#!/bin/bash

# exit on first error, see: 
error() {
    local parent_lineno=""
    local message=""
    local code="${3:-1}"
    if [[ -n "$message" ]] ; then
        echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
    else
        echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
    fi
    exit "${code}"
}
trap 'error ${LINENO}' ERR
# done with trap

# support cargo command override
if [[ -z $CARGO_BIN ]]; then
    CARGO_BIN=cargo
fi

# toplevel git repo
ROOT=$(git rev-parse --show-toplevel)

for cargo_dir in $(find "$ROOT" -name Cargo.toml -printf '%h\n'); do
    echo "Running tests in: $cargo_dir"
    pushd "$cargo_dir"
    RUST_BACKTRACE=0 $CARGO_BIN test --no-run
    RUST_BACKTRACE=1 $CARGO_BIN test -- --nocapture
    popd
done

感谢@набиячлэвэли的回答,这是一个扩展版本。

我现在无法测试,但我相信你可以使用 cargo test --all 来测试。

您可以使用货物工作区功能。 This crate 集合将它与 Makefile 结合使用,后者可用于单独编译每个板条箱。

(工作区功能有助于避免多次编译公共依赖项)