【问题标题】:Running Rust tests inside a separate file在单独的文件中运行 Rust 测试
【发布时间】:2022-01-15 22:44:12
【问题描述】:

我是 Rust 的绝对菜鸟,Rust 书似乎没有涵盖我的单元测试特定用例。

我正在为我的大学学位实施The Computer Language Benchmarks Game。为了保持一致,我决定每种语言和算法实现都应该遵守以下目录结构:

root
|
|__ language_1
|   |
|   |__ algorithm_1
|   |   |
|   |   |__ algorithm_1          <-- The algorithm logic.
|   |   |
|   |   |__ algorithm_1_tests    <-- Tests.
|   |   |
|   |   |__ algorithm_1_run      <-- A `main` function to execute the algorithm logic.
|   |
|   |__ algorithm_2
|
|__ language_2
...

我需要这种一致性,因为我稍后会编写一个 bash 脚本来遍历这个目录树结构,并且能够轻松编译(如果需要)和运行必要的文件。

我目前正在学习和编写 Rust 编程语言的算法。我将算法创建为库文件,并有一个单独的文件调用库文件并执行其中的函数。这很好用。

我的问题在于测试。我希望有一个包含所有测试的单独文件,导入原始算法逻辑文件,并调用(和断言)函数。

为了更清楚地说明这一点,我将提供一个我正在运行的模拟示例:

root
|
|__ rust
|   |
|   |__ algorithm
|   |   |
|   |   |__ algorithm.rs
|   |   |
|   |   |__ algorithm_tests.rs
|   |   |
|   |   |__ algorithm_run.rs

algorithm.rs

fn is_even(a: u32) -> bool {
    return a % 2 == 0;
}

algorithm_run.rs

mod algorithm;

fn main() {
    let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    for number in numbers {
        algorithm::is_even(number);
    }

algorithm_tests.rs

mod algorithm;

#[test]
fn test_is_even_returns_true_for_even_numbers() {
    let even_numbers = [2, 4, 6, 8, 10]
    for number in even_numbers {
        assert_eq!(true, algorithm::is_even(number));
    }
}

这是使用以下命令执行和运行的 $ rustc algorithm_run.rs -o algorithm &amp;&amp; ./algorithm

我需要进行哪些命令或修改才能运行测试?

【问题讨论】:

  • 如果你真的想学习 Rust 开发,我强烈建议不要使用这个目录和运行/测试结构。典型的开发不直接调用rustc,而是使用cargo。它可以管理构建工件、构建配置文件、外部依赖项、增量编译等等。如果您希望多种语言在脚本编写中表现相同,我建议使用 makefile。
  • 我从 Rust 书对cargo new 命令和src/* 结构的强调中了解到,但这是我为我的项目设定的要求,并且会像我一样让事情变得更容易旨在测试多种语言,因此首选一致的编译/运行方式。由于我没有那么有经验,所以没有研究 makefile tbh,但会记住!

标签: unit-testing testing rust


【解决方案1】:

fwiw 基准测试游戏project website 提供生成文件脚本来构建不同的测试程序并对程序进行测量。

https://salsa.debian.org/benchmarksgame-team/benchmarksgame/-/tree/master/bencher

【讨论】:

  • 这实际上是帮助我设置我的存储库(向创建者发送了一封电子邮件,他们非常友好地允许我访问该存储库)。 Albite,这是一个相当复杂的基础设施,我将看看他们是如何做到的。我认为 Docker 发挥了作用,因为我能够运行他们的基准测试,即使我没有安装其中一半的语言和他们的编译器。
【解决方案2】:

您可以通过--test 与测试工具一起编译:

$ rustc --test algorithm_tests.rs && ./algorithm_tests

running 1 test
test test_is_even_returns_true_for_even_numbers ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

【讨论】:

  • 完美运行!这是在官方文档中吗?我找不到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 2019-08-26
  • 2019-07-02
  • 2017-12-25
  • 1970-01-01
  • 2018-02-08
相关资源
最近更新 更多