我目前正在研究一个Rust 项目,该项目有一个库目标和一个二进制目标。
该库定义了两种恐慌处理程序,一种用于生产使用,另一种用于测试,它们使用 #[cfg(test)] 属性进行条件编译。这对于单元测试 src/lib.rs 来说效果很好,但是一旦在tests/(或 src/main.rs)中进行集成测试,“生产”恐慌处理程序就会被链接到,即在这些情况下,lib。 rs 使用 test=false 进行编译。
有什么方法可以防止/配置它吗?
使用以下目录结构可以最低程度地重现这一点:
Cargo.toml
src/lib.rs
src/main.rs
Run Code Online (Sandbox Code Playgroud)
清单如下所示:
# Cargo.toml
...
[lib]
name = "kernel"
[[bin]]
path = "src/main.rs"
name = "titanium"
Run Code Online (Sandbox Code Playgroud)
二进制代码:
// main.rs
fn main() {
println!("Hello, world!");
}
#[test]
fn it_works() {
assert_eq!(kernel::hello(), "Hello!".to_string());
}
Run Code Online (Sandbox Code Playgroud)
...对于图书馆:
// lib.rs
#[cfg(test)]
pub fn hello() -> String {
"Hello!".to_string()
}
#[cfg(not(test))]
pub fn hello() -> String {
"Goodbye!".to_string()
}
#[test]
fn it_works() {
assert_eq!(hello(), "Hello!".to_string())
}
Run Code Online (Sandbox Code Playgroud)
回答 事实上,上述行为对于大约 …