TExcelTAD
Home › Cargo in Depth › cargo test & cargo doc

cargo test & cargo doc

cargo test is three test runners in one: unit tests inside your source files, integration tests in tests/, and doc tests in your documentation comments. cargo doc turns those same comments into HTML. Together they make documentation that can't silently go out of date.

One command, three kinds of test

bash · try it yourself
cargo new --lib stats --vcs none -q
cd stats
mkdir tests
cat > src/lib.rs <<'RS'
//! Small statistics helpers.

/// Arithmetic mean of `xs`, or `None` when it is empty.
///
/// ```
/// assert_eq!(stats::mean(&[1.0, 2.0, 3.0]), Some(2.0));
/// assert_eq!(stats::mean(&[]), None);
/// ```
pub fn mean(xs: &[f64]) -> Option<f64> {
    if xs.is_empty() {
        return None;
    }
    Some(xs.iter().sum::<f64>() / xs.len() as f64)
}

/// Median of `xs` (sorts a copy).
///
/// ```
/// assert_eq!(stats::median(&[3.0, 1.0, 2.0]), Some(2.0));
/// ```
pub fn median(xs: &[f64]) -> Option<f64> {
    let mut v = xs.to_vec();
    v.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let n = v.len();
    match n {
        0 => None,
        _ if n % 2 == 1 => Some(v[n / 2]),
        _ => Some((v[n / 2 - 1] + v[n / 2]) / 2.0),
    }
}

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

    #[test]
    fn mean_single() {
        assert_eq!(mean(&[4.0]), Some(4.0));
    }

    #[test]
    fn median_even() {
        assert_eq!(median(&[1.0, 2.0, 3.0, 10.0]), Some(2.5));
    }
}
RS
cat > tests/api.rs <<'RS'
#[test]
fn mean_and_median_agree_on_symmetric_data() {
    let xs = [1.0, 2.0, 3.0];
    assert_eq!(stats::mean(&xs), stats::median(&xs));
}
RS
cargo test -- --test-threads=1 2>&1
   Compiling stats v0.1.0 (/home/learner/stats)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58s
     Running unittests src/lib.rs (target/debug/deps/stats-e102f27a3fdcacc2)

running 2 tests
test tests::mean_single ... ok
test tests::median_even ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/api.rs (target/debug/deps/api-bb9dd86d7364955b)

running 1 test
test mean_and_median_agree_on_symmetric_data ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests stats

running 2 tests
test src/lib.rs - mean (line 5) ... ok
test src/lib.rs - median (line 18) ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

all doctests ran in 0.16s; merged doctests compilation took 0.15s

(-- --test-threads=1 runs the tests one after another so the report comes out in a stable order; by default they run in parallel and print in completion order.) Each block of output is one test binary: the library's unit tests (compiled with cfg(test), so the tests module exists), each file in tests/, then the doc tests. Unit tests can reach private items through use super::*; integration tests and doc tests only see the public API.

Choosing what to run

Command Runs
cargo test median tests whose name contains median (in every binary)
cargo test --lib only unit tests of the library
cargo test --test api only tests/api.rs
cargo test --doc only doc tests
cargo test -p stats / --workspace one member / all members
cargo test -- --nocapture show println! output of passing tests (args after -- go to the test binary)
cargo test -- --test-threads=1 run tests one at a time (shared files, ports)
cargo test -- --ignored run tests marked #[ignore] (slow ones)
cargo test --no-run build test binaries without running them (CI: build stage)
bash · try it yourself
cargo new --lib stats --vcs none -q
cd stats
cat > src/lib.rs <<'RS'
pub fn mean(xs: &[f64]) -> f64 { xs.iter().sum::<f64>() / xs.len() as f64 }

#[cfg(test)]
mod tests {
    #[test]
    fn mean_small() { assert_eq!(super::mean(&[1.0, 3.0]), 2.0); }

    #[test]
    fn mean_prints() {
        println!("debug output from the test");
        assert_eq!(super::mean(&[2.0]), 2.0);
    }

    #[test]
    #[ignore = "takes minutes"]
    fn mean_huge() { assert!(super::mean(&vec![1.0; 10_000_000]) == 1.0); }

