运行 `cargo test --workspace` 并排除一项测试

M. *_*ard 3 testing rust rust-cargo exclude-constraint

我有一个带几个板条箱的工作区。我需要排除一个特定的测试。

我尝试添加环境变量检查,但这不起作用。我想过cargo test滤掉环境变量。

// package1/src/lib.rs

// ...

#[cfg(test)]
mod tests {

    #[test]
    fn test1() {
        if std::env::var("CI").is_ok() {
            return;
        }
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试--exclude使用各种选项传递参数,但它们都不起作用:

  • cargo test --workspace --exclude test1
  • cargo test --workspace --exclude tests:test1
  • cargo test --workspace --exclude tests::test1
  • cargo test --workspace --exclude '*test1'
  • cargo test --workspace --exclude 'tests*test1'
  • cargo test --workspace --exclude package1 这将跳过包中的所有测试。
  • cargo test --workspace --exclude 'package1*test1'

如何运行除一个之外的所有工作区测试?

Jas*_*son 8

排除测试

运行的帮助文件cargo test -- --help列出了有用的选项:

--skip FILTER   Skip tests whose names contain FILTER (this flag can
                be used multiple times)
Run Code Online (Sandbox Code Playgroud)

关于--after test,请参见:

源代码/库.rs

fn add(a: u64, b: u64) -> u64 {
    a + b
}

fn mul(a: u64, b: u64) -> u64 {
    a * b
}

#[cfg(test)]
mod tests {
    use super::{add, mul};

    #[test]
    fn test_add() {
        assert_eq!(add(21, 21), 42);
    }

    #[test]
    fn test_mul() {
        assert_eq!(mul(21, 2), 42);
    }
}
Run Code Online (Sandbox Code Playgroud)

运行上面的 withcargo test -- --skip test_mul将给出以下输出:

running 1 test
test tests::test_add ... ok
Run Code Online (Sandbox Code Playgroud)

排除特定包中的测试

如果要排除工作区中包的特定测试,可以按以下方式进行,替换my_package和 并my_test使用其适当的名称:

测试所有,但排除 my_package

cargo test --workspace --exclude my_package
Run Code Online (Sandbox Code Playgroud)

然后测试my_package自己,通过添加排除特定测试--skip my_test

cargo test --package my_package -- --skip my_test
Run Code Online (Sandbox Code Playgroud)

有关更多选项,请参阅:

默认排除测试

或者,您可以将该#[ignore]属性添加到默认情况下不应运行的测试。如果您愿意,您仍然可以单独运行它们:

源代码/库.rs

#[test]
#[ignore]
fn test_add() {
    assert_eq!(add(21, 21), 42);
}
Run Code Online (Sandbox Code Playgroud)

运行测试使用cargo test -- --ignored

running 1 test
test tests::test_add ... ok
Run Code Online (Sandbox Code Playgroud)

如果你正在使用 Rust >=1.51并且想要运行所有测试,包括那些用#[ignore]属性标记的测试,你可以通过--include-ignored.