如何在Rust中在测试和基准测试之间共享代码?

3
我使用文档中提到的“bench”和Rust nightly开始使用Rust编写基准测试。为了在测试和基准测试之间共享代码,我添加了Option<&mut Bencher>,并直接运行代码块或通过传递bencher来运行(“src/lib.rs”)。
fn block_requests(bencher_option: Option<&mut Bencher>, ...) {
    ...

    let mut block = || {
       ... // shared
    }

    match bencher_option {
            // regular test
            None => block(),

            // benchmark
            Some(bencher) => {
                bencher.iter(block);
            }
        }
    ...
}

// call from test
#[test]
fn test_smth() {
    block_requests(None, &requests, &mut matcher);
}


// call from benchmark
#[bench]
fn bench_smth(b: &mut Bencher) {
    block_requests(Some(b), &requests, &mut matcher);
}


现在我想使用Rust 稳定版 进行基准测试。 由于"bencher" crate已经3年没有更新了,似乎"criterion" crate是默认选择。为此,我需要将代码移动到"./benches/my_benchmark.rs"。 如何在测试和基准测试之间共享block_requests(..)

use mycrate::block_requests - undefined
1个回答

2
"

tests/benches/src/main.rssrc/bin/*.rs的工作方式相同:它们是独立的二进制箱。这意味着它们必须按名称引用库箱中的项,并且这些项必须是可见的。

因此,您需要进行更改。

"
fn block_requests(bencher_option: Option<&mut Bencher>, ...) {

为了使其公开,您可能还需要添加#[doc(hidden)],以便您的库文档不包含测试助手:
#[doc(hidden)]
pub fn block_requests(bencher_option: Option<&mut Bencher>, ...) {

然后,在您的测试和基准测试中,使用它,通过给出您的crate的名称。
use my_library_crate_name::block_requests;

fn bench_smth(...) {...}

在这里您不能使用 use crate::block_requests,因为关键字 crate 指的是基准二进制箱而不是库箱。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接