为集成测试和基准测试共享实用程序功能的惯用方式是什么? [英] What is an idiomatic way to have shared utility functions for integration tests and benchmarks?
问题描述
我有一个带有集成测试(在/tests
目录中)和基准(在/benches
目录中)的Rust项目.在测试和基准测试中,我需要几个实用程序功能,但它们与我的板条箱本身无关,所以我不能只将它们放在/utils
目录中.
I have Rust project with both integration tests (in the /tests
dir) and benchmarks (in the /benches
dir). There are a couple of utility functions that I need in tests and benches, but they aren't related to my crate itself, so I can't just put them in the /utils
dir.
处理这种情况的惯用方法是什么?
What is idiomatic way to handle this situation?
推荐答案
创建共享板条箱(首选)
如评论中所述,创建一个新的箱子.您不必将板条箱发布到crates.io .只需将其保留为项目中的本地未发布板条,然后将其标记作为仅开发依赖项:
Create a shared crate (preferred)
As stated in the comments, create a new crate. You don't have to publish the crate to crates.io. Just keep it as a local unpublished crate inside your project and mark it as a development-only dependency:
.
├── Cargo.toml
├── src
│ └── lib.rs
├── tests
│ └── integration.rs
└── utilities
├── Cargo.toml
└── src
└── lib.rs
Cargo.toml
# ...
[dev-dependencies]
utilities = { path = "utilities" }
utilities/src/lib.rs
pub fn shared_code() {
println!("I am shared code");
}
tests/integration.rs
extern crate utilities;
#[test]
fn a_test() {
utilities::shared_code();
}
仅测试模块
您可以将模块放置在板条箱中,该模块仅在通过特定功能时才编译.这与用于单元测试的概念相同.这具有可以访问您的库代码内部的优点.这样做的缺点是,每次运行代码时都需要传递标志.
A test-only module
You could place a module inside your crate that is only compiled when a specific feature is passed. This is the same concept used for unit tests. This has the advantage that it can access internals of your library code. It has the disadvantage that you need to pass the flag each time you run the 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")
}
}
tests/integration.rs
extern crate the_library;
#[test]
fn a_test() {
the_library::test_utilities::shared_code();
}
执行
cargo test --features=test-utilities
使用来自任意文件路径的模块
这对我来说很丑,而且确实超出了正常范围.
Use a module from an arbitrary file path
This is just ugly to me, and really goes out of the normal path.
utilities.rs
pub fn shared_code() {
println!("This is just sitting out there");
}
tests/integration.rs
#[path = "../utilities.rs"]
mod utilities;
#[test]
fn a_test() {
utilities::shared_code();
}
另请参阅:
这篇关于为集成测试和基准测试共享实用程序功能的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!