我有两个集成测试(在/tests
目录)和基准(在/benches
目录)的Rust项目。在测试和工作台中需要一些实用功能,但它们与我的箱子本身无关,所以我不能将它们放在/utils
目录中。什么是用于集成测试和基准测试的共享实用程序功能的惯用方式?
什么是地道的方式来处理这种情况?
我有两个集成测试(在/tests
目录)和基准(在/benches
目录)的Rust项目。在测试和工作台中需要一些实用功能,但它们与我的箱子本身无关,所以我不能将它们放在/utils
目录中。什么是用于集成测试和基准测试的共享实用程序功能的惯用方式?
什么是地道的方式来处理这种情况?
正如评论中所述,创建一个新的箱子。您不必将箱子发布到crates.io。只是keep it as a local unpublished crate项目内,其标记为development-only dependency:
.
├── Cargo.toml
├── src
│ └── lib.rs
├── tests
│ └── integration.rs
└── utilities
├── Cargo.toml
└── src
└── lib.rs
Cargo.toml
# ...
[dev-dependencies]
utilities = { path = "utilities" }
公用事业/ src目录/ lib.rs
pub fn shared_code() {
println!("I am shared code");
}
测试/ integration.rs
extern crate utilities;
#[test]
fn a_test() {
utilities::shared_code();
}
您可以将您的箱子里面一个模块时,一个特定的功能是通过了只编译。这与单元测试使用的概念相同。这有一个好处,它可以访问你的库代码的内部。它的缺点是每次运行代码时都需要传递该标志。
Cargo.toml
# ...
[features]
test-utilities = []
的src/lib.rs
#[cfg(feature = "test-utilities")]
pub mod test_utilities {
pub fn shared_code() {
println!("I'm inside the library")
}
}
测试/ integration.rs
extern crate the_library;
#[test]
fn a_test() {
the_library::test_utilities::shared_code();
}
执行
cargo test --features=test-utilities
这只是丑对我来说,真的超出正常路径的使用的模块。
公用事业。RS
pub fn shared_code() {
println!("This is just sitting out there");
}
测试/ integration.rs
#[path = "../utilities.rs"]
mod utilities;
#[test]
fn a_test() {
utilities::shared_code();
}
只需确认,“仅测试模块”解决方案只适用于库而不适用于二进制文件,对吗? ('extern crate the_library;'如果'the_library'已经使用'cargo new --bin'创建,则不能找到) – jean553
@ jean553 yes;只有图书馆的箱子可以被其他箱子重复使用。 – Shepmaster
好的,谢谢你的确认 – jean553
您可以将这些实用功能添加到主箱子中的pub
-模块,并使用#[doc(hidden)]
或#![doc(hidden)]
属性将它们从文档生成器中隐藏起来。额外的评论将指导读者为什么他们在那里。
也许你可以做一个外部箱子,如果你会重用他们? – Boiethios
这不是通用的功能,而只是与这个项目相关的帮手。所以我不认为,这将是很好的解决方案。 – Constantine