Rust has a test runner built in. This part writes unit tests, integration tests and doc tests for a small library, reads what a failing test prints, and lets a test catch a real bug.
Rust comes with a test runner. You mark a function with #[test], type cargo test, and Cargo builds and runs every test in the package. There’s no framework to install and no config file to write.
This part tests a small library that turns text like 1h30m into seconds. We’ll write the three kinds of test Rust has: unit tests next to the code, integration tests in a tests/ folder, and doc tests inside the documentation. We’ll read what a failing test prints, test code that should panic, run only some of the tests, and watch a test catch a real bug. The library returns Result with its own error type, from Part 12, and uses the lib.rs layout from Part 18. Every program here was run on Rust 1.95, and its output is pasted from the run.
cargo test prints a few things that change on every run, so the outputs below trim them. We cut the Compiling and Finished lines, the build path after each Running line, the thread id after a test’s name, and a hint about RUST_BACKTRACE. The test ... lines come out in the order the tests finish, which can change from run to run, so we sorted them by name. Everything else is as it came.
Try this first
Make a project with cargo new try-first, and put this in src/main.rs:
fn double(n: i32) -> i32 {
n * 2
}
fn main() {
println!("double(21) = {}", double(21));
}
#[test]
fn double_works() {
assert_eq!(double(2), 5);
}
The test at the bottom is wrong: 2 doubled is 4, not 5. Before reading on, guess two things. What does cargo run do? And what does cargo test do?
cargo run doesn’t care. It prints:
double(21) = 42
A function marked #[test] is only compiled when Cargo builds the tests. A normal build leaves it out, so the wrong test can’t break cargo run. cargo test builds a different program: a test runner that calls every #[test] function. Here’s what it prints:
Running unittests src/main.rs
running 1 test
test double_works ... FAILED
failures:
---- double_works stdout ----
thread 'double_works' panicked at src/main.rs:11:5:
assertion `left == right` failed
left: 4
right: 5
failures:
double_works
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--bin try-first`
Reading a failing test
A test passes if its function returns. It fails if it panics. assert_eq! panics when its two values differ, and the runner catches that panic, marks the test FAILED, and moves on to the next test.
Read the output from the top:
running 1 testandtest double_works ... FAILEDare the summary, one line per test.- Under
failures:comes each failed test’s story.panicked at src/main.rs:11:5is the file, line and column of theassert_eq!. leftis the first value you gaveassert_eq!, andrightis the second. Rust doesn’t know which one you meant as the expected value. Most Rust code puts the real result first and the expected value second, soleftis what you got andrightis what you wanted. Pick one order and keep it.- The
test result:line counts everything. The last line tells you how to run just this target again.
assert!, assert_eq! and assert_ne!
Three macros do almost all the checking:
assert!(condition)panics if the condition is false.assert_eq!(a, b)panics ifa != b, and prints both values.assert_ne!(a, b)panics ifa == b, and prints both values.
They work in any code, not only in tests. That makes them easy to try in a plain main:
fn main() {
let minutes = 90;
assert!(minutes < 60);
}
It prints:
panicked at src/main.rs:3:5:
assertion failed: minutes < 60
assert! can only say which expression was false. It can’t show you 90. All three macros take an optional message after the values, written like format!:
fn main() {
let minutes = 90;
let hours = minutes / 60;
assert_eq!(hours * 60, minutes, "{minutes} minutes isn't whole hours");
}
It prints:
panicked at src/main.rs:4:5:
assertion `left == right` failed: 90 minutes isn't whole hours
left: 60
right: 90
A good message says what the test was checking, so a failure makes sense before you open the code. assert_eq! and assert_ne! need both values to be comparable with == and printable with {:?}. In trait terms from Part 14, they need PartialEq and Debug. That’s why the error type below derives both.
The library we’ll test
The package is called timespan. It’s a library, so its code is in src/lib.rs. Its central function, parse_duration, collects digits into a number until it meets a unit letter, then adds that many seconds to the total:
pub fn parse_duration(text: &str) -> Result<u64, ParseError> {
let text = text.trim();
if text.is_empty() {
return Err(ParseError::Empty);
}
let mut total: u64 = 0;
let mut number: Option<u64> = None;
for c in text.chars() {
if let Some(digit) = c.to_digit(10) {
let n = number.unwrap_or(0);
let n = n.checked_mul(10).ok_or(ParseError::TooLong)?;
let n = n.checked_add(u64::from(digit)).ok_or(ParseError::TooLong)?;
number = Some(n);
} else {
let n = number.take().ok_or(ParseError::MissingNumber(c))?;
let secs = n.checked_mul(unit_seconds(c)?).ok_or(ParseError::TooLong)?;
total = total.checked_add(secs).ok_or(ParseError::TooLong)?;
}
}
if number.is_some() {
return Err(ParseError::MissingUnit);
}
Ok(total)
}
checked_mul and checked_add return None instead of overflowing (Part 2), and ok_or turns that None into our error so ? can return it (Part 12). number.take() hands back the number and leaves None in its place, ready for the next one.
unit_seconds turns a letter into a number of seconds. It isn’t pub, so it’s private to the library:
// Private: only this module and its child modules can call it.
fn unit_seconds(unit: char) -> Result<u64, ParseError> {
match unit {
'd' => Ok(86_400),
'h' => Ok(3_600),
'm' => Ok(60),
's' => Ok(1),
other => Err(ParseError::UnknownUnit(other)),
}
}
The library also has format_duration, which turns 5400 back into 1h30m, and split, which divides a duration into equal parts. The ParseError enum has one variant per mistake, like MissingUnit for 90, and implements Display, the same pattern as Part 12.
Three kinds of test
Rust tests live in three places, and each place sees a different amount of your code:
Unit tests live inside the crate and see everything. Integration tests and doc tests are built outside it, so they see only what a user would.
- Unit tests go in a
testsmodule at the bottom of the file they test. The module is a child of that file’s module, so it can see private items too. - Integration tests go in a
tests/folder next tosrc/. Each file there is compiled as its own crate, which uses your library the way any other crate would. It sees only the public API. - Doc tests are code examples in
///comments. Each one is compiled outside your crate, as a user’s program, so it also sees only the public API.
cargo test builds and runs all three.
Unit tests: next to the code
Here’s the start of the test module in src/lib.rs:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_hours_and_minutes() {
assert_eq!(parse_duration("1h30m"), Ok(5400));
}
Two lines do the work:
#[cfg(test)]means “compile the next item only when building tests”.cargo buildskips the whole module, so tests and their helpers add nothing to your real program.cfgstands for configuration.use super::*;brings in every name from the parent module:parse_duration,ParseError, and the private ones too. Part 18 explained why a child module can see its parent’s private items.
That second point means a unit test can call unit_seconds directly, even though nothing outside the library can:
#[test]
fn unit_seconds_is_private_but_testable() {
assert_eq!(unit_seconds('h'), Ok(3_600));
assert_eq!(unit_seconds('x'), Err(ParseError::UnknownUnit('x')));
}
Should you test private functions? Sometimes. A small private helper with tricky logic is worth a direct test. But most tests should go through the public functions, so you can change the private ones later without rewriting the tests.
Tests that return Result
A test can also return Result<(), E>. It passes if it returns Ok(()) and fails if it returns Err. That lets you use ? inside a test, the same way as in main:
#[test]
fn too_long_is_an_error_not_a_panic() -> Result<(), String> {
let secs = parse_duration("18446744073709551615s").map_err(|e| e.to_string())?;
if secs != u64::MAX {
return Err(format!("expected u64::MAX, got {secs}"));
}
match parse_duration("18446744073709551616s") {
Err(ParseError::TooLong) => Ok(()),
other => Err(format!("expected TooLong, got {other:?}")),
}
}
The first ? turns a parse error into a failed test, with the error message as the reason. 18446744073709551615 is u64::MAX, the largest u64. One more second can’t fit, so the second call must return TooLong.
This test found a real bug. The first version of parse_duration added each digit with a plain +:
let n = n + u64::from(digit);
cargo test builds in debug mode, and in debug mode an integer overflow panics, as Part 2 showed. So instead of returning TooLong, the test panicked with attempt to add with overflow. The fix was the checked_add line you saw in parse_duration above.
Tests that should panic
split divides a duration into equal parts. Dividing into zero parts makes no sense, so it panics on purpose:
/// Splits a duration into equal parts, rounding down.
///
/// ```
/// assert_eq!(timespan::split(3600, 4), 900);
/// ```
///
/// # Panics
///
/// Panics if `parts` is zero.
pub fn split(secs: u64, parts: u64) -> u64 {
assert!(parts > 0, "cannot split a duration into zero parts");
secs / parts
}
To test that it panics, add #[should_panic]:
#[test]
#[should_panic(expected = "zero parts")]
fn split_into_zero_parts_panics() {
split(60, 0);
}
The test passes only if the function panics. expected = "zero parts" adds a second condition: the panic message must contain that text. Without it, any panic would pass, including an unwrap on None from some unrelated bug. If split doesn’t panic at all, the test fails with note: test did not panic as expected. If it panics with a different message, the test fails and prints both the message and the text it expected.
#[should_panic] can’t go on a test that returns Result. The compiler stops with functions using #[should_panic] must return (). Use one style or the other.
Ignoring a slow test
Some tests take too long to run every time. Mark them #[ignore], with a reason:
#[test]
#[ignore = "slow: checks every second of a week"]
fn round_trips_every_second_of_a_week() {
for secs in 0..=7 * 86_400 {
let text = format_duration(secs);
assert_eq!(parse_duration(&text), Ok(secs), "{text}");
}
}
cargo test lists the test as ignored, with your reason, and doesn’t run it. cargo test -- --ignored runs only the ignored tests, and cargo test -- --include-ignored runs everything. We’ll explain the lone -- in a moment.
Integration tests: only the public API
This test lives in tests/integration.rs. It uses the library the way a user would, through its name:
// An integration test is a separate crate: it sees only the public API.
use timespan::{ParseError, format_duration, parse_duration};
#[test]
fn round_trips_common_durations() {
for text in ["45s", "1m", "1h30m", "2d3h", "1d1h1m1s"] {
let secs = parse_duration(text).unwrap();
assert_eq!(format_duration(secs), text);
}
}
#[test]
fn errors_read_well() {
let err = parse_duration("5w").unwrap_err();
assert_eq!(err, ParseError::UnknownUnit('w'));
assert_eq!(err.to_string(), "'w' is not a unit (use d, h, m or s)");
}
Every .rs file directly in tests/ is compiled as a separate crate. It needs a use timespan::... line, the same as any program that depends on the library. It doesn’t need #[cfg(test)], because Cargo only builds this folder for cargo test.
Integration tests work on library crates. They can call what src/lib.rs makes public, but they can’t call functions in src/main.rs. That’s one more reason for the layout in Part 18: put the logic in lib.rs, and keep main.rs thin.
Doc tests: examples that run
Here’s the documentation comment on parse_duration:
/// Parses a duration like `1h30m` into a number of seconds.
///
/// ```
/// use timespan::parse_duration;
///
/// assert_eq!(parse_duration("1h30m"), Ok(5400));
/// assert_eq!(parse_duration("45s"), Ok(45));
/// ```
///
/// A number with no unit after it is an error:
///
/// ```
/// use timespan::{ParseError, parse_duration};
///
/// assert_eq!(parse_duration("90"), Err(ParseError::MissingUnit));
/// ```
pub fn parse_duration(text: &str) -> Result<u64, ParseError> {
Each fenced block in a /// comment is a doc test. A fence is a line of three backticks, the same fence Markdown uses. cargo test hands them to rustdoc, Rust’s documentation tool. It wraps each one in a fn main, compiles it outside your crate as code that uses your library, and runs it. cargo doc shows the same blocks as examples on the documentation page.
So the examples in your docs can’t go stale. If someone changes what parse_duration returns and forgets the docs, cargo test fails. Notice the use timespan::... line: a doc test is outside the crate, so it needs one, just like an integration test.
A doc test’s fence can carry a word after the opening three backticks. should_panic means the example must panic, and ignore means it isn’t run at all.
Running cargo test
Here’s the whole suite. In the timespan folder, run cargo test:
Running unittests src/lib.rs
running 7 tests
test tests::parses_each_unit ... ok
test tests::parses_hours_and_minutes ... ok
test tests::rejects_bad_input ... ok
test tests::split_into_zero_parts_panics - should panic ... ok
test tests::too_long_is_an_error_not_a_panic ... ok
test tests::trailing_number_is_an_error ... ok
test tests::unit_seconds_is_private_but_testable ... ok
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/integration.rs
running 3 tests
test errors_read_well ... ok
test round_trips_common_durations ... ok
test round_trips_every_second_of_a_week ... ignored, slow: checks every second of a week
test result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests timespan
running 4 tests
test src/lib.rs - format_duration (line 77) ... ok
test src/lib.rs - parse_duration (line 36) ... ok
test src/lib.rs - parse_duration (line 45) ... ok
test src/lib.rs - split (line 99) ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
There are three sections, always in this order:
Running unittests src/lib.rs: the unit tests, the#[cfg(test)]module.Running tests/integration.rs: one section per file intests/.Doc-tests timespan: the doc tests. Each is named after the item it documents and the line where its fence starts.
should panic and ignored are marked on their lines. If one section fails, Cargo stops and doesn’t run the later ones. Add --no-fail-fast to run them all anyway.
Running some of the tests
When you’re working on one thing, you don’t need every test. Give cargo test part of a name, and it runs only the tests whose full name contains it. cargo test parse prints:
Running unittests src/lib.rs
running 2 tests
test tests::parses_each_unit ... ok
test tests::parses_hours_and_minutes ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 5 filtered out; finished in 0.00s
Running tests/integration.rs
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s
Two tests in tests:: matched, and the rest were filtered out. Notice what’s missing: the doc tests. On Cargo 1.95, a name filter skipped them, even though two of them are called parse_duration. Add --doc to run only the doc tests, with the same filter. cargo test --doc parse prints:
Doc-tests timespan
running 2 tests
test src/lib.rs - parse_duration (line 36) ... ok
test src/lib.rs - parse_duration (line 45) ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
Some settings belong to the test runner, not to Cargo. They go after a lone --, which means “pass the rest to the test program”. Two are worth knowing.
--nocapture shows what tests print. The runner captures a test’s output and shows it only if the test fails. parses_each_unit prints a line per case, and you never see them while it passes. To see them, run cargo test each_unit -- --nocapture:
Running unittests src/lib.rs
running 1 test
checking 1d
checking 1h
checking 1m
checking 1s
test tests::parses_each_unit ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
Running tests/integration.rs
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s
--test-threads=1 runs the tests one at a time. Normally they run in parallel, on several threads. That’s fast, but two tests that write the same file or change the same environment variable can get in each other’s way. cargo test -- --test-threads=1 is a quick way to check whether a flaky test is one of those. The real fix is to stop the tests sharing anything.
To run a single file of integration tests, use cargo test --test integration. For the unit tests only, use cargo test --lib.
Worked example: a bug a test found
Suppose parse_duration ended right after the loop, with Ok(total), and had no check for a number left over at the end. With that version, the tests for 1h30m and for each unit still pass. But what if someone types 1h30 and forgets the m? This test asks:
#[test]
fn trailing_number_is_an_error() {
assert_eq!(
parse_duration("1h30"),
Err(ParseError::MissingUnit),
"the 30 has no unit"
);
}
On that version, cargo test prints:
Running unittests src/lib.rs
running 7 tests
test tests::parses_each_unit ... ok
test tests::parses_hours_and_minutes ... ok
test tests::rejects_bad_input ... ok
test tests::split_into_zero_parts_panics - should panic ... ok
test tests::too_long_is_an_error_not_a_panic ... ok
test tests::trailing_number_is_an_error ... FAILED
test tests::unit_seconds_is_private_but_testable ... ok
failures:
---- tests::trailing_number_is_an_error stdout ----
thread 'tests::trailing_number_is_an_error' panicked at src/lib.rs:144:9:
assertion `left == right` failed: the 30 has no unit
left: Ok(3600)
right: Err(MissingUnit)
failures:
tests::trailing_number_is_an_error
test result: FAILED. 6 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Read it the way we read the first failure:
panicked at src/lib.rs:144:9points at theassert_eq!in the test. The line number is from the version without the check, which is three lines shorter.- The message is ours:
the 30 has no unit. It tells you what the test checks without opening the file. left: Ok(3600)is what the function really returned. It counted the hour and silently threw the30away. That’s worse than an error, because the caller gets a wrong number and no warning.right: Err(MissingUnit)is what we expected.- The
Running tests/integration.rsandDoc-testssections are missing. The unit tests failed, so Cargo stopped.
The fix is three lines after the loop. If a number is still waiting for its unit, it’s an error:
if number.is_some() {
return Err(ParseError::MissingUnit);
}
Ok(total)
}
Run cargo test again and all of it passes. That’s the output in the last section.
Two things are worth copying here. First, we saw the test fail before trusting it. A test you’ve only ever seen pass might not be checking anything. Second, there was a second safety net. The doc test with 90 also catches the bug. cargo test --no-fail-fast on the broken version prints test src/lib.rs - parse_duration (line 45) ... FAILED as well.
Worked example: an integration test can’t see private items
Say we want to test unit_seconds from tests/, and add a file tests/peek.rs:
#[test]
fn peek_at_a_private_function() {
assert_eq!(timespan::unit_seconds('h'), Ok(3_600));
}
cargo test doesn’t get as far as running anything. It prints:
error[E0603]: function `unit_seconds` is private
--> tests/peek.rs:3:26
|
3 | assert_eq!(timespan::unit_seconds('h'), Ok(3_600));
| ^^^^^^^^^^^^ private function
|
note: the function `unit_seconds` is defined here
Read it from the top:
E0603is the error code for using a private item.rustc --explain E0603gives the long version.- The arrow points at
unit_secondsintests/peek.rs, on line 3. - The note says where the function is defined. It’s in
src/lib.rs, withoutpub.
tests/peek.rs is a separate crate, and to another crate, private means invisible. The unit test in the tests module could call unit_seconds because it’s inside the library. This file isn’t.
There are three honest fixes:
- Test it from a unit test, as we did. The test stays inside the crate.
- Test it through the public API.
parse_duration("1x")already checks the unknown-unit path. - Make it
pub, but only if users should call it. Making something public just for a test adds it to your API, and changing it later can break other people’s code.
Tips and traps
- A test that passes the first time it runs. It might not be checking what you think. Break the code on purpose, or flip a value in the test, and watch it fail once. Then put it back.
#[should_panic]with noexpected. Any panic passes the test, including anunwrapon a real bug. Addexpected = "..."with part of the message you mean.- “Where did my
println!go?” The runner hides output from passing tests. Run with-- --nocapture, or read it in the failure report when the test fails. - A filter that skips doc tests.
cargo test parsedidn’t run the doc tests on Cargo 1.95. Run a plaincargo testbefore you push, so nothing is left out. - Tests that pass alone and fail together. They share something: a file, a directory, an environment variable. Give each test its own copy, such as a file name with the test’s name in it.
-- --test-threads=1hides the problem, but it doesn’t fix it. leftandrightswapped. Mixing the order between tests makes failures confusing to read. Put the value you got first and the value you expected second, everywhere.- Testing every private helper. Tests tied to private details break each time you restructure the code. Test mostly through the public functions, and add a unit test for a private helper only when its logic is tricky.
Put unit tests next to the code, integration tests in
tests/, and examples in doc comments, and letcargo testrun all three.
Exercises
Exercise 1. Without running it, decide what this prints:
fn main() {
let loud = "1h30m".to_uppercase();
assert_ne!(loud, "1H30M", "uppercasing should change the text");
}
Exercise 2. Here’s a function from a small calendar library, in src/lib.rs:
pub fn is_leap_year(year: u32) -> bool {
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
}
pub fn days_in_month(year: u32, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if is_leap_year(year) => 29,
2 => 28,
_ => panic!("month must be 1 to 12, got {month}"),
}
}
Write a unit test module with three tests: February 2024 has 29 days; 1900 is not a leap year, so February 1900 has 28 days; and month 13 panics with the right message.
Exercise 3. Add a doc test to days_in_month that shows month 13 panicking, so a reader of the docs sees it too.
Answers
1. to_uppercase returns the String "1H30M", which is equal to the text on the right, so assert_ne! panics. It prints both values with {:?}, which is why they have quotes. A String and a &str can be compared with ==, so the types don’t need to match exactly.
fn main() {
let loud = "1h30m".to_uppercase();
assert_ne!(loud, "1H30M", "uppercasing should change the text");
}
It prints:
panicked at src/main.rs:3:5:
assertion `left != right` failed: uppercasing should change the text
left: "1H30M"
right: "1H30M"
2. The module goes at the bottom of src/lib.rs. The first assert! in the 1900 test has a message, because assert! can’t print the values on its own:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn february_in_a_leap_year() {
assert_eq!(days_in_month(2024, 2), 29);
}
#[test]
fn february_1900_is_not_a_leap_year() {
assert!(!is_leap_year(1900), "1900 divides by 100 but not by 400");
assert_eq!(days_in_month(1900, 2), 28);
}
#[test]
#[should_panic(expected = "month must be 1 to 12")]
fn month_13_panics() {
days_in_month(2026, 13);
}
}
3. Mark the fence should_panic. The doc test is outside the crate, so it names the function with the crate name, calendar:::
/// Returns how many days a month has. Months are numbered 1 to 12.
///
/// ```should_panic
/// calendar::days_in_month(2026, 13);
/// ```
///
/// # Panics
///
/// Panics if `month` is not between 1 and 12.
pub fn days_in_month(year: u32, month: u32) -> u32 {
With both answers in place, cargo test prints:
Running unittests src/lib.rs
running 3 tests
test tests::february_1900_is_not_a_leap_year ... ok
test tests::february_in_a_leap_year ... ok
test tests::month_13_panics - should panic ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests calendar
running 1 test
test src/lib.rs - days_in_month (line 8) - should panic ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
What’s next
So far every value has had one owner, and a borrow has always ended before its owner did. In Part 20, we’ll meet the smart pointers that bend those rules safely: Box for values on the heap, Rc for shared owners, and RefCell for changing a value through a shared reference.