Home > front end >  Running Rust tests inside a separate file
Running Rust tests inside a separate file

Time:12-12

I'm an absolute noob to Rust, and the Rust book doesn't seem to cover my specific use case for unit tests.

I'm working on implementing The Computer Language Benchmarks Game for my university degree. To be consistent, I have decided that each language and algorithm implementation should abide to the following directory structure:

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
...

I require this consistency because I will later write a bash script to traverse this directory tree structure and be able to easily compile (if needed) and run the necessary files.

I'm currently learning and writing an algorithm in the Rust programming language. I created the algorithm as a library file and have a separate file that calls the library file and executes the function inside. This works fine.

My problem lies with testing. I wish to have a separate file containing all the tests, imports the original algorithm logic file, and calls (and asserts) the functions.

To make this clearer, I'll provide a mock example of what it is I'm running:

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

This is executed and run with the following command $ rustc algorithm_run.rs -o algorithm && ./algorithm

What command or modifications will I need to make to run the tests?

CodePudding user response:

You can pass --test to compile with the test harness:

$ 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
  • Related