Guide

Testing Sphinx documentation examples

Keep Sphinx's own builders for reStructuredText doctests and links, and be clear about which Markdown fences actually get executed.

Published
Updated
November 10, 2026
Reading time
14 min
Facts checked against
Sphinx directives, builders and sphinx-build, Python doctest and MyST Parser documentation (November 9, 2026)
Outlined documentation pages with a lime pulse line running out of the stack
On this pageThe short answerIdentify how the code reaches the pageUse Sphinx builders for their own checksUnderstand Python doctest outputChoose Markdown fences deliberatelyMake coverage visibleReview the source-to-result chainKeep the evidence currentTriage failures before changing a pageChecklist for a documentation example testWhat this does not replaceThe sources we checkedFAQ

The short answer

Test Sphinx documentation examples according to how they are authored. Keep Sphinx's doctest builder for doctests in reStructuredText pages, and run the linkcheck builder separately for external links. For Markdown pages, including MyST Markdown, use a scan that actually reads those files and inspect the fences it plans. A documentation build, an external link check and a code execution check answer different questions.

DocsAlive does not detect Sphinx or read .rst files. In a Sphinx project with no other recognized framework configuration it falls back to plain Markdown mode and reads .md, .mdx and .markdown pages. Plain python and pycon fences can be run; a MyST directive fence that opens with {code-block} followed by python is treated as text. It does not run Sphinx or its builders. Choose plain fences when execution by the product is the goal, and retain the native Sphinx checks for the rest.

Start with the docs testing overview and how it works. The Python guide covers the language-specific environment, while the TypeScript guide explains a different type-checking boundary. For a ReadMe platform export, see ReadMe documentation testing.

Identify how the code reaches the page

Sphinx supports several ways to show highlighted code. The directives reference distinguishes reStructuredText literal blocks, doctest blocks, the code-block directive and literalinclude. A doctest block shows an interactive Python session; the other approaches can show other languages. The choice affects both the source to review and the test that can find it.

A literal block places the text in the document. A highlight directive sets the highlighting language for subsequent literal blocks until another such directive appears. The setting is presentation information: it does not establish that the text runs or that its output is correct. A long page may change highlighting partway through, so identify the applicable setting before interpreting an unlabeled block.

The code-block directive accepts a language, and sourcecode and code are directive names for the same purpose. It gives authors control over individual blocks, including presentation options. That is useful when a page contains examples in multiple languages. A block can look convincing and still reference an outdated import or omit an installation step. Review the source and test the reader's sequence as well as the presentation.

literalinclude draws text from another file. The referenced file is normally relative to the current document, while an absolute path is relative to the top source directory. Options can select portions of that file. Record the included source and the selection when planning a test: executing a whole file does not necessarily test exactly the excerpt shown to a reader, and a correct excerpt can still depend on setup omitted from its surrounding page.

Inventory each form separately. For every page, note the authoring file, any included source, the language, the required environment and the result promised. Also identify generated or assembled content your site uses, and confirm which source supplies each example. The framework guide explains what the product detects, and the MkDocs guide offers a comparison for a different source format.

Use Sphinx builders for their own checks

The Sphinx builder reference describes the doctest builder as running the documentation's doctests when the sphinx.ext.doctest module is enabled in conf.py. Select it with sphinx-build -b doctest, providing the source and output directories. This is a Sphinx check, using the project's Sphinx configuration. Its result is evidence about the doctests it runs, not proof that every displayed code block was executed.

The linkcheck builder checks the integrity of external links. It answers a different question from the doctest builder. A working external link does not demonstrate that an example using the linked library works, and successful doctests do not establish that external links remain intact. Keep the results separately visible so the person reviewing a change can identify the relevant problem.

The sphinx-build reference explains that the command reads configuration from the source directory and selects a builder with -b. A normal HTML build produces documentation; it is another useful check of the site. Inspect the generated result when a change affects formatting, included text or navigation. None of these separate signals should be described as an end-to-end test of every reader journey.

Understand Python doctest output

Python's doctest module finds interactive examples beginning with >>>, runs them and compares their output with the expected output shown in the text. That comparison makes an example both an instruction and an assertion about the displayed result. Check that the expected output is stable and actually important to the reader. A changed value may be a real behavior change; incidental variation needs a deliberate treatment rather than a blind update.

A doctest is most useful when its inputs, setup and expected result are clear. Keep the example small enough to understand, but do not remove context that a reader needs. If a snippet relies on earlier state, record the intended sequence and verify it under the same assumptions as the test. A doctest result speaks to the examples and conditions it covers, not to unmarked shell commands or arbitrary illustrated fragments on the page.

