Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively test all crates under a directory?

Some projects include multiple crates, which makes it a hassle to run all tests manually in each.

Is there a convenient way to recursively run cargo test ?

like image 455
ideasman42 Avatar asked Feb 01 '17 02:02

ideasman42


1 Answers

Update: since adding this answer 1.15 was released, adding cargo test --all, will compare this with a custom script.


This shell-script runs tests recursively on a git repository for all directories containing a Cargo.toml file (easy enough to edit for other VCS).

  • Exits on the first error.
  • Uses nocapture so stdout is shown
    (depends on personal preference, easy to adjust).
  • Runs tests with RUST_BACKTRACE set, for more useful output.
  • Builds and runs in two separate steps
    (workaround for this bug in 1.14 stable).
  • Optional CARGO_BIN environment variable to override the cargo command
    (handy if you want to use a cargo-wrapper such as cargo-out-of-source builder).

Script:

#!/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

Thanks to @набиячлэвэли's answer, this is an expanded version.

like image 58
ideasman42 Avatar answered Sep 18 '22 17:09

ideasman42