← Retour au cours: Rust from scratch

Automated tests with cargo test

Vidéo bientôt disponible

Testing your program by hand, running it and looking at the output, works at first and becomes unsustainable as the project grows: every change could break something that already worked. Automated tests are small functions that verify your code does what it should, and that you can repeat in a second with a single command. Rust includes a testing system in the language itself and in cargo, with nothing to install. In this lesson you will write your first tests and learn to organize them.

Your first test

A test is a function marked with #[test]. Inside you use assertion macros: assert!(condition) fails if the condition is false, assert_eq!(a, b) compares two values and prints both if they differ, and assert_ne!(a, b) checks they are different. If the function ends without panicking, the test passes; if it panics, it fails. By convention, unit tests are written in the same file as the code, inside a mod tests with #[cfg(test)], which is only compiled when running cargo test and does not enter your final program. With use super::*; you bring everything from the file into the module.

rust
// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("division by zero"))
    } else {
        Ok(a / b)
    }
}

pub fn is_palindrome(text: &str) -> bool {
    let clean: Vec<char> = text
        .chars()
        .filter(|c| c.is_alphanumeric())
        .map(|c| c.to_ascii_lowercase())
        .collect();
    clean.iter().eq(clean.iter().rev())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn divides_ok() {
        assert_eq!(divide(10, 2), Ok(5));
    }

    #[test]
    fn divide_by_zero_is_error() {
        assert!(divide(1, 0).is_err());
    }

    #[test]
    fn detects_palindromes() {
        assert!(is_palindrome("A man, a plan, a canal: Panama"));
        assert!(!is_palindrome("rust"));
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn raw_division_panics() {
        let zero = add(0, 0);
        let _ = 1 / zero;
    }
}

Run cargo test and you will see one line per test (ok or FAILED) and a summary. With cargo test name you run only the tests whose name contains that text. By default cargo hides the println! output of passing tests; add -- --nocapture to see it. The test with #[should_panic] expects the code to panic: it is useful to verify that invalid cases really fail, and with expected it also checks the message.

sh
# Typical commands (shell)
cargo test                       # run all tests
cargo test palindrome            # only tests with "palindrome" in the name
cargo test -- --nocapture        # show println! output
cargo test -- --test-threads=1   # run one test at a time

Tests returning Result and custom messages

A test can also return Result<(), E>: if it returns Err, it fails. That lets you use the ? operator inside and keep the test clean. And assertions accept an optional formatted message as the last argument, very useful when a failure does not explain itself: assert!(x > 0, "x must be positive but was {x}"). When assert_eq! fails, it prints both values with Debug, so the types you compare must implement Debug and PartialEq (derive gives them for free).

rust
#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

fn parse_point(text: &str) -> Result<Point, std::num::ParseIntError> {
    let (a, b) = text.split_once(',').unwrap_or((text, "0"));
    Ok(Point { x: a.trim().parse()?, y: b.trim().parse()? })
}

fn main() {
    println!("{:?}", parse_point("3, 4"));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_point() -> Result<(), std::num::ParseIntError> {
        let p = parse_point("3, 4")?;
        assert_eq!(p, Point { x: 3, y: 4 }, "the point was parsed wrongly");
        Ok(())
    }

    #[test]
    fn rejects_garbage() {
        assert!(parse_point("a,b").is_err());
    }
}

Integration and documentation tests

Unit tests live next to the code and can even test private functions. Integration tests are in a tests/ folder next to src/, each file is a separate crate that uses your library as a third party would, with only its public API. It is the best way to check that the pieces work together. Also, the code examples inside /// comments run as tests (doctests), which guarantees the documentation never gets outdated. A good practice is to write the failing test first and then the code that makes it pass.

rust
// tests/basic.rs  (integration test; uses only the public API)
use my_lib::add;

#[test]
fn add_works_from_outside() {
    assert_eq!(add(1, 1), 2);
}

// In src/lib.rs, a doctest:
/// Adds two numbers.
///
/// ```
/// assert_eq!(my_lib::add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
rust
pub fn count_words(text: &str) -> usize {
    text.split_whitespace().count()
}

pub fn capitalize(word: &str) -> String {
    let mut chars = word.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counts_words() {
        assert_eq!(count_words("the quick  brown fox"), 4);
    }

    #[test]
    fn counts_zero_in_empty_text() {
        assert_eq!(count_words(""), 0);
    }

    #[test]
    fn capitalizes_a_word() {
        assert_eq!(capitalize("rust"), "Rust");
    }

    #[test]
    fn capitalizes_empty() {
        assert_eq!(capitalize(""), "");
    }
}

Testez vos acquis

Question 1 sur 4

Which attribute marks a function as a test?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →