Inline Unit Tests With Cfg Test

Embed #[cfg(test)] unit tests beside the code they verify with assert_eq!, assert! and #[should_panic], so cargo test runs them and cargo run skips them.

RustData Integrity

Code

rustsnippet
45 lines
fn slugify(input: &str) -> String {
    let words: Vec<String> = input
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|w| !w.is_empty())
        .map(|w| w.to_ascii_lowercase())
        .collect();
    words.join("-")
}

fn divide(numerator: i32, denominator: i32) -> Option<i32> {
    if denominator == 0 { None } else { Some(numerator / denominator) }
}

fn parse_port(raw: &str) -> u16 {
    raw.parse().expect("port out of range")
}

fn main() {
    println!("{}", slugify("Hello, Rust World!"));
    println!("div 10/4 = {:?}", divide(10, 4));
    // cargo run 不执行下面的测试;cargo test 才会运行整个 mod tests
}

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

    #[test]
    fn slug_is_lowercased_and_dashed() {
        assert_eq!(slugify("Hello, Rust World!"), "hello-rust-world");
        assert_eq!(slugify("!"), "");
    }

    #[test]
    fn division_by_zero_is_none() {
        assert!(divide(1, 0).is_none());
        assert_eq!(divide(9, 3), Some(3));
    }

    #[test]
    #[should_panic(expected = "port out of range")]
    fn invalid_port_panics() {
        parse_port("99999");
    }
}

How it works

Inline Unit Tests With Cfg Test reduces to the functions slugify, divide, parse_port and main.

Caveats

  • Plan for an install step: super:: is a real dependency, resolved by the package manager.

Using it

The primary signature is fn slugify(input: &str) -> String

The demo output is labeled (div 10/4 =), so every printed line maps back to its originating operation.

main sequences slugify, divide, slug_is_lowercased_and_dashed and division_by_zero_is_none; executing the file runs that flow once.

Key statements

if denominator == 0 { None } else { Some(numerator / denominator) }
fn slug_is_lowercased_and_dashed() {
    assert_eq!(slugify("Hello, Rust World!"), "hello-rust-world");
    assert_eq!(slugify("!"), "");
}
fn slugify(input: &str) -> String {
    let words: Vec<String> = input
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|w| !w.is_empty())
        .map(|w| w.to_ascii_lowercase())
        .collect();
    words.join("-")
}

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `super::`. Add it to your project before running the snippet.