【问题标题】:How to recursively test all crates under a directory?如何递归测试目录下的所有箱子?
【发布时间】:2017-06-17 16:01:14
【问题描述】:

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

有没有一种方便的方法来递归运行 cargo test ?

【问题讨论】:

  • 很高兴看到我不是唯一一个希望在同一个存储库中捆绑多个 crate 的人。我很惊讶货物似乎对此没有更好的支持。

标签: testing rust rust-cargo


【解决方案1】:

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


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

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

脚本:

#!/bin/bash

# exit on first error, see: http://stackoverflow.com/a/185900/432509
error() {
    local parent_lineno="$1"
    local message="$2"
    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

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

【讨论】:

    【解决方案2】:

    您可以使用 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 的目录(对于 crates 来说是一个不错的选择)并在其中运行 cargo test。

    【讨论】:

      【解决方案3】:

      我现在无法对其进行测试,但我相信您可以使用 cargo test --all 进行测试。

      【讨论】:

      • 这个选项实际上在今天才登陆稳定的 Rust 1.15 版本!
      • 等待的人会有好事。
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-12-31
        • 2011-02-04
        • 2020-08-19
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 2020-02-10
        • 2016-06-06
        • 2018-11-15
        相关资源
        最近更新 更多