Sub topic 15
Documentation Tests
This chapter assumes you can write unit tests with #[cfg(test)], know the difference between a library crate and a binary crate, and can use pub use to re-export items. Documentation tests (doc tests) turn the examples in your doc comments into real tests.
What a doc test is
A doc comment starts with /// and documents the item that follows it. Markdown inside a doc comment can include a fenced code block. When you run cargo test, Rust extracts each block, compiles it, and runs it. If the code fails to compile or panics, the test fails.
This keeps examples honest. An example that drifts out of date breaks the build instead of misleading readers.
/// Adds two numbers.
///
/// ```
/// assert_eq!(my_geometry::add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}How rustdoc builds each example
Rustdoc compiles every example as its own small program, separate from your library. It links that program against your crate as an external dependency. Two consequences follow:
- The example can only use your public API, just like an integration test.
- You refer to your crate by name, as in
my_geometry::add, or bring it in withuse my_geometry::add;.
This is why re-exports matter. If you re-export a type with pub use, the doc test can import it from the short public path.
Hiding setup lines
Rustdoc wraps your snippet in a fn main() if it does not define one. You can also hide lines from the rendered documentation while still compiling them. Start a line with # (a hash and a space).
/// Parses a port number.
///
/// ```
/// # use std::num::ParseIntError;
/// # fn main() -> Result<(), ParseIntError> {
/// let port = my_geometry::parse_port("8080")?;
/// assert_eq!(port, 8080);
/// # Ok(())
/// # }
/// ```
pub fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse()
}Readers see only the two meaningful lines. The hidden lines make the ? operator legal by giving the example a Result return type.
Controlling how a block runs
You can add attributes after the opening fence to change how rustdoc treats a block.
| Attribute | Effect |
|---|---|
| `ignore` | The block is skipped and reported as ignored. |
| `no_run` | The block is compiled but not executed. |
| `should_panic` | The test passes only if the code panics. |
| `compile_fail` | The test passes only if the code fails to compile. |
| `text` | The block is not treated as Rust code. |
Use no_run for examples that touch the network or filesystem. Use compile_fail to show code that the borrow checker or privacy rules reject.
Common errors
- Forgetting the crate name. Writing
add(2, 3)without ausefails, because the example is a separate crate. - Documenting a private item. The example cannot call private functions, so it fails to compile.
- Using
?without aResultreturn. Add the hiddenfn main() -> Result<...>wrapper shown above. - Doc tests in a binary crate. Rustdoc only tests library crates. A package with only
src/main.rsruns no doc tests.
Running doc tests
cargo test --doc
cargo test --doc addThe first command runs only doc tests. The second filters them by item name.
Exercise
You wrote a doc example for a function in a package that has only src/main.rs. cargo test --doc reports no tests. Why, and what is the fix?
Show answer
Rustdoc runs doc tests only for library crates. Move the function into src/lib.rs, make it pub, and call it from the example by crate name. Keep main.rs as a thin caller.
Exercise
A doc example uses the ? operator and fails to compile with an error about the return type. How do you fix it without cluttering the rendered docs?
Show answer
Wrap the example in a hidden fn main() -> Result<(), ErrorType> using lines that start with "# ", and end with a hidden Ok(()) line.