用于集成测试和基准测试的共享实用函数的惯用方法是什么?

问题描述 投票:0回答:3

我有 Rust 项目,其中包含集成测试(在

/tests
目录中)和基准测试(在
/benches
目录中)。我在测试和工作台中需要一些实用函数,但它们与我的板条箱本身无关,所以我不能只是将它们放在
/utils
目录中。

处理这种情况的惯用方法是什么?

testing rust benchmarking rust-cargo
3个回答
42
投票

创建一个共享板条箱(首选)

如评论中所述,创建一个新箱子。您不必将箱子发布到 crates.io。只需将其保留为项目中本地未发布的板条箱,并将其标记为仅开发依赖项

这最适合与 Cargo 解析器版本 2 一起使用。为了获得更好的性能,请考虑使用 Cargo 工作区

.
├── 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");
}

测试/集成.rs

extern crate utilities;

#[test]
fn a_test() {
    utilities::shared_code();
}

仅测试模块

您可以将一个模块放入您的板条箱中,该模块仅在通过特定功能时才进行编译。这与单元测试使用的概念相同。这样做的优点是它可以访问库代码的内部。它的缺点是每次运行代码时都需要传递标志。

这最适合与 Cargo 解析器版本 2 一起使用。

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")
    }
}

测试/集成.rs

extern crate the_library;

#[test]
fn a_test() {
    the_library::test_utilities::shared_code();
}

执行

cargo test --features=test-utilities

这最适合与 Cargo 解析器版本 2 一起使用。

使用任意文件路径中的模块

这对我来说太丑了,而且真的偏离了正常的道路。

utilities.rs

pub fn shared_code() {
    println!("This is just sitting out there");
}

测试/集成.rs

#[path = "../utilities.rs"]
mod utilities;

#[test]
fn a_test() {
    utilities::shared_code();
}

另请参阅:


7
投票

您可以将这些实用函数添加到主箱内的

pub
模块中,并使用
#[doc(hidden)]
#![doc(hidden)]
属性将它们隐藏在文档生成器中。额外的评论将引导读者了解他们为什么在那里。


2
投票

虽然这对基准测试没有帮助,但我来这里寻找一种通过多个集成测试来做到这一点的方法,后来发现您可以对集成测试执行以下操作:

具有公共代码的模块遵循普通模块规则,因此可以创建公共模块为tests/common/mod.rs。

来源:https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html

© www.soinside.com 2019 - 2024. All rights reserved.