Choose Markdown fences deliberately

The MyST code reference describes ordinary fenced code with a language identifier for highlighting. It also describes a directive-style code block with options such as a caption or emphasized lines. Those forms can both present code, but their source text is different. The product takes the first word of a fence's info string as its language, so {code-block} is not recognized as python.

This fictional page excerpt uses plain fences. The package is illustrative; use a real package and its documented setup in your own project.

# Work with the demo

```python
from acme_docs_demo import greeting
message = greeting("reader")
print(message)
```

```pycon
>>> 2 + 2
4
```

DocsAlive plans supported blocks in page order in a fresh container for each page. It runs Python fences and executes pycon sessions line by line, comparing printed output. The import above requires a real installed package to succeed; a fictional name makes the illustration clear, not an executable dependency. If a test harness supplies setup, record it beside the test so a missing instruction for readers does not become invisible.

A directive fence is useful when its presentation options are needed, but the product treats that fence as text and does not run it. A plain fence is the choice to make when the same source block should be selected by this scan. If a directive or included file must remain, keep it and add a separate appropriate test of the reader-visible content. Check the actual report to confirm which file, line and language were planned.

A generic CI outline

Run these commands from a repository root with Sphinx, the project dependencies and the product CLI already available. Replace the directories with the real source and build paths. The doctest module must be enabled in the Sphinx configuration for the doctest builder to run doctests.

sphinx-build -b html docs build/html
sphinx-build -b doctest docs build/doctest
sphinx-build -b linkcheck docs build/linkcheck
docsalive scan . --execute --include 'docs/**' --out docs-test-report

The scan only reads eligible Markdown files in its docs directory. If the source directory differs from the detected directory, use --docs-dir deliberately and check the include pattern. The CLI reference explains selection, --setup, and reports. A scan without --execute extracts and plans rather than executing, so make the execution choice explicit in CI.

Read the HTML build, doctest, linkcheck and scan results as separate evidence. Record the revision, dependency setup and any failures or skips. Run the checks on a documentation change and when the underlying package changes; repeat them later to find drift. If a check requires a service or credential, identify a separate safe environment for that path instead of assuming a local example run covers it.

Make coverage visible

A mixed Sphinx repository often contains .rst pages, Markdown pages and code in separate files. List the sources each check covers before interpreting a green result. The product does not extract indented literal blocks, reStructuredText code-block directives, literalinclude content or Sphinx doctest blocks. It does not use the Sphinx configuration, toctree, directives or builders. It reads eligible Markdown source directly, without rendering the site.

For .rst doctests, retain the Sphinx doctest builder and inspect its result. For included source, test the relevant file and selected excerpt with a suitable project-owned check. For Markdown, inspect the product report for executed blocks and omissions. For every remaining item, name an owner and a way to check it; this is especially important for a prominent installation or first-use path.

A page can also contain several dependent steps. The product preserves page order for planned blocks, but a page container is fresh. Explicitly document prerequisites and do not assume variables or files from another page exist. For a journey that spans pages, write a separate test that follows the full sequence and keeps the necessary state. The guide index and free tools guide can help identify complementary checks.

Review the source-to-result chain

A useful review starts at the page a reader sees and works backward. Identify the source page, the code as displayed, any file supplying included text and the expected outcome. Then work forward from the repository through the relevant build or test. This chain makes it clear whether a failure belongs to the source, the inclusion, the example's dependencies or the output shown on the page.

When the same code is included in more than one page, inspect each surrounding explanation. One page may introduce an environment variable or file that another page never mentions. A standalone check of the shared source is valuable, but it cannot prove that both pages give readers the context needed to use the excerpt. Conversely, a correct page introduction does not prove that the included source is current. Keep both checks when they answer different questions.

Doctest output needs similar care. Treat expected output as part of the documentation contract when the page relies on it to explain behavior. Compare the actual result in the intended environment and ask whether a difference changes the reader's understanding. For values that naturally vary, provide an explanation and choose a test that checks the meaningful property. Preserve enough evidence for a reviewer to decide why a changed output is acceptable.

A Sphinx project can also contain Markdown that is not part of the intended published documentation. A source scan and a site build can therefore have different scopes. Select the docs directory and include patterns intentionally, compare the report with the site's source inventory and explain any differences. The fact that a file was eligible for scanning does not alone show that it appeared in the built site; a build result and source report should be read together.

