Module 16 Exercises — Testing, Docs & Tooling
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to explain:
- when a test belongs in
mod testsversus intests/; - what
#[cfg(test)]saves you; - why a doc test is worth more than a README example.
Write at least one deliberately failing test in these drills and read the output carefully. Knowing what a failure looks like — which line, which values — is what makes tests useful under pressure later.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 16.1 — First tests
Write a fn is_palindrome(s: &str) -> bool (case- and punctuation-insensitive) with at
least five tests: empty string, single char, true case, false case, and a phrase with
punctuation.
Solution
pub fn is_palindrome(s: &str) -> bool {
let cleaned: Vec<char> = s.chars()
.filter(|c| c.is_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
cleaned.iter().eq(cleaned.iter().rev())
}
#[cfg(test)]
mod tests {
use super::*;
#[test] fn empty_is_palindrome() { assert!(is_palindrome("")); }
#[test] fn single_char() { assert!(is_palindrome("a")); }
#[test] fn simple_true() { assert!(is_palindrome("racecar")); }
#[test] fn simple_false() { assert!(!is_palindrome("rust")); }
#[test] fn ignores_punctuation() {
assert!(is_palindrome("A man, a plan, a canal: Panama!"));
}
}.iter().eq(.iter().rev()) compares two iterators element-wise without allocating a
reversed copy.
🟢 Exercise 16.2 — should_panic
Write fn percent(value: f64, total: f64) -> f64 that panics with "total must be positive" when total <= 0.0, plus a test asserting the exact message.
Solution
pub fn percent(value: f64, total: f64) -> f64 {
if total <= 0.0 { panic!("total must be positive, got {total}"); }
value / total * 100.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn computes_percent() { assert!((percent(1.0, 4.0) - 25.0).abs() < 1e-9); }
#[test]
#[should_panic(expected = "total must be positive")]
fn rejects_zero_total() { percent(1.0, 0.0); }
}Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 16.3 — Doc tests
Add doc comments with runnable examples to a Stack<T> (from module 11), including a
# Examples block and one should_panic block. Verify cargo test --doc runs them, then
deliberately break an example and confirm the test fails.
Solution
/// A last-in-first-out stack.
///
/// # Examples
///
/// ```
/// use mycrate::Stack;
/// let mut s = Stack::new();
/// s.push(1);
/// s.push(2);
/// assert_eq!(s.pop(), Some(2));
/// assert_eq!(s.len(), 1);
/// ```
#[derive(Debug, Default)]
pub struct Stack<T> { items: Vec<T> }
impl<T> Stack<T> {
/// Creates an empty stack.
pub fn new() -> Self { Stack { items: Vec::new() } }
/// Pushes an item onto the top.
pub fn push(&mut self, item: T) { self.items.push(item); }
/// Removes and returns the top item, or `None` if empty.
pub fn pop(&mut self) -> Option<T> { self.items.pop() }
/// Returns the number of items.
pub fn len(&self) -> usize { self.items.len() }
/// Returns the top item.
///
/// # Panics
/// Panics if the stack is empty.
///
/// ```should_panic
/// use mycrate::Stack;
/// let s: Stack<i32> = Stack::new();
/// s.top();
/// ```
pub fn top(&self) -> &T { self.items.last().expect("stack is empty") }
}🟡 Exercise 16.4 — Integration test suite
Create a library with pub fn tokenize(&str) -> Vec<String> and pub struct Counter.
Write tests/tokenize_test.rs and tests/counter_test.rs sharing a tests/common/mod.rs
with a sample_text() helper. Confirm private functions are not visible from there.
Solution sketch
// tests/common/mod.rs
pub fn sample_text() -> &'static str {
"the quick brown fox jumps over the lazy dog"
}
// tests/tokenize_test.rs
mod common;
use mylib::tokenize;
#[test]
fn splits_on_whitespace() {
assert_eq!(tokenize(common::sample_text()).len(), 9);
}
// tests/counter_test.rs
mod common;
use mylib::Counter;
#[test]
fn counts_words() {
let mut c = Counter::new();
for w in mylib::tokenize(common::sample_text()) { c.add(&w); }
assert_eq!(c.get("the"), 2);
}Attempting use mylib::internal_helper; gives E0603: function is private — proof the
integration test sees only your public surface.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 16.5 — Test-driven Roman numerals
Using strict TDD, implement fn to_roman(n: u32) -> String and fn from_roman(s: &str) -> Option<u32>.
Write the test first, watch it fail, then implement. Cover: 1, 4, 9, 14, 40, 90, 400, 1994,
3999, and the round-trip property from_roman(&to_roman(n)) == Some(n) for all
1..=3999.
Solution
const TABLE: [(u32, &str); 13] = [
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"),
];
pub fn to_roman(mut n: u32) -> String {
let mut out = String::new();
for (value, symbol) in TABLE {
while n >= value {
out.push_str(symbol);
n -= value;
}
}
out
}
pub fn from_roman(s: &str) -> Option<u32> {
let val = |c: char| match c {
'I' => Some(1), 'V' => Some(5), 'X' => Some(10), 'L' => Some(50),
'C' => Some(100), 'D' => Some(500), 'M' => Some(1000), _ => None,
};
let digits: Option<Vec<u32>> = s.chars().map(val).collect();
let digits = digits?;
let mut total = 0;
for (i, d) in digits.iter().enumerate() {
if digits.get(i + 1).is_some_and(|next| next > d) { total -= d; } else { total += d; }
}
Some(total as u32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_values() {
for (n, s) in [(1, "I"), (4, "IV"), (9, "IX"), (14, "XIV"), (40, "XL"),
(90, "XC"), (400, "CD"), (1994, "MCMXCIV"), (3999, "MMMCMXCIX")] {
assert_eq!(to_roman(n), s, "to_roman({n})");
assert_eq!(from_roman(s), Some(n), "from_roman({s})");
}
}
#[test]
fn round_trip_all() {
for n in 1..=3999 {
assert_eq!(from_roman(&to_roman(n)), Some(n), "round trip failed at {n}");
}
}
#[test]
fn rejects_garbage() {
assert_eq!(from_roman("hello"), None);
}
}The round-trip test is a property test — it asserts an invariant across the whole
input space rather than checking hand-picked examples. For real property testing, look at
the proptest and quickcheck crates.
Self-check
- Why does
#[cfg(test)]matter? - Why can unit tests access private functions but integration tests can't?
- What breaks if two tests write to the same file, and what are two fixes?
- What does
black_boxdo in a benchmark? - Name the four commands a minimal Rust CI should run.
Answers
- It excludes the test module from normal builds, so tests add nothing to your binary.
- Unit tests are a child module of the code under test; integration tests are separate crates that see only the public API.
- They run in parallel and race; fix by giving each test a unique temp path or by running
with
--test-threads=1. - Prevents the optimizer from removing the computation as dead code.
cargo fmt --check,cargo clippy -D warnings,cargo test,cargo doc.
