Lecture 26 - Tests: writing them, and what to test
Announcements
You have been running tests like this on your projects
Every cargo test --test cp1 ran this, among others:
#[test]
fn push_then_get_numbers() {
let mut v = SlowVec::new();
v.push(1);
v.push(33);
v.push(-5);
assert_eq!(v.get(0), &1);
assert_eq!(v.get(2), &-5);
assert_eq!(v.get(1), &33);
}
What would have happened if you ran cargo test when your get implementation had an off-by-one error in it?
The test's name in red, and then two values: what the get() returned on the left, what the test expected on the right.
Today we'll understand how to write tests like this ourselves.
Learning Objectives
By the end of today, you should be able to:
- Write a unit test with
#[test]and theassertmacros, and run it withcargo test - Predict whether a given test passes or fails, and why
- Name a case that a function's tests miss
- Write a test from a signature and a one-line description
Why write tests?
Everyone's code has bugs. Not writing tests is like not wearing a seatbelt because you think you will never get in an accident.
What we all do at first:
- Write code
- Run it, see if it works
- Fix bugs
- Hope you didn't break something else
With tests:
- Write code
- Write tests
- Run them every time you change anything
- The tests catch when you broke something else
Even better:
- Write tests that determine the behavior you want
- Write code until they pass
That is called test-driven development, and it is how all our projects are set up!
The simplest test
A test is a function with #[test] on it.
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
Run with cargo test:
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed
A real test
// Our code
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
// Our test
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
assert_eq!(add(-1, 1), 0);
assert_eq!(add(0, 0), 0);
}
Three parts:
#[test], which tellscargo testto run it- A name, which is what you will see when it fails
- Assertions: things that must be true
The three asserts
assert!(condition) checks that something is true:
#[test]
fn test_positive() {
let x = 5;
assert!(x > 0);
}
assert_eq!(left, right) checks that two things are equal, and prints both when they are not:
#[test]
fn test_length() {
let v = vec![1, 2, 3];
assert_eq!(v.len(), 3);
}
assert_ne!(left, right) checks that two things differ:
#[test]
fn test_different() {
assert_ne!(String::from("hello"), String::from("world"));
}
All three panic when they fail. Panicking is how a test fails.
Including an error message in assert
Any assert takes a message after the condition. You see it only when the test fails, which is exactly when you want it.
#[test]
fn test_score_in_range() {
let score = calculate_score(&data);
assert!(
score >= 0.0 && score <= 100.0,
"Score should be between 0 and 100, but got: {}",
score
);
}
The same works for assert_eq! and assert_ne!: the two values come first, then the message, then anything the message's {} slots need, in order, the same shape as println!.
#[test]
fn test_round_total() {
let total = round_total(&rolls, player);
assert_eq!(
total,
18,
"wrong total for player {} in round {}",
player,
round
);
}
Where tests live
Convention: a tests module at the bottom of the file they test.
pub fn is_even(n: i32) -> bool {
n % 2 == 0
}
#[cfg(test)]
mod tests {
use super::*; // bring in everything from the file above
#[test]
fn test_is_even() {
assert!(is_even(2));
assert!(is_even(0));
assert!(!is_even(3));
}
}
#[cfg(test)]means "only compile this forcargo test". Your real binary does not carry its testsuse super::*is why the test can callis_evenwithout a path
Project 2 did it the other way, with a tests/ directory next to src/. Both work.
Running tests
$ cargo test
running 3 tests
test tests::test_is_even ... ok
test tests::test_average_single ... ok
test tests::test_average_empty ... FAILED
failures:
---- tests::test_average_empty stdout ----
note: test did not panic as expected
test result: FAILED. 2 passed; 1 failed
Three things to read, in order: the name of what failed, the note under it, and the count.
cargo test # everything
cargo test --test cp1 # one file in tests/
cargo test average # every test with "average" in its name
Good tests test one thing at a time
One test, three functions:
#[test]
fn test_everything() {
assert_eq!(add(1, 2), 3);
assert_eq!(multiply(2, 3), 6);
assert_eq!(divide(10, 2), 5);
}
Three tests:
#[test]
fn test_add() { assert_eq!(add(1, 2), 3); }
#[test]
fn test_multiply() { assert_eq!(multiply(2, 3), 6); }
#[test]
fn test_divide() { assert_eq!(divide(10, 2), 5); }
Why? When test_everything fails, you know one of three things broke. When test_divide fails, you know which.
Good tests: expect the panic
Sometimes a function should panic:
pub fn get_first(v: &Vec<i32>) -> i32 {
v[0] // panics on an empty vector
}
#[test]
#[should_panic]
fn test_empty_vec() {
get_first(&vec![]); // the test passes only if this panics
}
Even better, say which panic you expect:
#[test]
#[should_panic(expected = "index out of bounds")]
fn test_empty_vec() {
get_first(&vec![]);
}
Without expected, a test that panics for the wrong reason still passes.
Good tests: the edges
The "happy path" is how things work normally, and is worth testing.
More important, in some ways, is testing edge cases that are off the happy path.
pub fn average(numbers: &[i32]) -> i32 {
let sum: i32 = numbers.iter().sum();
sum / numbers.len() as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_average_normal() {
assert_eq!(average(&[1, 2, 3]), 2);
}
#[test]
fn test_average_single() {
assert_eq!(average(&[42]), 42);
}
#[test]
#[should_panic]
fn test_average_empty() {
average(&[]); // integer division by zero panics
}
}
Empty. One element. Zero. Negative. The biggest value that fits. Ask what could go wrong, then write that down as a test.
Will this test pass?
Same average as before. Which of these tests pass? Think/pair/share.
pub fn average(numbers: &[i32]) -> i32 {
let sum: i32 = numbers.iter().sum();
sum / numbers.len() as i32
}
#[test]
fn a() { assert_eq!(average(&[2, 4]), 3); }
#[test]
fn b() { assert_eq!(average(&[1, 2, 5]), 3); }
#[test]
#[should_panic]
fn c() { average(&[]); }
apasses. 6 / 2 is exactly 3bfails. 8 / 3 is 2.67, so 3 looks like the right answer. Integer division throws the remainder away and returns 2. The test reportsleft: 2, right: 3, and now you have to decide which one is wrong: the function, for truncating, or the test, for expecting a rounded answercpasses. Integer division by zero panics, and#[should_panic]is satisfied
Reading a test is reading the code and the expectation, and either one can be wrong.
What does this test miss?
From Project 2. Your next_capacity had visible tests like these (abridged):
#[test]
fn double_doubles() {
assert_eq!(Growth::Double.next_capacity(4), 8);
}
#[test]
fn add_adds() {
assert_eq!(Growth::Add(3).next_capacity(4), 7);
}
#[test]
fn multiply_rounds_down() {
assert_eq!(Growth::Multiply(1.5).next_capacity(5), 7);
}
They all pass for this implementation, yet there are still bugs here. What input breaks it, and what test could check for it?
pub fn next_capacity(&self, capacity: usize) -> usize {
match self {
Growth::Double => capacity * 2,
Growth::Add(n) => capacity + n,
Growth::Multiply(f) => (capacity as f64 * f) as usize,
}
}
The input: Capacity 0.
Double returns 0, and push has nowhere to go. Also Multiply(1.0), or Multiply(1.1) on a small capacity, where rounding down lands on the same number.
The spec said "the answer must always be bigger than capacity" but no (visible) test checked.
The secret test that does check it:
// The handout promises only that the answer is bigger than `capacity`, so
// that is all this checks. These are the cases where the arithmetic alone
// does not get there; any bigger number is a pass.
#[test]
fn always_grows_even_when_the_arithmetic_does_not() {
let cases: Vec<(Growth, usize)> = vec![
(Growth::Double, 0),
(Growth::Multiply(1.5), 0),
(Growth::Multiply(1.5), 1),
(Growth::Multiply(1.1), 5),
(Growth::Multiply(1.0), 4),
(Growth::Multiply(0.5), 4),
(Growth::Add(0), 4),
(Growth::Add(0), 0),
];
for (growth, capacity) in cases {
let next = growth.next_capacity(capacity);
assert!(next > capacity, "{:?}.next_capacity({}) returned {}, which is not bigger",
growth, capacity, next);
}
}
Activity 26, Problem 1: plan the tests
See Problem 1 on Activity 26.
Beyond unit tests
Unit tests check one function in isolation.
Integration tests check that the parts work together, and in Rust they live in a tests/ directory next to src/, which is what Project 2's cp1.rs, cp2.rs, and cp3.rs were.
my_project/
src/
lib.rs # unit tests at the bottom of each file
tests/
cp1.rs # integration tests: use the crate like a user would
The car gap story
A few more habits for good test design
- Test behavior, not implementation If you rewrite the inside of a function, its tests should still pass
- Do not test the language
assert_eq!(vec![1, 2].len(), 2)can never fail, so it can never tell you anything. - Keep tests independent Each one runs on its own, in any order
- Lean into wordy test names
panic_if_first_value_in_vec_is_zerois a lot more informative thancheck_zeroor worse,test_7
Take-aways
- A test is a function with
#[test], and it fails by panicking. Theassertmacros are how you panic on purpose - Run them with
cargo test. Read the name, then the note, then the count - One thing per test. Edges over happy paths: empty, one, zero, too big
- A test can be wrong too
- A failing test names the bug, which is why the name is worth writing well
Wednesday: review. Friday: Midterm 2.
Activity 26
See Activity 26. Problem 1 is done, so start at Problem 2: the playground, your six tests, and the bug they find.