Sub topic 15
Documentation tests
This chapter assumes you can write unit and integration tests, you know how pub and use paths work, and you can run cargo test. It covers how Rust turns the code examples in your documentation into tests, how to hide or annotate parts of an example, and what usually goes wrong.
Why documentation tests exist
Examples in documentation go stale. A function gains a parameter, a type is renamed, and the README example no longer compiles. Nobody notices until a user complains.
Rust removes this problem. rustdoc, the documentation tool that ships with Cargo, finds every code block in your doc comments. cargo test compiles and runs each block. If an example stops compiling, or an assertion in it fails, the test run fails.
Doc tests have a second use. They check your public API from the outside, the way a user sees it. They sit between integration tests and documentation: small, readable, and tied to one item.
Doc comments
Rust has two kinds of doc comment:
///documents the item that follows it (a function, struct, enum, module, and so on).//!documents the item that contains it. You normally put it at the top ofsrc/lib.rsto document the whole crate.
Code in a doc comment goes in a Markdown fenced block. This chapter is itself written in Markdown, so the examples below use ~~~ fences inside the comments. rustdoc accepts tilde fences and treats them exactly like triple-backtick fences. In your own code, triple backticks are the usual choice.
// src/lib.rs
/// Adds two numbers.
///
/// ~~~
/// assert_eq!(my_geometry::add(2, 3), 5);
/// ~~~
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Run it with cargo test --doc. The output lists the test by file, item, and line:
running 1 test
test src/lib.rs - add (line 3) ... okHow a doc test is built
Each block is compiled as its own tiny crate. The crate links against your library the same way an outside user's crate would. That has three consequences:
- The block can only use public items.
- You must refer to your crate by name, for example
my_geometry::add, or bring it in withuse. - Every block compiles separately, so a library with many examples builds more slowly than one with many unit tests.
Before compiling, rustdoc does some preparation. If the block has no fn main, it wraps the whole block in one. It also adds extern crate your_crate; when needed.
The package name matters here. A package named my-geometry is imported as my_geometry, because Cargo turns hyphens into underscores.
Hiding setup lines
Real examples often need setup that distracts a reader. A line that starts with # (a hash and a space) is compiled and run, but left out of the rendered documentation.
// src/lib.rs
/// A length in whole meters. The field is private, so use [`Meters::new`].
pub struct Meters(u32);
impl Meters {
/// Creates a length.
///
/// ~~~
/// # use my_geometry::Meters;
/// let m = Meters::new(5);
/// assert_eq!(m.get(), 5);
/// ~~~
pub fn new(value: u32) -> Meters {
Meters(value)
}
/// Returns the stored number.
pub fn get(&self) -> u32 {
self.0
}
}Readers of the generated page see only the last two lines. The compiler sees all three. Use hidden lines for imports and setup. Don't hide the part you are teaching.
Using the question mark operator
Because the generated main returns (), the ? operator fails inside a plain example. The fix is a hidden last line that makes main return a Result:
// src/lib.rs
/// Parses a TCP port number.
///
/// ~~~
/// use my_geometry::parse_port;
///
/// let port = parse_port("8080")?;
/// assert_eq!(port, 8080);
/// # Ok::<(), std::num::ParseIntError>(())
/// ~~~
pub fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse()
}The hidden Ok::<(), ...>(()) line tells rustdoc to generate fn main() -> Result<(), ParseIntError>. You write the error type explicitly because the compiler can't infer it from ? alone. The visible example then reads like normal code that handles errors.
Block attributes
You can add attributes after the opening fence to change what rustdoc does with a block.
| Attribute | Compiles? | Runs? | Passes when |
|---|---|---|---|
| (none) | yes | yes | it compiles and does not panic |
| `should_panic` | yes | yes | it panics |
| `no_run` | yes | no | it compiles |
| `compile_fail` | tries to | no | compilation fails |
| `ignore` | no | no | never run, reported as ignored |
| `text` | no | no | not treated as Rust code at all |
Here are three of them in use:
// src/lib.rs
/// Integer division.
///
/// ~~~should_panic
/// my_geometry::divide(1, 0);
/// ~~~
pub fn divide(a: i32, b: i32) -> i32 {
a / b
}
/// Loads settings from disk.
///
/// ~~~no_run
/// let text = std::fs::read_to_string("settings.toml").unwrap();
/// println!("{text}");
/// ~~~
pub fn load_settings() {}
/// The private field blocks direct construction.
///
/// ~~~compile_fail
/// let m = my_geometry::Meters(5);
/// ~~~
pub struct Distance(u32);In the last example the doc test passes only because the code fails to compile. This documents a promise, such as "you cannot build this type directly". Be aware that compile_fail passes for any compile error, including a typo, so keep these blocks small and obvious.
Use ignore sparingly. An ignored example is not checked, so it can go stale. If the example only needs to avoid running (network, files, long loops), prefer no_run, which still catches compile errors.
Where doc tests run and where they don't
- Doc tests work for library crates. A package that has only
src/main.rshas no library for the examples to link against, socargo testskips them. This is one reason to put logic insrc/lib.rsand keepmain.rsthin. cargo test --libruns only unit tests. It does not run doc tests. Usecargo test --docfor those.- Doc tests are collected from private items as well, but they still compile against the public API only. A doc test on a private function can't call that function.
- Doc tests can use your
[dev-dependencies], the same as integration tests.
Running and filtering
cargo test --doc
cargo test --doc parse_port
cargo test --doc -- --nocaptureThe second command filters by name. Doc test names look like src/lib.rs - parse_port (line 12), so a substring such as parse_port selects the matching tests. Line numbers change as you edit, so filter by item name and not by line.
Doc tests and re-exports
Your doc tests should use the path a user would type. If you shorten a path with pub use, write the examples against the short path:
// src/lib.rs
mod geometry;
pub use geometry::shapes::Square;
/// ~~~
/// use my_geometry::Square;
/// let s = Square(3);
/// assert_eq!(s.area(), 9);
/// ~~~
pub fn unit_example() {}If you later move the implementation to another private module, these examples keep passing, because only the public path matters. If a refactor accidentally changes the public path, the doc tests fail. That makes them a cheap guard on your API's shape.
Common errors
- The item is not
pub. The error is "functionxis private". Make it public, or test it in a unit test instead. - Missing the crate name.
add(2, 3)fails with "cannot find function". Writemy_geometry::add(2, 3)or add auseline. ?without the closingOkline. You get "the?operator can only be used in a function that returnsResult". Add the hiddenOk::<(), E>(())line.- A binary-only package.
cargo test --docreports that there is no library targets to test. Move the code tosrc/lib.rs. - A stray fence. A code block in a doc comment that is not Rust, such as shell output or a diagram, is treated as Rust and fails. Mark it
textorsh. - Overusing
ignore. The test run looks green while the example is broken.
Exercise
A library has pub fn half(n: u32) -> Result<u32, String>, which returns an error for odd numbers. Write a doc test that calls half(8) with the ? operator, asserts the result is 4, and does not fail to compile. What is the one extra line you need, and why?
Show answer
Use let h = my_crate::half(8)?;, then assert_eq!(h, 4);, then the hidden last line # Ok::<(), String>(()). Without it, rustdoc generates a main that returns (), and ? is not allowed there. The hidden line makes main return Result<(), String>, and the error type is written out because the compiler cannot infer it.