On this page
The short answerWhere mdBook keeps examplesWhat mdbook test coversClassify the examples before scanningMake a scan-ready copyCatch untagged output before it reaches rustdocTriage failures in contextA pasteable review checklistThe sources we checkedFAQThe short answer
Use mdbook test to check the Rust examples in an mdBook, then test the shell, Python, JavaScript and configuration examples through their own appropriate checks. DocsAlive can help run supported non-Rust blocks and classify their failures, but engine 0.6.3 reads raw Markdown without expanding mdBook directives. For books that use includes or hidden lines, build the Markdown renderer output, prepare a scan-ready copy and scan that copy. Keep the original chapter and listing files in review, because generated-copy line numbers point to the copy.
Where mdBook keeps examples
An mdBook repository normally has a book.toml configuration file and a src/ directory. The src/SUMMARY.md file defines the chapter navigation, while chapter Markdown files hold the prose and fenced examples. A book can also keep complete programs in a listings folder and include all or part of those files in a chapter.
That layout gives maintainers two related things to check: the source a reader sees in the rendered book and the file or snippet that actually runs. A listing can change without its surrounding explanation changing. An API can move while the chapter still shows an old import. A setup line can be hidden from the rendered page even though the test needs it. Shell and Python steps can remain untouched because the Rust test command does not execute them.
The following setup uses the tested Linux x86_64 release of mdBook 0.5.4 and creates a small book. It downloads a binary, so run it only in an environment where that download is appropriate.
MDBOOK_VERSION=v0.5.4
curl -sSL "https://github.com/rust-lang/mdBook/releases/download/${MDBOOK_VERSION}/mdbook-${MDBOOK_VERSION}-x86_64-unknown-linux-gnu.tar.gz" | tar -xz
export PATH="$PWD:$PATH"
mdbook --version
mdbook init example-book --title "Example Book" --ignore none
The generated book contains book.toml, src/SUMMARY.md and src/chapter_1.md. The configuration below enables HTML output, declares a Python hidden-line prefix and enables the Markdown renderer. The Markdown renderer is included with mdBook but disabled by default; it runs preprocessors and writes resulting Markdown.
[book]
title = "Example Book"
authors = []
language = "en"
[output.html]
[output.html.code.hidelines]
python = "~"
[output.markdown]
The next listing is a complete Rust file with an anchored region. The anchor allows a chapter to include the function without necessarily displaying the rest of the file. Test the whole listing as well as the chapter: a passing isolated file and a passing chapter answer related but different questions.
// ANCHOR: area
fn area(width: u32, height: u32) -> u32 {
width * height
}
// ANCHOR_END: area
fn main() {
assert_eq!(area(3, 4), 12);
println!("area = {}", area(3, 4));
}
This Python listing supplies a separate example for inclusion. Running the file directly checks the complete file; checking a rendered chapter also matters because the chapter may include only part of a file or add context around it.
settings = {"retries": 3, "timeout_s": 10}
print(settings["retries"])
The chapter below combines the forms that make mdBook testing distinctive. It includes Rust test attributes, hidden Rust setup, an anchored Rust listing, a Python listing, hidden Python setup and an inline shell step.
# Chapter 1
A function with a hidden `main`. mdBook hides the lines that start with `# `
in the rendered page, and `mdbook test` still compiles them.
```rust
# fn main() {
let total: u32 = [1, 2, 3].iter().sum();
assert_eq!(total, 6);
# }
```
This example should panic, and the test passes only if it does.
```rust,should_panic
let v: Vec<u32> = Vec::new();
let _first = v[0];
```
This one is compiled but not run.
```rust,no_run
use std::net::TcpListener;
let _listener = TcpListener::bind("127.0.0.1:0").unwrap();
```
This one is not compiled at all.
```rust,ignore
let x = undefined_function();
```
Code pulled in from a file, by anchor:
```rust
{{#include ../listings/area.rs:area}}
# fn main() { assert_eq!(area(2, 5), 10); }
```
A Python file pulled in the same way:
```python
{{#include ../listings/settings.py}}
```
A Python block with a hidden setup line (the prefix comes from book.toml):
```python
~import math
print(math.sqrt(16))
```
A shell step written inline:
```bash
python3 -c 'print(sum([1, 2, 3]))'
```
In Rust fences, lines beginning with # are hidden in HTML but still compiled by the Rust documentation test. should_panic expects a panic, no_run compiles without executing, and ignore leaves the example untested. For other languages, a book can set a hidden-line prefix in configuration or on an individual fence. Hidden setup can make an example runnable while leaving readers without a prerequisite, so inspect both the rendered page and the source.
The include directive can select a whole file, line ranges or named anchors. mdBook also provides the rustdoc_include directive and the playground directive. Its preprocessors expand these at build and test time. When a listing changes, review its anchors and the explanation beside every inclusion; the fact that a file still runs does not establish that a chapter still teaches the right behavior.
What mdbook test covers
Run the book's Rust documentation tests from the book directory:
mdbook test
In the checked example, the command succeeded and reported the chapter being tested:
INFO Testing chapter 'Chapter 1': "chapter_1.md"
The underlying Rust documentation test considered five Rust examples: four passed and one was reported ignored. The no_run example was compiled, and the should_panic example was expected to panic. The Python and shell blocks were not tested. The mdBook test reference describes Rust as the supported test language; the Rust documentation test reference explains the test attributes.
A fence without a language is also treated as Rust by the Rust documentation test. That default is useful for Rust prose, but it can turn a displayed result into a compilation failure. Label output and other non-Rust material deliberately, and separately decide whether the label reflects runnable code, configuration or an illustration.
The next command deliberately breaks the assertion in the hidden-main example. Restore the expected value before continuing with a working book.
sed -i 's/assert_eq!(total, 6);/assert_eq!(total, 7);/' src/chapter_1.md
mdbook test
The failure below shows that the hidden lines did not hide the assertion from the test. The command exited with status 101.
running 5 tests
test chapter_1.md - Chapter_1 (line 29) ... ignored
test chapter_1.md - Chapter_1 (line 22) - compile ... ok
test chapter_1.md - Chapter_1 (line 15) ... ok
test chapter_1.md - Chapter_1 (line 35) ... ok
test chapter_1.md - Chapter_1 (line 6) ... FAILED
thread 'main' panicked at chapter_1.md:4:1:
assertion `left == right` failed
left: 6
right: 7
test result: FAILED. 3 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.16s
This is a useful regression check for Rust API drift, but it is not evidence that the entire chapter works. A successful Rust test leaves the documented installation, shell commands, Python code and any external service behavior to other checks. A no_run result also leaves runtime behavior untested, and an ignored block needs a separate owner and reason.
Classify the examples before scanning
Treat a chapter as a sequence of reader actions and examples, not as one uniform collection of code. The classification determines what a passing result can establish.
| Block form | What mdbook test does | What the engine does in 0.6.3 |
|---|---|---|
| Rust fence | Compiles and normally runs a Rust documentation test | Recognizes Rust and skips it as not executable |
Rust with should_panic |
Expects the test to panic | Reads the language as Rust, ignores the attribute and skips it |
Rust with no_run |
Compiles without running | Ignores the attribute and skips the Rust block |
Rust with ignore |
Reports it ignored rather than testing it | Ignores the attribute and skips the Rust block |
| Untagged fence | Treats it as Rust, including when it contains displayed output | Treats it as text and skips it |
| Python or shell fence | Does not test it | Plans supported code for execution; raw mdBook syntax can cause false failures |
| Included code | Expands the directive before its Rust test | Reads the raw directive rather than the included file |
| TOML configuration | Does not run it as Rust when labeled TOML | Parses TOML syntax, without checking whether keys are meaningful to mdBook |
An illustrative configuration block may be valid TOML while using an obsolete or meaningless setting. A displayed output block is evidence for a human to review, not a program to execute. An included file deserves a direct test as well as a check of the chapter that presents it. A runnable Python or shell block needs its prerequisites, working directory and dependencies stated clearly enough that a reader can reproduce the path.
Engine 0.6.3 treats an mdBook as plain Markdown; it does not detect book.toml as a framework configuration. It scans Markdown pages, not the listing files or rendered HTML. It takes the language from the first part of a fence label and ignores attributes after a comma. Recognized Rust is skipped, so keep mdbook test or an appropriate cargo test for Rust listings.
On the raw example chapter, both Python blocks failed as invalid syntax: one contained an unexpanded include directive and the other contained the hidden-line prefix. Those are false failures caused by mdBook syntax, yet invalid syntax is counted as a likely documentation bug. A shell block containing only an include directive failed as missing-tool, which is not a documentation bug category. This is a real limitation of engine 0.6.3 and was not fixed during the current product freeze.
The engine executes supported Python blocks in page order in a shared interpreter and runs shell blocks in a shell. It compares printed output only in Python pycon or python-repl sessions. An unrecognized fence label can be reported as passing without being run or parsed, another known 0.6.3 limitation. Check the language and the stated result, not only its color.
Make a scan-ready copy
The verified workaround starts with mdBook's Markdown renderer. It expands includes into book/markdown/, but it retains configured hidden-line prefixes. The following script copies that output, removes the configured prefixes and flags untagged fences and unexpanded directives for review. It is a repository-specific helper: review its assumptions if your book uses per-block hidden-line settings or more complex fence layouts.
"""Make a scan-ready copy of an mdBook's Markdown output.
Reads book/markdown (written by the [output.markdown] renderer, so includes are
already expanded), removes the hidden-line prefixes set in book.toml for
non-Rust languages, and reports what a Markdown code scanner would trip on.
"""
import pathlib
import re
import shutil
import sys
import tomllib
src = pathlib.Path("book/markdown")
dst = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "scan-docs")
config = tomllib.loads(pathlib.Path("book.toml").read_text(encoding="utf-8"))
hide = config.get("output", {}).get("html", {}).get("code", {}).get("hidelines", {})
FENCE = re.compile(r"^(`{3,}|~{3,})(.*)$")
if not src.is_dir():
sys.exit("book/markdown is missing: add [output.markdown] to book.toml and run mdbook build")
shutil.rmtree(dst, ignore_errors=True)
problems = 0
for page in sorted(src.rglob("*.md")):
out, fence, lang = [], None, ""
rel = page.relative_to(src)
for n, line in enumerate(page.read_text(encoding="utf-8").splitlines(), 1):
m = FENCE.match(line)
if fence is None and m:
fence = m.group(1)
lang = m.group(2).strip().split(",")[0].split()[0] if m.group(2).strip() else ""
if lang == "":
problems += 1
print(f"{rel}:{n}: fence with no language; mdbook test compiles it as Rust")
elif fence and line.strip() == fence:
fence, lang = None, ""
elif fence:
prefix = hide.get(lang)
if prefix and line.lstrip().startswith(prefix):
line = line.replace(prefix, "", 1)
if "{{#" in line and lang != "rust":
problems += 1
print(f"{rel}:{n}: unexpanded mdBook directive in a {lang or 'plain'} block")
out.append(line)
target = dst / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("\n".join(out) + "\n", encoding="utf-8")
print(f"wrote {dst}/ from {src}/; hidden-line prefixes removed for: {', '.join(sorted(hide)) or 'none'}")
print(f"{problems} problem(s)")
sys.exit(1 if problems else 0)
The helper removes and recreates its destination, so choose a generated directory whose existing contents can be replaced. Build, make the copy and plan a scan as follows:
mdbook build
python3 scripts/mdbook_scan_copy.py scan-docs
docsalive scan . --docs-dir scan-docs
On the checked book, the helper reported that it wrote the copy and found no flagged problems:
wrote scan-docs/ from book/markdown/; hidden-line prefixes removed for: python
0 problem(s)
The scan command shown plans the work; without --execute, it does not run the blocks. The plan found one page and eight blocks: five Rust blocks skipped and three non-Rust blocks to run. When the scan-ready page was executed, both Python blocks and the shell block passed. That result is specific to this small book and its environment.
Select the copy explicitly. Without a top-level docs/ folder or a chosen docs directory, scanning the book root found three pages: the source summary, the source chapter and the generated Markdown chapter. That picked up the chapter's code twice. The Markdown renderer output did not contain a summary page. Findings on the copy use generated-file line numbers, so trace each finding back to the source chapter or listing before editing.
Catch untagged output before it reaches rustdoc
The next example deliberately adds an untagged output fence. It is broken on purpose: the helper should flag it, and the Rust documentation test can try to compile the displayed text.
printf '\nRunning it prints:\n\n```\narea = 12\n```\n' >> src/chapter_1.md
mdbook build
python3 scripts/mdbook_scan_copy.py scan-docs
The helper exits with status 1 and identifies the untagged fence in the generated chapter:
chapter_1.md:64: fence with no language; mdbook test compiles it as Rust
wrote scan-docs/ from book/markdown/; hidden-line prefixes removed for: python
1 problem(s)
In the checked example, mdbook test also failed because it attempted to compile that displayed result as Rust. Label the material according to its purpose, then review it against the example by an appropriate check. The helper flags the ambiguity; it does not establish that an output value is correct.
The following GitHub Actions YAML is illustrative. Its run steps were checked in order, but adapt the paths and environment to the repository. It tests Rust and builds the scan-ready copy; it does not itself execute a product scan.
name: mdbook-examples
on:
pull_request:
paths:
- "src/**"
- "listings/**"
- "book.toml"
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Install mdBook 0.5.4
run: |
mkdir -p "$HOME/.local/bin"
curl -sSL "https://github.com/rust-lang/mdBook/releases/download/v0.5.4/mdbook-v0.5.4-x86_64-unknown-linux-gnu.tar.gz" | tar -xz -C "$HOME/.local/bin"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: Test the Rust examples
run: mdbook test
- name: Build and make the scan-ready copy
run: |
mdbook build
python3 scripts/mdbook_scan_copy.py scan-docs
Include changes to listings and book configuration in the same review as chapter changes. A scheduled run can find dependency drift between edits; a pull request check can catch a regression before a chapter or listing change is merged. The documentation testing checklist and GitHub Actions guide give broader coverage ideas.
Triage failures in context
A failed command is a reason to investigate, not automatically proof of a documentation defect. Start with the source and the environment, then distinguish a reader-facing error from a limitation of the test.
| Finding | What to investigate | Typical action |
|---|---|---|
| Rust assertion or compile failure | API version, changed listing, hidden setup and intended behavior | Correct the example or its surrounding instructions; rerun the Rust test |
| Invalid syntax from a raw include or hidden prefix | Whether mdBook syntax reached the scanner without preprocessing | Build and scan the prepared copy; do not file the raw result as a real syntax defect |
| Missing tool from a raw shell include | Whether the scanner attempted to execute the directive itself | Expand the include through the renderer and rerun |
| Missing install step | Whether the reader is actually told to install the dependency | Add or clarify the prerequisite when the page needs it |
| Untagged displayed result | Whether rustdoc is compiling text intended as output | Label and review the block according to its purpose |
| Failure requiring a credential or external service | Whether a safe, separate authorized check covers the flow | Record the coverage gap and review the result rather than treating it as an automatic docs bug |
For supported non-Rust examples, DocsAlive runs blocks in isolated page environments and classifies failures using the error. Review likely documentation bugs alongside missing fixtures, external failures, timeouts and intentional fragments. The findings reference explains the categories, and the CLI reference describes execution and scan scope.
The product fits around the Rust tests: use it for supported non-Rust blocks and setup steps once the Markdown is suitable for scanning. It does not turn an mdBook build into a complete reader journey test. Check rendered navigation, missing context, listing anchors and the accuracy of the prose separately. For Rust examples outside an mdBook, see the Rust docs testing guide. If you maintain a public book and want an outside report, the health check is a one-off check of up to 40 documentation pages. For another browser-rendered documentation system with different source boundaries, see testing Docsify examples.
A pasteable review checklist
Copy this into a change description or issue and adapt it to the book:
[ ] Identify changed chapters, listings, anchors and book configuration.
[ ] Run mdbook test and investigate failures and ignored Rust examples.
[ ] Test complete Rust listings with the repository's appropriate Rust checks.
[ ] Review hidden setup against the prerequisites visible to readers.
[ ] Label output and other non-Rust fences deliberately.
[ ] Build the Markdown renderer output and prepare a scan-ready copy.
[ ] Review unexpanded directives and untagged fences flagged by the helper.
[ ] Scan only the prepared directory and execute supported non-Rust blocks.
[ ] Trace generated-file findings back to the chapter or listing source.
[ ] Review missing tools, credentials, fixtures and external failures in context.
[ ] Check the rendered book and record remaining coverage gaps.
The sources we checked
These sources were read on November 12, 2026. Engine behavior was checked against engine 0.6.3 on the same day.
| Source | What it covers |
|---|---|
| mdBook test command | Rust documentation testing through mdBook |
| mdBook format | Chapter format, includes and code presentation |
| mdBook renderers | Renderer configuration and Markdown output |
| Rust documentation tests | Rust test attributes and hidden lines |
| mdBook 0.5.4 release | The release used in the checked example |
FAQ
Does mdbook test run Python and shell examples?
No. It supports Rust documentation tests. Use separate checks for Python, shell and other languages, including their setup steps and dependencies.
Are ignored Rust blocks tested?
No. An ignore attribute leaves the block untested. Record why it is ignored and decide whether a separate check can cover the behavior.
Why did a Python include fail as invalid syntax?
Engine 0.6.3 reads the raw Markdown directive rather than expanding it. Build the Markdown renderer output, remove configured hidden-line prefixes in a scan-ready copy and scan that copy.
Why can an untagged output block break mdbook test?
The Rust documentation test treats an untagged fence as Rust. Label displayed results deliberately and review their correctness with an appropriate separate check.
Does a passing scan prove that a listing and its explanation agree?
No. Run complete listing files where appropriate, check the included region and review the rendered explanation. A scan result covers only the blocks and checks reported for that run.
Where should a finding in the scan-ready copy be fixed?
Trace the generated line back to the source chapter or included listing and make the correction there. The copy is generated and its line numbers do not necessarily match the source.




