Tests and cargo test
The café building has one more place — the inspection desk at the exit. Before a dish goes out to a guest, the inspector checks it against the order. If something is wrong, the dish goes no further, and the cook finds out at once.
Tests do the same job for code. Take a function that computes the average of two numbers:
fn average(a: u32, b: u32) -> u32 {
(a + b) / 2
}
fn main() {
println!("{}", average(2, 4)); // 3
}You ran the program, saw 3 and made sure everything is right. A month later someone edits the function and accidentally deletes the parentheses. Running every function after every edit and checking the output by eye takes long, and a mistake can slip through unnoticed. A test does that check by itself, in a second.
A function with #[test]
A test is a function with no parameters marked with the attribute #[test]. By custom, tests go into a module tests at the end of the same file:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn average_of_two() {
assert_eq!(average(2, 4), 3);
}
}Let's go through it line by line:
#[cfg(test)]means the module is built only for tests; it never gets intocargo runor the finished program.mod testsis an ordinary module, the same kind of room askitchen.use super::*;is a signpost to everything in the parent module:supermeans the module one level up. Tests see private functions too, since a nested module sees the contents of the outer one.#[test]marks the function as a test.assert_eq!(average(2, 4), 3)compares two values and panics if they are not equal.
A test passes if the function reaches its end, and fails if it panics. Interviewers often ask you to state this rule.
Here the inspector picture is inexact. In the café the inspector stands at the exit all the time, but tests work only under cargo test. In cargo run the tests module does not exist at all, and cargo test does not run main.
Running cargo test
The command cargo test builds the project together with its tests and runs every function marked #[test]. After the build lines it prints a report:
running 1 test
test tests::average_of_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00srunning 1 test— one test was found.test tests::average_of_two ... ok— the test is named by its path through the module, and it passed.test result: ok. 1 passed; 0 failed— the total: one passed, none failed.
When a test fails
Now delete the parentheses: a + b / 2. Division happens before addition, and average(2, 4) returns 2 + 2, that is, 4. cargo test reports:
running 1 test
test tests::average_of_two ... FAILED
failures:
---- tests::average_of_two stdout ----
thread 'tests::average_of_two' (179529) panicked at src/main.rs:15:9:
assertion `left == right` failed
left: 4
right: 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::average_of_two
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00spanicked at src/main.rs:15:9is the file, line and column of the check; the number in parentheses before it changes from run to run.leftis the first value inassert_eq!, the one the function returned.rightis the second, expected value.FAILEDin the total: the test caught the bug before a user did.
When there are many tests, a failed one does not stop the rest: each runs on its own, and the report lists every failure.
Assertion macros
assert_eq!
assert_eq!(a, b) requires the values to be equal and prints both when it fails. From left and right you see at once what the function returned. The opposite macro, assert_ne!(a, b), requires them to differ.
assert!
assert!(condition) panics if the condition is false: assert!(average(2, 3) == 2). It suits yes-or-no checks, such as assert!(n > 0). It shows no values when it fails, so assert_eq! is handier for comparisons.
Both macros are ordinary: they work in any function, main included, and in any build, not only under cargo test.
A test that expects a panic
Sometimes the right behavior for a function is a panic. Integer division by zero panics, and a function that splits a bill among guests must refuse to work when there are no guests. The attribute #[should_panic] flips the rule: such a test passes only if the function panicked.
fn share(bill: u32, people: u32) -> u32 {
bill / people
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn nobody_pays() {
share(100, 0);
}
}cargo test prints test tests::nobody_pays - should panic ... ok. If share(100, 0) returned a number without a panic, the test would fail with the note note: test did not panic as expected.
Common mistake
People think assert_eq! works only in tests, and that in a normal program the check is skipped or prints a warning and moves on:
fn average(a: u32, b: u32) -> u32 {
a + b / 2
}
fn main() {
assert_eq!(average(2, 4), 3); // ✗
println!("checked");
}assertion `left == right` failed
left: 4
right: 3The program builds, but at run time it panics on the check, and checked is never printed. The left and right lines are part of the panic message, not the program's normal output. Inside a test the same panic marks the test as failed, and in main it stops the program.
Key points
- A test is a function with
#[test]; tests go into#[cfg(test)] mod testswithuse super::*;and run withcargo test. - A test passes if it reaches its end and fails if it panics;
#[should_panic]flips that rule. assert_eq!showsleftandrightwhen it fails, andassert!checks a condition.assert_eq!works in any function and in any build: when the values differ, the program panics.