gpt4 book ai didi

rust - 如何在二进制项目中使用 src 文件夹外部的模块,例如用于集成测试或基准测试?

转载 作者:行者123 更新时间:2023-12-03 11:38:43 24 4
gpt4 key购买 nike

我的项目的路径结构如下:

demo
├── benches
│   └── crypto_bench.rs
├── src
│   ├── main.rs
│   └── crypto.rs
├── Cargo.lock
└── Cargo.toml
crypto.rs包含一个结构 Crypto与实现。 crypto.rs引用自 main.rs使用 mod crypto;
如何使用 crypto.rs来自 crypto_bench.rs在长椅文件夹里面?

我已经尝试过 extern crate 的各种变体, mod , superuse .
我可以在网上找到的所有示例都是针对带有 lib.rs 的图书馆项目的。当使用带有 main.rs 的项目时,这些“导入”不起作用文件。

最佳答案

这是一个字面的答案,但是 实际上不要使用这个 !

#![feature(test)]
extern crate test;

#[path = "../src/foo.rs"] // Here
mod foo;

#[bench]
fn bencher(_: &mut test::Bencher) {
println!("{:?}", foo::Thang);
}

事实上,这很可能不起作用,因为您的代码在 foo.rs需要来自其他文件的支持代码,这些文件不会被包含在内。

而不是这样做,只需创建一个库。你有一个库的纯粹定义——一段想要在两个不同的可执行文件中使用的代码。您不必放弃拥有可执行文件甚至创建单独的目录(参见 Rust package with both a library and a binary?),但创建可重用代码是编写好代码的关键组成部分。

您的最终状态将类似于:

demo
├── Cargo.lock
├── Cargo.toml
├── benches
│   └── crypto_bench.rs
├── benchmarks
└── src
├── bin
│   └── main.rs
├── crypto.rs
└── lib.rs

将可重用代码移动到库中:

src/lib.rs
pub mod crypto;

src/crypto.rs
pub struct Crypto;
impl Crypto {
pub fn secret() {}
}

然后从基准和二进制文件中导入您的库:

长凳/crypto_bench.rs
#![feature(test)]

extern crate test;

use demo::crypto::Crypto;
use test::Bencher;

#[bench]
fn speedy(b: &mut Bencher) {
b.iter(|| Crypto::secret());
}

src/bin/main.rs
use demo::crypto::Crypto;

fn main() {
Crypto::secret();
eprintln!("Did the secret thing!");
}

然后,您可以以不同的方式运行它:

$ cargo build
Compiling demo v0.1.0 (/private/tmp/example)
Finished dev [unoptimized + debuginfo] target(s) in 0.51s

$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/main`
Did the secret thing!

$ cargo +nightly bench
Compiling demo v0.1.0 (/private/tmp/example)
Finished release [optimized] target(s) in 0.70s
Running target/release/deps/my_benchmark-5c9c5716763252a0

running 1 test
test speedy ... bench: 1 ns/iter (+/- 0)

test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured; 0 filtered out

也可以看看:
  • Rust package with both a library and a binary?
  • What is an idiomatic way to have shared utility functions for integration tests and benchmarks?
  • Can I make an object public for integration tests and/or benchmarks only?
  • Cannot import a module in an integration test
  • 关于rust - 如何在二进制项目中使用 src 文件夹外部的模块,例如用于集成测试或基准测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64722892/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com