有人可以帮助我理解这一点吗?
我有一个 rust 项目,它有一个 lib 箱:
my_crate_2
。这是它的文件结构:
my_project/
├── Cargo.toml
└── src/
└── main.rs
my_crate_2/
├── Cargo.toml
|-- build.rs
└── src/
└── lib.rs
|__ tests/
|__my_crate_2.rs
在
my_crate_2/tests/my_crate_2.rs
中是我的集成测试。
在集成测试中,我想提取其中的环境变量
OUT_DIR
。 根据货物文件,OUT_DIR
应由Cargo
设置。
一个简单的测试:
#[cfg(test)]
pub mod tests {
use my_crate_2::*;
#[test]
fn test_add() {
// I need to use env var `OUT_DIR` here
// err: called `Result::unwrap()` on an `Err` value: NotPresent
// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
let out_dir = std::env::var("OUT_DIR").unwrap();
println!("OUT_DIR is {}", out_dir);
assert_eq!(add(2, 5), 7);
}
}
我在
cargo test -- --nocapture
目录中使用 my_crate_2/
运行了所有集成测试,并且测试通过了(OUT_DIR
存在)。
cargo test -- --nocapture
Finished test [unoptimized + debuginfo] target(s) in 0.00s
Running unittests src/lib.rs (target/debug/deps/my_crate_2-e7e58afb09a93b31)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/my_crate_2.rs (target/debug/deps/my_crate_2-9892d21b51d30121)
running 1 test
OUT_DIR is /workspaces/workspace/my_crate_2/target/debug/build/my_crate_2-443e542c04636da9/out
test tests::test_add ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests my_crate_2
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
但是,如果我只运行特定测试:
cargo test --package my_crate_2 --test my_crate_2 -- tests::test_add --nocapture
,测试将失败,并显示 OUT_DIR
env var not found。
cargo test --package my_crate_2 --test my_crate_2 -- tests::test_add --nocapture
Finished test [unoptimized + debuginfo] target(s) in 0.00s
Running tests/my_crate_2.rs (target/debug/deps/my_crate_2-9892d21b51d30121)
running 1 test
thread 'tests::test_add' panicked at tests/my_crate_2.rs:10:48:
called `Result::unwrap()` on an `Err` value: NotPresent
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
test tests::test_add ... FAILED
任何人都可以帮助我理解为什么 Cargo 在针对单个测试时没有设置
OUT_DIR
吗?我该如何解决它?
我在这里创建了一个沙箱。你可以尝试一下。谢谢!
此问题已报告给 GitHub 上的 Cargo。现在应该修复了。 https://github.com/rust-lang/cargo/issues/13127#event-11421120844