    #[test]
    fn mean_empty_is_nan() { assert_eq!(super::mean(&[]), 0.0); }
}
RS
echo "--- filter by name"
cargo test -q mean_small 2>&1 | grep -E '^test |test result'
echo "--- a failure"
cargo test -q 2>&1 | grep -E -A5 '^---- ' | sed -E 's/ \([0-9]+\) panicked/ panicked/'
echo "--- show output of one passing test"
cargo test -q mean_prints -- --nocapture 2>&1 | grep -E 'debug output|test result'
--- filter by name
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s
--- a failure
---- tests::mean_empty_is_nan stdout ----

thread 'tests::mean_empty_is_nan' panicked at src/lib.rs:19:30:
assertion `left == right` failed
  left: NaN
 right: 0.0
--- show output of one passing test
debug output from the test
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s

The failure report shows the assertion with both values: NaN (0/0) is not 0.0, and NaN isn't even equal to itself, a classic float trap the test caught.

Doc tests

A code block in a /// comment is compiled and run as its own little program that uses your crate as an external dependency. Annotations change that:

Info string after the opening fence Effect
none, or rust compile and run; must not panic
no_run compile only (code that opens sockets, loops forever)
compile_fail must fail to compile (documenting what the API forbids)
should_panic must panic
ignore skip entirely (avoid: it rots)
text not Rust at all

Lines starting with # are compiled but hidden in the rendered docs, handy for setup code. Doc tests only exist for library crates.

cargo doc

bash · try it yourself
cargo new --lib stats --vcs none -q
cd stats
cat > src/lib.rs <<'RS'
//! Small statistics helpers. See [`mean`].

/// Arithmetic mean. Unlike [`median`], it is not robust to outliers.
pub fn mean(xs: &[f64]) -> f64 { xs.iter().sum::<f64>() / xs.len() as f64 }

/// Returns the middle value. See [`Summary`] for everything at once.
pub fn median(xs: &[f64]) -> f64 { xs[xs.len() / 2] }
RS
cargo add anyhow -q
cargo doc 2>&1 | grep -v Unpacking
echo "--- only our own crate"
cargo doc --no-deps 2>&1
ls target/doc
   Compiling anyhow v1.0.104
 Documenting anyhow v1.0.104
 Documenting stats v0.1.0 (/home/learner/stats)
warning: unresolved link to `Summary`
 --> src/lib.rs:6:37
  |
6 | /// Returns the middle value. See [`Summary`] for everything at once.
  |                                     ^^^^^^^ no item named `Summary` in scope
  |
  = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
  = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default

warning: `stats` (lib doc) generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.71s
   Generated /home/learner/stats/target/doc/stats/index.html
--- only our own crate
 Documenting stats v0.1.0 (/home/learner/stats)
warning: unresolved link to `Summary`
 --> src/lib.rs:6:37
  |
6 | /// Returns the middle value. See [`Summary`] for everything at once.
  |                                     ^^^^^^^ no item named `Summary` in scope
  |
  = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
  = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default

warning: `stats` (lib doc) generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.11s
   Generated /home/learner/stats/target/doc/stats/index.html
anyhow
crates.js
help.html
search.index
settings.html
src
src-files.js
static.files
stats
trait.impl
type.impl
  • cargo doc documents dependencies too (here anyhow), so the docs link across crates. --no-deps is faster when you only need yours; --open opens it in a browser.
  • Intra-doc links like [`mean`] are checked: the broken [`Summary`] produced a rustdoc::broken_intra_doc_links warning. RUSTDOCFLAGS="-D warnings" cargo doc turns such warnings into errors in CI.
  • docs.rs builds the same HTML for every published crate, with --all-features unless configured otherwise in [package.metadata.docs.rs].

Test yourself

Which tests can call a private function of the library?

  1. Integration tests in tests/
  2. Unit tests in a #[cfg(test)] module inside the crate
  3. Doc tests
  4. All of them

How do you see println! output from passing tests?

  1. cargo test --verbose
  2. cargo test -- --nocapture
  3. cargo test --show-output-all
  4. RUST_LOG=debug cargo test

A doc example opens a network connection. How should its fence be marked so docs stay compile-checked?

  1. ignore
  2. no_run
  3. text
  4. should_panic