On this page
The short answerWhat pytest-codeblocks collectsWalk through a small README projectMarkers and output checksCompare the plugin with the engineTriage failures and gapsA checklist for a pull requestWhere DocsAlive fitsThe sources we checkedFAQThe short answer
pytest-codeblocks is a pytest plugin that runs selected Python and shell code blocks in Markdown files when you enable --codeblocks. It can join Python blocks, honor pytest markers, and compare documented expected output. Use it as a CI gate for examples written to its collection rules. DocsAlive adds a separate clean-sandbox scan and triage, but engine 0.6.3 ignores those markers, skips multi-line HTML comments containing hidden setup, shares one Python namespace per page, runs labels such as py, Python, and titled Python fences, uses set -e for shell blocks, and does not compare pytest-codeblocks expected-output blocks. Each page starts in an empty work directory, so packages need a documented install step or --setup.
The distinction matters because a passing test means different things in the two systems. pytest-codeblocks checks a deliberately marked subset of the page under pytest. The scan can find executable fences that the plugin did not collect, but it cannot reproduce the plugin’s marker and output semantics. Use both results as evidence about their respective coverage.
What pytest-codeblocks collects
The plugin is designed for code blocks in README files and supports Python and shell code. Install it alongside pytest and invoke pytest with --codeblocks. Version 0.18.0 requires Python 3.10 or newer.
In the tested 0.18.0 release, collection is narrower than a visual review of a Markdown page might suggest:
- The file must end in
.md. - The entire fence info string must be exactly
python,sh, orbash. - Labels such as
py,Python,console, orpythonfollowed by a title are not collected. - The README mentions
zsh, but azshblock was not collected by 0.18.0 in the checked run.
This is a practical reason to review collection, not just the final pass count. A block can look like Python in the rendered page and still be absent from pytest’s test list. The broader README testing guide covers the reader path around those individual blocks.
Each Python block normally executes in a fresh namespace. A later block cannot use a variable from an earlier one unless you join it to the preceding block with the cont marker. The joined code is reported at the first block’s line. Shell blocks run as scripts: absent set -e, the status of the last command can hide a failure earlier in the block.
Walk through a small README project
The following examples use acme-slug and acme_slug as illustrative names, not published packages. The files and package are a compact local project for showing the testing behavior.
First install pytest and the plugin:
python -m pip install pytest pytest-codeblocks
The illustrative package exposes a slug-making function and a shortening function. Its default separator and public function names are part of what the docs will demonstrate.
"""Tiny slug helpers used in the DocsAlive guides."""
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):
"""Cut a slug at a word boundary."""
if len(slug) <= limit:
return slug
cut = slug[:limit + 1]
return cut[:cut.rfind("-")] if "-" in cut else slug[:limit]
The illustrative usage page has two related Python blocks. The continuation marker joins the second to the first, so slug is available when the shortening function runs. The next untagged block supplies expected printed output. The page also shows a skipped network-dependent example and a deliberately expected failure.
# Usage
Make a slug:
```python
from acme_slug import slugify
slug = slugify("Docs That Run Everywhere")
assert slug == "docs-that-run-everywhere"
```
Shorten it for a URL. This block continues the one above:
<!--pytest-codeblocks:cont-->
```python
from acme_slug import truncate_slug
print(truncate_slug(slug, 13))
```
<!--pytest-codeblocks:expected-output-->
```
docs-that-run
```
This call needs a network service, so it is skipped:
<!--pytest.mark.skip(reason="needs the live API")-->
```python
import urllib.request
urllib.request.urlopen("https://api.acme.invalid/slugs")
```
Dividing by zero is documented as an error:
<!--pytest.mark.xfail-->
```python
1 / 0
```
The illustrative README checks a shell invocation and its printed result. This output check belongs to pytest-codeblocks; the engine’s handling is different, as the comparison below explains.
# acme-slug
Install from a checkout and make a slug from the shell:
```sh
python -c "from acme_slug import slugify; print(slugify('Hello, World'))"
```
<!--pytest-codeblocks:expected-output-->
```
hello-world
```
Configure pytest to enable the plugin on ordinary runs and collect the chosen docs paths. Here pythonpath also makes the illustrative package available from the project directory.
[tool.pytest.ini_options]
addopts = "--codeblocks"
testpaths = ["docs", "README.md"]
pythonpath = ["."]
Run pytest from the project directory. The configuration supplies the plugin flag.
python -m pytest -v
The checked run reported two passes, one skip, and one expected failure. The continued usage code appears at the first Python block’s line, rather than as a separate later test.
docs/usage.md::line 5 PASSED [ 25%]
docs/usage.md::line 32 SKIPPED (needs the live API) [ 50%]
docs/usage.md::line 42 XFAIL [ 75%]
README.md::line 5 PASSED [100%]
=================== 2 passed, 1 skipped, 1 xfailed in 0.02s ====================
Now consider an illustrative page.md that deliberately exposes collection and execution assumptions. Its first five fences are not collected by the tested plugin. The shell block contains a failing command followed by a successful one; the final Python block refers to a name that its fresh namespace does not contain.
```py
raise SystemExit("py label ran")
```
```python title="example.py"
raise SystemExit("title label ran")
```
```Python
raise SystemExit("capital label ran")
```
```zsh
exit 3
```
```console
$ false
```
```sh
false
echo "the block still passes"
```
```python
print(slug)
```
The checked run collected two blocks. The shell script passed because its last command succeeded; the Python block failed because slug was undefined. Put set -e at the top of a shell block when each command must succeed, and make Python blocks independent or mark a genuine continuation.
page.md::line 21 PASSED [ 50%]
page.md::line 26 FAILED [100%]
...
name 'slug' is not defined
========================= 1 failed, 1 passed in 0.01s ==========================
The next change is broken on purpose relative to the docs: it changes the default separator and renames the shortening function. It represents a release where existing examples have not yet been updated.
--- 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, the README output check and the merged usage test both fail; the skip and expected failure remain. The usage test stops at its bare assertion, which has no message, so its reported reason is empty. Give assertions useful messages to make failures easier to diagnose.
FsxF [100%]
...
Expected output
```
hello-world
```
but got
```
hello_world
```
...
FAILED docs/usage.md::line 5 - line 5, line 5:
FAILED README.md::line 5 - line 5, line 5:
2 failed, 1 skipped, 1 xfailed in 0.02s
Markers and output checks
Markers are single-line HTML comments immediately above the relevant block. pytest-codeblocks accepts pytest.mark.skip, pytest.mark.skipif, and pytest.mark.xfail; it evaluates pytest mark expressions with sys and pytest available. importorskip skips when its named module is unavailable. skipfile applies only when it is the file’s very first line.
The cont marker appends a Python block to the previous block. Use it where the reader is meant to continue the same session. Otherwise, self-contained blocks provide a clearer test and a clearer copy-and-paste experience.
An expected-output marker precedes a block containing expected stdout. The plugin compares that text exactly with the Python or shell block’s captured stdout. The expected-output-ignore-whitespace variant removes all whitespace from both sides before comparing; it does more than ignore indentation or trailing spaces. Choose it only when spaces and line breaks really do not matter.
The plugin README also describes hidden setup inside a multi-line HTML comment that the plugin still collects. Hidden setup is useful for a fixture, but review it as carefully as visible code: it can supply an import or variable that readers do not have. Older pytest-codeblocks:skip, skipif, and expect-exception keywords are deprecated in favor of pytest marks. An unknown plugin keyword raises an error.
A test suite should make omissions visible to maintainers. Keep a reason with intentional skips, revisit expected failures, and inspect collection after changing labels or moving pages. A successful output check is valuable, but it only covers blocks that the plugin actually collected and paired with expectations.
Compare the plugin with the engine
| pytest-codeblocks feature | What pytest-codeblocks does | What the engine does in 0.6.3 |
|---|---|---|
| File scope | Collects .md files in pytest’s selected paths |
Reads .md, .mdx, and .markdown pages within its scan scope |
| Fence labels | Collects exact python, sh, and bash info strings in the checked release |
Uses the first info-string word and runs recognized labels, including py, Python, and titled Python fences |
| Python state | Starts a fresh namespace per block unless blocks are joined | Keeps one Python namespace per page in page order |
| Markers | Applies supported skips, expected failures, continuation, and output markers | Ignores the single-line marker comments |
| Hidden setup | Can collect code inside a multi-line HTML comment | Skips a multi-line HTML comment entirely |
| Shell scripts | Uses the script’s final exit status | Runs each shell block under set -e |
| Expected output | Compares marked stdout, with an optional all-whitespace removal mode | Skips expected-output blocks without comparing them |
| Setup | Runs in the pytest environment | Starts each page in an empty work directory; use page install steps or --setup |
For the usage and README pages above, a clean scan without the illustrative package reports missing installation steps. When the package is importable, the initial Python examples pass; after the deliberate change, the renamed import is identified as API drift, while the failed assertion is a runtime error for review. The marker on the division example is ignored, so it runs and produces a runtime error. The network-dependent example was syntax-checked in the network-off probe.
The engine runs the py, titled, and capitalized Python fences in the illustrative page, as well as the zsh and console fences. It stops the shell block at the failing command. This wider collection is useful evidence, but it is not a replacement for the plugin’s expected-output checks. Engine output comparison is limited to printed output in Python pycon or python-repl sessions.
A further coverage limit deserves attention: an unknown fence label can be reported as passing without being run or parsed. Review the language and the stated operation, not just a green status. See framework coverage and findings for the scan’s scope and classifications.
Triage failures and gaps
| Finding | Likely cause | What to do |
|---|---|---|
| Expected Python block is absent | File suffix or fence info string does not match plugin collection | Use an exact supported label and inspect pytest collection |
| Name is undefined in a later block | Python blocks have separate namespaces | Make the block independent or use cont when it is a real continuation |
| Shell block passes after an earlier failure | A later command supplied a successful final status | Add set -e and rerun the block |
| Output mismatch | The documented value or implementation changed | Check the intended contract and update the code or docs |
| Empty assertion reason | A bare assertion failed without a message | Add an explanatory assertion message and inspect its values |
| Missing installation hint in a scan | The page starts in a clean work directory without the package | Document installation or supply appropriate --setup; verify that readers have the same prerequisite |
| Unexpected runtime error in a scan | The scan ignored a skip or expected-failure marker | Review the example and retain pytest as the marker-aware gate |
| Passing status on an unfamiliar label | No checker may exist for that label | Confirm support and add a separate test for the language |
A failed block is not automatically a docs bug. A missing fixture, an intentional fragment, a credential-dependent call, and an actual removed API call require different responses. Conversely, a passing block with no output assertion may leave a documented result unchecked.
A checklist for a pull request
Copy this checklist into your review:
[ ] Confirm the intended Markdown files are in pytest's test paths.
[ ] Check that each intended fence uses an exact collected label.
[ ] Inspect pytest collection, including skips and expected failures.
[ ] Make Python blocks independent or mark real continuations.
[ ] Put set -e in shell blocks where every command must succeed.
[ ] Add meaningful assertion messages and stable output expectations.
[ ] Review hidden setup against the prerequisites readers actually have.
[ ] Run in a clean environment with the intended package version.
[ ] Review scan skips, runtime errors, and unsupported labels.
[ ] Update the docs or implementation and rerun the affected checks.
Where DocsAlive fits
Keep pytest-codeblocks in CI when its exact-label collection, markers, and stdout assertions express the contract you want. Use a scan to inspect recognized fences across Markdown pages, run each page in a fresh container, and separate likely docs bugs from findings that need context. The CLI reference describes --setup and scan scope; docs testing explains the broader workflow.
For other pytest-oriented approaches, compare mktestdocs and pytest-markdown-docs. The Python docs testing guide and free tools guide help you choose coverage beyond a single plugin. For annotation-based, language-independent tests, see txm; for Sphinx directives, see sphinx.ext.doctest.
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 |
|---|---|
| pytest-codeblocks repository | Collection, markers, configuration, and output checks |
| pytest-codeblocks on PyPI | Release and Python requirements |
| pytest skip and expected-failure guidance | Pytest markers and their intended use |
FAQ
What does pytest-codeblocks test?
In the checked 0.18.0 release, it collects blocks in .md files whose entire info string is exactly python, sh, or bash. Enable it with --codeblocks and inspect collection to confirm the intended examples are included.
Why did a later Python block lose a variable?
Each Python block starts in a fresh namespace unless a continuation marker appends it to the preceding block. Make the example self-contained or use the marker when the page describes one continuing session.
Why can a shell block pass after a command fails?
The plugin checks the exit status of the whole script, which can be the successful status of its final command. Add set -e when an earlier failure should stop the block.
Does the plugin check documented output?
Yes, when an expected-output marker pairs a block with expected stdout. Its ignore-whitespace variant removes all whitespace before comparison, so use that option only when whitespace is immaterial.
How does DocsAlive handle these pages?
Engine 0.6.3 ignores plugin markers and skips multi-line HTML comments, including hidden setup. It shares one Python namespace per page, runs py, Python, and titled fences, uses set -e for shell blocks, and does not compare expected-output blocks. Pages start in an empty work directory, so install dependencies in the page or use --setup.
Should I run both checks?
They cover different behavior. Keep pytest-codeblocks for its marker-aware tests and stdout expectations; use the scan to inspect other recognized fences and triage findings in a clean page environment. Review unsupported labels and skips in either workflow.