For a release, identify the package or artifact against which the examples should run. A development checkout may expose an API that is not in the package readers install. Repeat the relevant checks against the intended artifact, record the setup and verify a representative new-reader path. When the project changes dependencies, investigate differences before changing expected output or weakening a check. This makes a result useful to both the documentation author and the package maintainer.

Review the plan before focusing on the final count. A skipped block can be a deliberate fragment, an unselected alternative or unsupported content; each has a different implication. Note whether the excluded example is prominent, what a reader would need to run it and who owns its separate test. An inventory that lists these boundaries is more useful than a single green indicator with no explanation of what was omitted.

Keep the evidence current

Give each important check an owner and a trigger. A documentation change can alter the instructions; a package release can change an import or output without changing the page. Revisit the inventory for both kinds of change, and inspect the first failure before deciding how much downstream evidence remains useful. Record the artifact, setup and revision with the result so another maintainer can reproduce it.

A small representative check is a useful beginning, but prominent reader paths deserve complete coverage. Include setup, the action and the expected result, then add separate checks for alternatives or environments that matter. When a path remains untested, say what is missing and why. Revisit that decision when the documentation or its audience changes.

Triage failures before changing a page

A failing block is a starting point for investigation. Read the actual error, the documented prerequisites, the selected block and the environment together. A missing package in the test environment may point to an omitted installation instruction, an intentional prerequisite, or an incorrect setup choice. Reproduce the smallest reader journey before deciding which explanation fits.

Finding What to investigate Next action
api-drift An import, attribute or argument differs from the installed API Reproduce with the intended package and correct the example or prerequisite
invalid-syntax A complete example does not parse Fix the code and distinguish deliberate fragments from complete examples
stale-output The code runs but shown output is from an older runtime Check the promised result before updating the page
package-not-found A documented package name cannot be found Verify the package name and the reader's installation path
missing-install-step A package is imported without a page install step Review the hint and clarify setup if readers need it
needs-credentials The example requires a credential Record the gap and arrange a separate authorized check
missing-fixture or depends-on-context A file or earlier context is required Trace the reader's setup and reproduce it explicitly
unsupported-syntax, unsupported-lang or alt-variant Content was not judged or an alternative was skipped Record the missing coverage and choose another check

A timeout, runtime error or external network result can need human review. An output difference may reflect a changing timestamp or ordering, but it may also reveal a change that matters to readers. Keep the expected and actual output with the finding. Do not update a result merely to turn a report green; establish what the page promises first.

The report makes these decisions easier to trace. Its JSON findings identify the page, line, language, status, category and reason, with a hint and evidence where supplied. The summary includes a count of likely documentation bugs. A pass can mean execution or a syntax check, while warn, fail and skip each require their own interpretation. Read the plan and the reason rather than treating all statuses as equivalent.

A reproducible fix should identify the installed artifact and any setup provided outside the page. Run the relevant check again after changing the source, and look for the next failure in the same sequence. If a page depends on an earlier page, test that longer journey separately: a fresh environment per page makes missing local setup easier to spot, but it does not establish the whole cross-page path.

Checklist for a documentation example test

Check Evidence to retain
Identify the source and intended reader journey File, page, prerequisites and expected result
Inventory examples and their languages Blocks in scope and those outside the scan
Set up a clean environment Dependency artifact and any setup supplied by the test
Follow dependent instructions in order First failing step and preceding state
Test the promises made by the page Actual result alongside stable expected output
Run the relevant site or language checks Separate results and configurations for each check
Inspect alternatives and unsupported content Selected path, skips and a plan for important gaps
Triage before editing Error, category, reproduction and decision
Verify the change Changed source and result of a repeat check
Review periodically Owner, trigger and unresolved coverage gaps

The docs testing checklist helps turn that inventory into a repeatable review. The installation testing guide is useful when the first failure is in setup. For the wider relationship between builds, sources and reader-visible pages, see static-site documentation testing.

What this does not replace

DocsAlive does not detect Sphinx, read .rst files, extract Sphinx directives or run sphinx-build and the doctest builder. It does not render the site or check links. Keep the Sphinx builders and checks for included sources alongside Markdown example execution.

Human review still matters for whether the instructions are understandable, the output is meaningful and the reader can complete the task. A successful isolated block does not prove that a whole tutorial is coherent. Keep build, link, accessibility and visual review wherever they apply, and assign an owner to every important path the automated report did not cover.

