Sub topic 7
Doc tests: examples that run as tests
This chapter assumes you can write a Rust library crate with pub functions, run cargo test, and use assert! and assert_eq!. It also assumes you know how to write /// doc comments with Markdown. The examples use a library crate named mycrate.
Why examples in docs go stale
Documentation examples are code that nobody compiles. A function gets a new parameter, the example keeps calling the old signature, and readers copy code that no longer builds.
Rust avoids this by compiling and running the code blocks in your doc comments. These are called doc tests. A doc test is a code block in a documentation comment that rustdoc (the documentation tool that ships with Rust) extracts, compiles, and runs as a test. If the example fails to compile or panics, the test fails. Your examples stay correct for as long as your test suite is green.
Your first doc test
Any fenced code block in a doc comment is treated as Rust unless you say otherwise. Here is a complete src/lib.rs:
/// Adds two numbers.
///
/// # Examples
///
/// ~~~
/// use mycrate::add;
///
/// assert_eq!(add(2, 3), 5);
/// ~~~
pub fn add(a: i32, b: i32) -> i32 {
a + b
}The fence inside the comment is written with ~~~ here, so it can sit inside this page's code block. In real projects you will usually see three backticks. Rustdoc accepts both, and everything in this chapter applies to either.
Run only the doc tests:
cargo test --docThe output looks like this:
Doc-tests mycrate
running 1 test
test src/lib.rs - add (line 5) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01sThe test name has three parts: the file, the item the comment documents (add), and the line where the code block starts.
cargo test with no flags runs unit tests, then integration tests, then doc tests. Use --doc when you want only the last group.
What rustdoc does with your block
Rustdoc does not run your snippet in place. It turns each block into a small program and compiles it separately.
- It finds every Rust code block in the documentation.
- If the block has no
fn main, it wraps the whole block infn main() { ... }. - It links the program against your library, as if the program were another crate depending on it.
- It compiles and runs the program. Exit status 0 means pass. A compile error or a panic means fail.
The diagram shows this flow.
Two consequences follow from this design.
- The example sees only your public API. The program is a separate crate, so it needs
use mycrate::add;just as a user would. Private functions andpub(crate)items are not reachable. This is the point: if the example compiles, a real user can write the same code. - Every block is its own program. One block cannot use variables or imports from another block, even in the same comment. Each block must contain everything it needs.
What counts as passing
A doc test passes when the program exits normally. Rustdoc does not compare printed output against anything. If you write this, the test passes whatever add returns:
/// ~~~
/// use mycrate::add;
///
/// println!("{}", add(2, 3)); // checks nothing
/// ~~~
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Use assert! or assert_eq! to check behavior. If you only want to show output to the reader, a println! is fine, but add an assertion next to it if the value matters.
Reading a failure
Change the assertion to assert_eq!(add(2, 3), 6); and run cargo test --doc again. The output will be similar to this:
running 1 test
test src/lib.rs - add (line 5) ... FAILED
failures:
---- src/lib.rs - add (line 5) stdout ----
Test executable failed (exit status: 101).
stderr:
thread 'main' panicked at src/lib.rs:7:1:
assertion `left == right` failed
left: 5
right: 6
failures:
src/lib.rs - add (line 5)
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered outExit status 101 is how a Rust program reports a panic. The stderr section shows the panic message from the generated program. A compile error looks different. You get the compiler's diagnostic with line numbers relative to the generated program, so they may be offset from the line in your file. Use the (line N) in the test name to find the block.
Running a subset
Doc tests are slower than unit tests because each one needs its own compile and link step. When you are working on one function, filter by name:
cargo test --doc addOnly tests whose names contain add run. The name includes the item path, so you can also filter by module, such as cargo test --doc parser::.
What is and is not tested
Rustdoc tests more than you might expect, and less than you might hope.
| Content | Tested? |
|---|---|
| Fenced block with no language | Yes, as Rust |
| Fenced block marked `rust` | Yes |
| Fenced block marked `text`, `toml`, `json`, `sh`, and so on | No |
| Indented code block (four spaces) | Yes, as Rust |
| Code in a `//` comment (not `///`) | No |
| Examples in documentation of private items | Compiled and run, but they cannot import private items |
The indented-block rule catches people. If you indent a sample directory listing or a log excerpt by four spaces in your Markdown, rustdoc tries to compile it as Rust and fails. Mark non-Rust content with a fence and a language such as text:
/// Writes the report to disk. The file looks like this:
///
/// ~~~text
/// name,count
/// apples,3
/// ~~~
pub fn write_report() {}Doc tests also run only for library targets. A package that has only src/main.rs has no doc tests, and cargo test --doc reports that no library targets were found. If you want doc tests for the logic in a binary crate, move that logic into src/lib.rs and call it from main.
Common errors
unresolved importorcannot find function. The example uses a name without importing it. Adduse mycrate::name;. Remember that the crate name uses underscores if the package name has hyphens: packagemy-crateis imported asmy_crate.function is private. The item is notpub, or it ispubinside a private module and not re-exported. Fix the visibility or re-export the item. A user could not call it either.- A passing test that proves nothing. The block has no assertion, so any behavior passes. Add an assertion.
- A sample failing to compile because it was never meant to be Rust. Add a language to the fence, such as
text. - A block depends on a previous block. Each block is a separate program. Repeat the setup in each block. The next chapter covers hiding repeated setup lines from readers.
Writing examples worth testing
A doc test serves two readers, the person reading rendered HTML and the compiler. Write for the first, and let the second keep you honest.
- Show the typical call first, then edge cases the reader might trip over.
- Keep each example short. If a block needs 30 lines of setup, the reader will skip it.
- Prefer
assert_eq!over comments like// returns 5. A comment can go stale, but an assertion cannot. - Treat a failing doc test like a failing unit test. It means either the code or the documentation is wrong, and both are worth fixing.
Summary
A code block in a /// comment is a test. Rustdoc wraps it in fn main if needed, compiles it against your library as a separate crate, and runs it. The test passes on a clean exit and fails on a compile error or panic. Each block is independent and sees only public items. Run the tests with cargo test --doc, narrow them with a name filter, and mark non-Rust blocks with a language so they are skipped.
Exercise
A package has the name text-utils and a pub fn shout(s: &str) -> String in src/lib.rs. Write a doc comment with one doc test showing that shout("hi") returns "HI!". Then say what cargo test --doc shout does.
Show answer
The block must import the function using the underscore form of the crate name, and it must assert the result:
/// ~~~
/// use textutils::shout;
///
/// asserteq!(shout("hi"), "HI!");
/// ~~~
cargo test --doc shout compiles and runs only the doc tests whose names contain "shout", skipping unit tests, integration tests, and other doc tests. The test passes if the program exits normally and fails if it fails to compile or the assertion panics.
Exercise
A doc comment contains an indented block, four spaces in, showing a sample log line: ERROR disk full. cargo test --doc fails on it with a compile error. Why does it fail, and how do you fix it without removing the sample?
Show answer
Rustdoc treats indented code blocks as Rust and tries to compile them, and ERROR disk full is not valid Rust. Replace the indented block with a fenced block that names a non-Rust language, such as text. Rustdoc skips blocks whose language is not Rust, so the sample stays in the rendered docs and is no longer compiled.
Exercise
Why can a doc test not call a function that is pub(crate), even though the doc comment sits right above it?
Show answer
Rustdoc compiles each doc test as a separate program that links against the library like any other dependency. The program is outside the crate, so it can use only the public API. pub(crate) items are invisible to it.