问题描述
我尝试添加环境变量检查,但这不起作用。我猜 cargo test
会过滤掉环境变量。
// 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'
如何运行除一个之外的所有工作区测试?
解决方法
排除测试
运行 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_package
和 my_test
替换为其适当的名称:
测试所有,但排除my_package
cargo test --workspace --exclude my_package
然后测试 my_package
本身,通过添加 --skip my_test
排除特定测试:
cargo test --package my_package -- --skip my_test
有关更多选项,请参阅:
默认排除测试
或者,您可以将 #[ignore]
属性添加到默认情况下不应运行的测试。如果您愿意,您仍然可以单独运行它们:
src/lib.rs
#[test]
#[ignore]
fn test_add() {
assert_eq!(add(21,42);
}
使用 cargo test -- --ignored
运行测试:
running 1 test
test tests::test_add ... ok
如果您使用 Rust >= 1.51
并希望运行所有测试,包括那些标有 #[ignore]
属性的测试,您可以通过 --include-ignored
。