For a starting point, the free health check lets you send a public repository you own or maintain; the team runs the engine on up to 40 of its docs pages and emails the real report within 2 business days; the checkout is deleted after the run. Pricing is Open source $0/month, Team $299/month, Growth $699/month, and Scale from $1,499/month.

The sources we checked

Source What it covers
Sphinx directives Literal blocks, directives, highlighting and included files
Sphinx builders and sphinx-build Builder selection, doctest and external link checks
Python doctest Interactive examples and expected output
MyST code and APIs Fenced code and directive-style blocks

FAQ

Does a Sphinx HTML build run every code example?

A build produces the documentation; it is not evidence that every displayed snippet executed. Use the doctest builder for configured doctests and separate execution checks for other examples.

What is needed for the doctest builder?

Enable sphinx.ext.doctest in the Sphinx configuration and run the doctest builder with the appropriate source and output directories. Its result covers the doctests it runs.

Does linkcheck run Python code?

Its stated job is to check external link integrity. Keep Python execution and link checking as distinct results.

Can the product read an .rst page?

No. It reads eligible Markdown files and does not extract reStructuredText literal blocks, directives, includes or doctest blocks.

Will a MyST directive fence be run as Python?

No. A fence beginning with {code-block} is treated as text. A plain python fence is recognized as Python; select the form that meets the page's presentation and testing needs.

How are pycon sessions handled?

They run line by line and printed output is compared. Review the actual and expected output when a result differs, especially when a value can vary between runs.

Does a scan cover a file included by Sphinx?

It does not extract literalinclude content. Identify the included source and selected lines and test the relevant content separately.

Should a page depend on a previous page's state?

If it does, say so and test the complete journey separately. The product uses a fresh container per page, while keeping planned blocks in order within that page.

Keep reading
Outlined documentation pages with a lime pulse line running out of the stackGuide

Docs Testing: How to Test the Code Samples in Your Docs

Why code examples in documentation break, the ways teams test them (doctest, docs-as-tests, CI runners) and how to run every sample on each release.

Two lenses held over the same documentation page, each bringing a different layer into focusComparison

Vale vs markdownlint: What Each Docs Linter Catches

Vale checks prose style; markdownlint checks Markdown structure. What each catches, sample configs, running both in CI and what neither one tests.

Blueprint of two documentation pages: one with a handwritten test script, one whose code blocks are framed and checkedComparison

Doc Detective vs DocsAlive: Testing the Code in Your Docs

Doc Detective is a free, open-source docs-as-tests framework; DocsAlive is a hosted docs CI for code examples. Features, price, setup and when to use each.

A machine blueprint above a ruled documentation page, with a caliper measuring between themComparison

Promptless Alternative: Promptless vs DocsAlive Compared

Promptless drafts docs updates from what you ship; DocsAlive runs the code examples you've published. Features, pricing, security and when to use each.

A long workbench of outlined testing instruments, each with a small lime light, beside a stack of documentation pagesGuide

Best Free Tools to Test Code Examples in Documentation

Free, open-source tools that run the code examples in your docs: rustdoc, Go examples, doctest, pytest plugins, Sphinx doctest, Doc Detective and byexample.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing SDK Docs Before Every Release: A Release-Gate Guide

Test SDK and client-library docs against the package you ship: build the wheel or npm tarball, install it clean, run every example, and gate the release in CI.

Outlined documentation pages with a lime pulse line running out of the stackGuide

How to Test Quickstarts and Tutorials in Your Docs

Test the onboarding path a new reader follows: run quickstarts in a clean environment, in page order, sort real bugs from credentials and fragments, and wire it into CI.

Outlined documentation pages with a lime pulse line running out of the stackGuide

How to Test CLI Documentation: Commands, Flags and Output

Test the commands a CLI page promises: install in a clean container, run examples in order, compare flags with --help, check exit codes and output, and run it in CI.

Outlined documentation pages with a lime pulse line running out of the stackGuide

How to Test API Reference Docs: Requests, Responses and SDKs

Test API reference pages against the contract they publish: methods, parameters, request and response examples, SDK snippets, status codes and OpenAPI samples.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Docs testing for API-first companies

Keep API quickstarts, SDK snippets and curl examples working across releases.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Docs testing for CLI and developer-tool vendors

Test developer-tool install paths, package managers and command examples across releases.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing README Code Examples: Install, Usage and CI

Keep README install commands and usage examples working with clean environments, output checks and CI.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Notebooks and Executable Docs: Cells, Kernels and Output

