On this page
The short answerHow the doctest builder organizes testsWalk through a MyST projectConfigure the builder deliberatelyKeep reader setup and test setup alignedCompare the builder with the engineTriage a doctest failure or coverage gapA checklist for Sphinx changesWhere DocsAlive fitsThe sources we checkedFAQThe short answer
The Sphinx doctest builder runs directive-marked examples as grouped tests, including interactive sessions and code paired with expected output. Use it as the gate for those examples. DocsAlive adds a separate scan for plain fences in Markdown pages: engine 0.6.3 skips MyST directive fences as not executable, never reads .rst pages or conf.py, and therefore does not see doctest_global_setup. Names supplied only there can be reported as depends-on-context. It runs recognized plain Python, pycon, and shell fences; its printed-output comparison applies to Python pycon sessions.
The two checks have different boundaries. A passing doctest build does not mean a plain Markdown fence was executed. A scan does not mean a Sphinx directive or a reStructuredText page was tested. Record both boundaries when deciding what a green build covers.
How the doctest builder organizes tests
sphinx.ext.doctest provides a doctest builder that collects marked snippets and runs them as tests. Within each document, snippets belong to groups. A group has zero or more setup blocks and one or more test blocks. Groups run one after another: setup first, then tests in file order.
An omitted group name means the default group. An asterisk selects all groups; otherwise, a comma-separated list names the groups to which a directive belongs. Use groups to make shared setup deliberate. A name defined in one group should not be assumed to exist in another.
There are two main test styles. A doctest block presents an interactive Python session with prompts and expected output. A testcode block holds ordinary code, optionally followed by a testoutput block. testcode executes all at once, so a bare expression does not produce output: use print when output is intended. Doctest cannot combine regular output and an exception message in the same snippet; that limit applies to a testcode and testoutput pair too.
The five directives have distinct roles:
testsetupruns before its group’s tests and is not shown by other builders. It acceptsskipif.testcleanupsupplies cleanup code for a group.doctestacceptshide, doctestoptions,pyversion, the trim flags, andskipif.testcodeacceptshide, the trim flags, andskipif.testoutputsupplies output or an exception message for the lasttestcode; it acceptshide,options, the trim flags, andskipif.
The trim options are trim-doctest-flags and no-trim-doctest-flags. pyversion uses PEP 440 version specifiers. skipif is evaluated as a Python expression; when true, the directive is omitted as if it were absent. A hidden block can still run and fail even though readers cannot see it.
In MyST Markdown, write directives as fenced blocks with a single pair of braces around the directive name, such as {doctest}. Arguments follow the directive name, and option lines go at the top of the block. The examples below show the complete fence form.
Walk through a MyST project
The following files use acme-slug and acme_slug as illustrative names, not a published package. The package is assumed to provide slugify and truncate_slug with the behavior shown in the page.
Install Sphinx and MyST-Parser. The checked example used Sphinx 9.2.0 and MyST-Parser 5.2.0; the Sphinx release requires Python 3.13 or newer.
python -m pip install sphinx myst-parser
The illustrative docs/conf.py does three things: it turns on myst_parser and sphinx.ext.doctest (in the usual list in conf.py, as the sphinx.ext.doctest page in the Sphinx documentation shows; that one line is left out of the excerpt below), adds the project directory to Python’s path, and imports helpers for every group. The global setup is convenient for testing, but a reader copying an example does not automatically receive it.
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
project = "acme-slug"
doctest_global_setup = "from acme_slug import slugify, truncate_slug"
The illustrative MyST page contains a default-group doctest, then a named group with testsetup, testcode, and testoutput. The final plain Python fence is highlighted for readers, but the doctest builder does not run it.
# Usage
A doctest-style block. Readers see a console session:
```{doctest}
>>> slugify("Docs That Run Everywhere")
'docs-that-run-everywhere'
```
Hidden setup comes first, then a code block and its expected lines, all in a group named short.
```{testsetup} short
from acme_slug import truncate_slug
slug = "docs-that-run-everywhere"
```
```{testcode} short
print(truncate_slug(slug, 13))
```
```{testoutput} short
docs-that-run
```
A plain fence is only highlighted. The doctest builder never runs it.
```python
print(slugify("Not Tested"))
```
Run the doctest builder using Sphinx’s make-mode command:
sphinx-build -M doctest docs docs/_build
The builder writes its report under the build directory at doctest/output.txt. In the checked run, the default and named groups each passed one test. The plain Python fence did not contribute a test.
Document: usage
---------------
2 items passed all tests:
1 test in default
1 test in short
2 tests in 2 items.
2 passed.
Test passed.
Doctest summary
===============
2 tests
0 failures in tests
0 failures in setup code
0 failures in cleanup code
The next change is broken on purpose relative to the configuration and page. It changes the separator and renames the imported shortening function.
--- a/acme_slug/__init__.py
+++ b/acme_slug/__init__.py
@@ -1,13 +1,13 @@
"""Tiny slug helpers used in the DocsAlive guides."""
-def slugify(text, sep="-"):
+def slugify(text, sep="_"):
"""Turn a title into a URL slug."""
keep = "".join(c.lower() if c.isalnum() else " " for c in text)
return sep.join(keep.split())
-def truncate_slug(slug, limit):
+def shorten_slug(slug, limit):
"""Cut a slug at a word boundary."""
if len(slug) <= limit:
return slug
After the change, global setup fails in both groups and the named group’s setup import also fails. The build exits with status 1, with three setup failures and no tests run. A zero test count here is a consequence of setup failure, not evidence that the examples were checked successfully.
***Test Failed*** 3 failures.
Doctest summary
===============
0 tests
0 failures in tests
3 failures in setup code
0 failures in cleanup code
The following material was appended to a copy of the illustrative page. Both displayed values are wrong on purpose. One is in a plain pycon fence; the other is in a hidden doctest directive.
This pycon fence is wrong on purpose.
```pycon
>>> slugify("A B")
'wrong'
```
This doctest directive is hidden from readers and wrong on purpose.
```{doctest}
:hide:
>>> slugify("A B")
'a_b'
```
The checked builder run reports the hidden directive’s mismatch. It does not run the plain MyST pycon fence. This is a useful reminder that hidden tests can fail where readers see no corresponding code, while visible fences can remain untested.
File "usage.md", line 41, in default
Failed example:
slugify("A B")
Expected:
'a_b'
Got:
'a-b'
Configure the builder deliberately
doctest_default_flags defaults to ELLIPSIS, IGNORE_EXCEPTION_DETAIL, and DONT_ACCEPT_TRUE_FOR_1. Those flags affect comparison behavior, so review them before deciding that a doctest verifies every character of an error or result. A directive’s options can specify doctest flags for the relevant block.
doctest_show_successes defaults to true. doctest_path supplies absolute directories to add to Python’s import path. doctest_global_setup and doctest_global_cleanup supply code treated like setup and cleanup for every file and group. Keep that global code small: a removed import there can prevent many examples from running, as the walkthrough shows.
doctest_test_doctest_blocks defaults to default, enabling testing of standard reStructuredText doctest blocks as well; those blocks cannot contain blank lines. This does not make a plain MyST pycon fence a directive test. doctest_fail_fast, added in Sphinx 9.0, defaults to false and can stop at the first failure when enabled.
You can also select the doctest builder with -b doctest. Preserve and inspect output.txt in CI when diagnosing failures. Separate setup, test, and cleanup counts help identify whether the builder reached the examples at all.
Keep reader setup and test setup aligned
Hidden setup can reduce repetition, but it can also hide a missing import or prerequisite. Review each visible example from a reader’s perspective: what must be installed, which names are already defined, and where did those names come from? If the page describes a continuing session, make that relationship clear.
Global setup in conf.py is especially easy to overlook because it is outside the page. It can make a directive pass while a reader’s copy fails. Conversely, a changed import can make every group fail before individual examples run. Treat setup failures as first-class results and investigate the earliest missing dependency or changed API.
Plain fences need an explicit coverage plan. The builder does not run the plain Python fence or the plain MyST pycon fence in the walkthrough. A separate test or scan can exercise them, but its environment and interpretation may differ from Sphinx’s. For the broader build and publishing context, see Sphinx docs testing and Read the Docs testing.
Compare the builder with the engine
| sphinx.ext.doctest feature | What the doctest builder does | What the engine does in 0.6.3 |
|---|---|---|
| Directive fences | Runs supported marked tests and setup by group | Skips MyST directive fences as not executable |
| Groups | Runs setup first, then tests in file order for each group | Does not interpret directive groups |
| Global setup and cleanup | Applies configured code to every file and group | Never reads conf.py or its global setup |
| Plain Python fence in MyST | Does not run it as a directive test | Runs recognized plain Python fences in page order |
| Plain MyST pycon fence | Does not run it as a directive test | Runs it and compares printed output |
.rst pages |
Can test marked examples and configured standard doctest blocks | Never reads .rst pages |
| Hidden directive | Can execute it even when it is not displayed | Skips the directive fence |
| Work environment | Uses the Sphinx build and its configured Python environment | Starts each Markdown page in a fresh container with an empty work directory |
In the scan probe, the plain Python fence in the illustrative page was reported as depends-on-context because its name came from global setup the engine never reads. The plain pycon fence had the same missing context. Install a package through the page or --setup where appropriate, and make reader-facing imports explicit when the example needs them.
The engine also has a known limitation for unknown fence labels: a label without a checker can be reported as passing without being run or parsed. Inspect the operation and skip reasons in the report. A clean scan is useful evidence about supported Markdown fences, not evidence that the Sphinx builder ran.
Triage a doctest failure or coverage gap
| Finding | Likely cause | What to do |
|---|---|---|
| Setup failures and no tests run | A global or group import failed | Fix or update setup first, then rerun and inspect the test count |
| A visible plain fence has no doctest result | It is not a directive test | Add an appropriate separate check or convert it when directive semantics fit |
| A hidden test fails | A hidden directive still executes | Locate its source and decide whether it tests a meaningful reader contract |
Expected output is missing from testcode |
A bare expression did not print | Use print for output that the test should compare |
| A directive is unexpectedly absent | Its skipif expression evaluated true |
Review the condition and the environments it excludes |
| A scan reports depends-on-context | A name came from Sphinx setup or another omitted context | Make prerequisites explicit or supply appropriate setup, then review the result |
| A scan skips a directive fence | Engine 0.6.3 does not execute that directive | Use the doctest builder for it |
A scan does not include an .rst page |
That file type is outside engine scope | Keep Sphinx or another suitable check for the page |
Use the Python docs testing guide for package and environment choices, and compare Sybil when considering another way to collect documentation examples.
A checklist for Sphinx changes
[ ] Run the doctest builder and inspect its test and setup counts.
[ ] Confirm each intended directive belongs to the right group.
[ ] Review global and hidden setup for imports readers also need.
[ ] Use print when testcode must produce expected output.
[ ] Check skip conditions and hidden tests after dependency changes.
[ ] Inventory plain Markdown fences the builder does not run.
[ ] Test .rst pages with a tool that reads them.
[ ] Run supported plain fences in a clean, documented environment.
[ ] Review depends-on-context findings and unsupported labels.
[ ] Rerun the relevant checks after fixing code or documentation.
Where DocsAlive fits
Use the Sphinx doctest builder for directive-marked examples and reStructuredText doctests in the project’s configured build. Use DocsAlive to scan supported plain fences in Markdown and MyST pages, with a fresh container per page and findings classified for review. The scan cannot replace the builder’s group, directive, or global-setup semantics.
The CLI reference explains page setup and scope, while findings describes categories. For different Markdown testing models, compare pytest-codeblocks and txm. A useful coverage record names each tool, the pages and block styles it checks, and the examples left for another test.
The sources we checked
These sources were read on November 17, 2026. Engine behavior was checked against engine 0.6.3, the engine code in the deployed release, on the same day.
| Source | What it covers |
|---|---|
| The sphinx.ext.doctest page in the Sphinx documentation (www.sphinx-doc.org, Usage section) and its source for the v9.2.0 tag | Directives, groups, options, and configuration |
| Sphinx builders documentation | Builder selection and build output |
| MyST directives documentation | Directive syntax in Markdown |
| Python doctest documentation | Interactive test behavior and doctest flags |
FAQ
What does the Sphinx doctest builder run?
It runs marked doctest and code-output examples in document groups, along with their setup and cleanup. It can also test standard reStructuredText doctest blocks according to configuration.
Does the builder run every Python fence in MyST?
No. A plain Python or pycon fence in MyST is not automatically a directive test. Inventory those fences and give them a separate check when readers depend on them.
Why did setup fail before any tests ran?
Global or group setup can import a name that was removed or is unavailable in the build environment. Inspect setup failures first, correct the environment or import, and rerun to see the individual test results.
Why does a bare expression in testcode show no output?
testcode executes the block all at once rather than as an interactive session. Use print when the example must produce output for a testoutput block.
How does DocsAlive handle Sphinx examples?
Engine 0.6.3 skips MyST directive fences, never reads .rst pages or conf.py, and does not receive doctest_global_setup names; those names can be reported as depends-on-context. It runs recognized plain Python, pycon, and shell fences in Markdown, and compares printed output in pycon sessions.
Should I use both the builder and a scan?
Yes, when the project has both directive-marked tests and plain Markdown fences that matter to readers. The builder checks its directives; the scan covers supported plain fences with a different environment and does not replace the Sphinx build.




