Thursday, June 26, 2014

Rust note 4: Rust unit tests

Unit tests are a crucial part of "real world" development. Manually testing code in some kind of REPL (which rust no longer has) is time-consuming and cannot be verified across distributions of your code. Luckily, rust provides unit testing right inside of its compiler, so you don't even need a third-party solution to bolster your code. Here's how to do it.

The assert! Macro
assert! is a simple concept that can be used in complex ways. It tests to see if a boolean is true, and, if it is, does nothing. Otherwise, it will call the fail!() macro, causing the program to terminate.

The test function
So, before we can test anything we need functions.

fn add_one(x: int) -> int { x + 1 }
fn subtract_one(x: int) -> int { x - 1}


Obviously, add_one(1) will be 2. And subtract_one(1) is zero. So, we put these assertions in a function called "test", which takes no arguments and returns nothing.

#[test]
fn test(){
  assert!(add_one(1) == 2, "It's all gone wrong!");
  assert!(subtract_one(1) == 0);
  assert!(add_one(subtract_one(1)) == 1);
}

The test pragma ("#[test]") will tell rustc that this is a test. The function that tests the code can be named anything, as long as it returns nothing and takes no arguments. The tests inside of the function are just standard boolean expressions, and an optional message for if the code fails ("It's all gone wrong!"). Now, compile put this in a file and compile it with rustc --test file.rs.  

Run the resulting executable. It should say "test result: ok. 1 passed, 0 failed; 0 ignored; 0 measured". The number of passed tests refers to how many #[test] pragmas are found. There can be a variable number of tests, so try to group up tests of a related domain under a single function. 

Just out of curiosity, what would happen if you made the test fail? Well, it's not pretty. 

No comments:

Post a Comment