Test notebooks in fresh kernels, check meaningful output and manage dependencies, data and drift in CI.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Docs in GitHub Actions: Pull Requests and Scheduled Checks

Run documentation example checks in GitHub Actions with practical guidance on schedules, path filters, caching, secrets and reports.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Code Examples in MkDocs, Docusaurus and Sphinx Sites

Find and test documentation examples in Markdown, MDX and reStructuredText, alongside site builds and link checks.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Python Docs Testing: Doctest, Pytest and Markdown

Test Python documentation with doctest, pytest, Markdown example execution and isolated environments.

Outlined documentation pages with a lime pulse line running out of the stackGuide

JavaScript Docs Testing: Node, TypeScript and Modules

Test Node and TypeScript documentation examples across module formats, package versions and type checks.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Go documentation examples

Test Go example functions and Markdown snippets against the intended module versions in clean environments.

Outlined documentation pages with a lime pulse line running out of the stackGuide

ReadMe Docs Testing: CLI, OpenAPI and Code Examples

Test ReadMe documentation examples: docs-as-code and bi-directional sync, what lint and oas:validate prove, Tabs variants and runnable code.

Outlined documentation pages with a lime pulse line running out of the stackGuide

TypeScript Docs Testing: tsc --noEmit and Runtime

Test TypeScript documentation examples: type-check snippets with tsc --noEmit in a consumer project, then run them, and what each check proves.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Docusaurus Docs Testing: Code Blocks, Tabs and MDX

Test Docusaurus documentation examples: builds vs runnable code, code block metadata, Tabs install variants, MDX pages and clean-container runs.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Mintlify Docs Testing: CodeGroup, Tabs and the CLI

Test Mintlify documentation examples: docs.json, MDX pages, CodeGroup and Tabs variants, what mint broken-links and mint validate prove, and clean runs.

Outlined documentation pages with a lime pulse line running out of the stackGuide

MkDocs Docs Testing: Code Examples, Tabs and Snippets

Test MkDocs documentation examples: strict builds, Material tabs, Snippets includes, mkdocstrings pages and clean-container runs.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Installation Instructions: pip, npm and Containers

Test documented install steps in clean environments: pip and extras, venv, npm install vs npm ci, containers and the first import.

Outlined documentation pages with a lime pulse line running out of the stackGuide

AI SDK Docs Testing: LLM Examples, Keys and Drift

Test AI and LLM SDK documentation examples: requests, responses, streaming, tool calls, credentials, model retirements and CI.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing migration guides and changelog examples

Test before and after examples against the right releases and make migration documentation part of the release gate.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Docs Testing Checklist: Code Examples Before Release

A practical pre-release checklist for testing documentation examples, reviewing gaps and verifying published packages.

Outlined documentation pages with a lime pulse line running out of the stackGuide

The Cost of Broken Code Examples in Documentation

Understand how broken documentation examples create friction in developer adoption and support, and how to reduce it.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Rust documentation examples

Test Rust rustdoc examples and cargo documentation tests, and keep native Rust checks because compiled Rust fences are recognized but not executed.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing VitePress documentation examples

Test VitePress Markdown examples separately from the site build, including code groups, includes and what a plain Markdown scan covers.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing docs in GitLab CI

Run documentation example checks in GitLab CI jobs, keep site builds separate from execution, and review what a scan covers and skips.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing JSON, TOML and YAML examples in docs

Test JSON, TOML and YAML config examples in documentation: parse, schema and tool checks, honest fence labels, fragments, CI jobs and what a scan covers.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing Java documentation examples

Test Java examples in READMEs, SDK docs and Javadoc: the source launcher, javac, JShell scripts, assertions, @snippet files, CI and what a scan covers.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing PHP documentation examples

Test PHP examples in docs: php -l lint, clean-directory runs, assertions with zend.assertions, Composer scratch projects, PHPUnit, CI and scan coverage.

Outlined documentation pages with a lime pulse line running out of the stackGuide

Testing docs examples that need API keys

Test credential-gated docs examples: honest placeholders, offline stubs and fixtures, live sandbox jobs, CI secrets and fork rules, and how a scan classifies them.

A machine blueprint above a ruled documentation page, with a caliper measuring between themGuide

Documentation Drift: How to Detect It Before Users Do

What documentation drift is, why code examples drift first, and practical ways to detect it: ownership, release checks, link and execution tests.

See which of your code samples still run.

Send us a public repository. Our team runs DocsAlive on its docs and emails you the real report within 2 business days. Free, no signup.