运行 `cargo test --workspace` 命令并排除一个测试。

8
我有一个带有多个板条箱的工作空间。 我需要排除特定的测试。
我尝试添加环境变量检查,但这并不起作用。 我猜过滤掉了环境变量。
// package1/src/lib.rs

// ...

#[cfg(test)]
mod tests {

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

然后我尝试使用不同的选项传递--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'
如何运行除一个之外的所有工作区测试?
1个回答

23

排除一个测试

通过运行cargo test -- --help,可以列出有用的选项:

--skip FILTER   Skip tests whose names contain FILTER (this flag can
                be used multiple times)

关于test之后的--,请参见:

src/lib.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);
    }
}

使用cargo test -- --skip test_mul运行上述命令将得到以下输出:

running 1 test
test tests::test_add ... ok

在特定包中排除一个测试

如果您想在工作区中的某个包中排除特定的测试,可以按照以下方式进行操作,将my_packagemy_test分别替换为它们正确的名称:

测试所有,但排除my_package

cargo test --workspace --exclude my_package

然后使用--skip my_test来排除特定的测试,测试my_package本身:

cargo test --package my_package -- --skip my_test

了解更多选项,请参见:

默认情况下排除测试

或者,您可以向不应默认运行的测试添加 #[ignore] 属性。如果您希望这样做,仍然可以单独运行它们:

src/lib.rs

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

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

running 1 test
test tests::test_add ... ok

如果您正在使用 Rust >= 1.51 并且想运行所有测试,包括那些标记有 #[ignore] 属性的测试,您可以传递 --include-ignored 参数。


有没有办法在 -- --skip 参数中指定包或者板条箱的名称? - M. Leonhard
1
据我所知,您将不得不将其拆分为两个命令。我已更新帖子以反映这一点。 - Jason
请注意,如果您想将筛选器应用于每个包,则 cargo test --workspace -- --skip FILTER 可以完美地工作。 - Cyrill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接