Level 2 · Practitioner· Lesson 7 of 8 · 20 min
Testing and documentation
Unit tests, integration tests, doc tests, property testing, and the tooling that keeps a codebase healthy.
Unit tests
Tests live next to the code, in a module compiled only under cargo test. Open the block below in the Playground and press Test there.
pub fn median(values: &mut [f64]) -> Option<f64> {
if values.is_empty() {
return None;
}
values.sort_by(|a, b| a.total_cmp(b));
let mid = values.len() / 2;
Some(if values.len() % 2 == 0 {
(values[mid - 1] + values[mid]) / 2.0
} else {
values[mid]
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_has_no_median() {
assert_eq!(median(&mut []), None);
}
#[test]
fn odd_length() {
assert_eq!(median(&mut [3.0, 1.0, 2.0]), Some(2.0));
}
#[test]
fn even_length_averages_the_middle() {
assert_eq!(median(&mut [4.0, 1.0, 3.0, 2.0]), Some(2.5));
}
#[test]
#[should_panic(expected = "index out of bounds")]
fn indexing_past_the_end_panics() {
let v = vec![1];
let i = v.len();
let _ = v[i];
}
#[test]
fn tests_can_return_result() -> Result<(), std::num::ParseIntError> {
let n: i32 = "42".parse()?;
assert_eq!(n, 42);
Ok(())
}
}
fn main() {
println!("{:?}", median(&mut [5.0, 1.0, 9.0]));
}
The tools: assert!(cond), assert_eq!(a, b), assert_ne!(a, b), each with an optional trailing format message. Because tests is a child module, it can test private functions.
Useful commands:
| Command | Effect |
|---|---|
cargo test |
run everything |
cargo test median |
run tests whose name contains median |
cargo test -- --nocapture |
show println! output from passing tests |
cargo test -- --test-threads=1 |
run serially |
#[ignore] + cargo test -- --ignored |
opt-in slow tests |
Integration tests
Files in tests/ are separate crates that see only your public API — they use the library exactly as a user would.
my_crate/
├── src/lib.rs
└── tests/
├── basic.rs
└── common/mod.rs // shared helpers
// tests/basic.rs
use my_crate::median;
#[test]
fn works_through_the_public_api() {
assert_eq!(median(&mut [1.0, 2.0, 3.0]), Some(2.0));
}
A binary-only crate has no library for integration tests to import, which is one reason to keep main.rs thin and put logic in lib.rs.
Documentation and doc tests
/// documents the item that follows; //! documents the enclosing module or crate. Comments are Markdown, and code blocks in them are compiled and run by cargo test.
/// Clamps `value` to the inclusive range `lo..=hi`.
///
/// # Examples
///
/// ```
/// assert_eq!(my_crate::clamp(15, 0, 10), 10);
/// assert_eq!(my_crate::clamp(-3, 0, 10), 0);
/// ```
///
/// # Panics
///
/// Panics if `lo > hi`.
pub fn clamp(value: i32, lo: i32, hi: i32) -> i32 {
assert!(lo <= hi, "lo must not exceed hi");
value.max(lo).min(hi)
}
Conventional sections are # Examples, # Panics, # Errors, and # Safety (mandatory on unsafe fn). cargo doc --open renders it all in the same format as the standard library’s documentation.
Property-based testing
Example tests check the cases you thought of. Property tests state a law and let the machine hunt for a counterexample, then shrink it to a minimal one. With the proptest crate:
// crate: proptest
use proptest::prelude::*;
fn reverse<T: Clone>(xs: &[T]) -> Vec<T> {
xs.iter().rev().cloned().collect()
}
proptest! {
#[test]
fn reversing_twice_is_identity(xs in proptest::collection::vec(any::<i32>(), 0..100)) {
prop_assert_eq!(reverse(&reverse(&xs)), xs);
}
#[test]
fn reverse_preserves_length(xs in proptest::collection::vec(any::<u8>(), 0..100)) {
prop_assert_eq!(reverse(&xs).len(), xs.len());
}
}
Good properties: round trips (decode(encode(x)) == x), invariants (output is sorted), agreement with a slow, obviously correct implementation.
The rest of the toolbox
| Tool | Purpose |
|---|---|
cargo fmt |
Canonical formatting. Run it on save |
cargo clippy |
Lints for bugs, performance and idiom. Treat warnings as lessons |
cargo bench with criterion |
Statistically sound micro-benchmarks |
cargo fuzz |
Coverage-guided fuzzing: the best way to find panics in parsers |
cargo miri test |
Runs tests in an interpreter that detects undefined behaviour |
cargo audit, cargo deny |
Known vulnerabilities and licence policy in dependencies |
cargo llvm-cov |
Code coverage |
A reasonable continuous-integration baseline: cargo fmt --check, cargo clippy -- -D warnings, cargo test.
Exercises
- Write
fn roman(n: u32) -> Stringtest-first: begin with tests for 1, 4, 9, 14, 40, 90, 400, 1994, then implement. - Add a doc comment with a runnable example and a
# Panicssection (for 0 and values above 3999). - With
proptest, check that your sort-basedmedianalways lies between the minimum and maximum of the input.
Check your understanding
Pick an answer to see the explanation.
1.Where do integration tests live in a Cargo package?
2.What does
#[cfg(test)]on a module do?3.What happens to a Rust code block inside a
///doc comment when you runcargo test?