为集成测试和基准测试共享实用函数的惯用方法是什么? [英] What is an idiomatic way to have shared utility functions for integration tests and benchmarks?

查看:25
本文介绍了为集成测试和基准测试共享实用函数的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含集成测试(在 /tests 目录中)和基准测试(在 /benches 目录中)的 Rust 项目.我在测试和工作台中需要一些实用函数,但它们与我的 crate 本身无关,所以我不能将它们放在 /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?

推荐答案

创建共享 crate(首选)

如评论中所述,创建一个新的 crate.您不必将 crate 发布到 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.

这最好与 第 2 版一起使用货物解析器.

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

仅供测试的模块

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

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.

这最好与 第 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")
    }
}

tests/integration.rs

extern crate the_library;

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

执行

cargo test --features=test-utilities

这最好与 version 一起使用2 Cargo resolver.

这对我来说太丑了,真的不正常.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