Skip to content

Commit bcca0ea

Browse files
committed
test(docs): Run plain Python and console fences
why: Verify copy-pasteable Python blocks, runnable console commands, and MyST literalinclude directives across README.md and docs/ in pytest and CI alongside existing doctests. what: - Add tests/_docs_codeblocks.py and wire conftest.py pytest_collect_file - Register pytest documentation marker and allow exec in docs harness - Execute plain python fences in isolation with explicit imports and run top-level def test_* blocks via real pytest fixtures - Classify and sandbox console fences across README.md and docs/, failing CI on unclassified shell blocks, and verify literalinclude - Classify MIGRATION Before/After blocks and convert pytest_plugin and quickstart fixture examples to plain python fences - Add unit, end-to-end, packaging, and negative-control tests in tests/test_docs_codeblocks.py and update WRITING.md, CONTRIBUTING.md, and CHANGES
1 parent b77d7e4 commit bcca0ea

10 files changed

Lines changed: 1961 additions & 144 deletions

File tree

‎.github/CONTRIBUTING.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,13 @@ Test:
6969
$ uv run pytest
7070
```
7171

72-
Documentation is a gate, not a courtesy. Examples in docstrings,
73-
documentation pages, and `README.md` are executed by `pytest`; the
74-
doctest flags live in `pyproject.toml`, so there is no separate doctest
75-
step and a green `pytest` is the proof. Which blocks qualify, and the
76-
one mistake that silently removes a test, are in
77-
[WRITING.md](WRITING.md#documented-examples-that-run).
72+
Documentation is a gate, not a courtesy. Doctests in docstrings,
73+
documentation pages, and `README.md` — together with plain `python` fences,
74+
runnable `console` fences, and `{literalinclude}` directives in `README.md`
75+
and `docs/` — are collected and executed by `pytest` (run
76+
`uv run pytest -m documentation` to target only Markdown code-block checks).
77+
The rules for executable blocks and explicit classification of non-runnable
78+
commands are in [WRITING.md](WRITING.md#documented-examples-that-run).
7879

7980
Use the [test bite gate](../REVIEW.md#4-test-bite) to prove a regression
8081
fails for the reason it claims to catch. For bug fixes and behavioral

‎.github/WRITING.md‎

Lines changed: 69 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -141,85 +141,81 @@ Badges are few and load-bearing.
141141
## Documented examples that run
142142

143143
Examples in this repository are tests. This section is the contract for
144-
writing one the test suite can actually see, and it is this repo's real
145-
mechanism — read from `pyproject.toml`'s `[tool.pytest.ini_options]` and
146-
the root `conftest.py`, not assumed.
147-
148-
**A fence tag is cosmetic. Only a `>>> ` prompt executes.** A block
149-
written as
150-
151-
```python
152-
term = Terminal(rows=2, cols=20)
153-
```
154-
155-
is prose that looks like a test. Nothing collects it, nothing runs it,
156-
and it can be wrong for years. The same block written with prompts is a
157-
test:
158-
159-
```python
160-
>>> term = Terminal(rows=2, cols=20)
161-
```
162-
163-
This is the single most expensive mistake available when editing
164-
documentation, because removing the prompts leaves a green test suite
165-
and a silently deleted test. When editing a file that contains examples,
166-
count the prompts before and after.
167-
168-
**The fence tag is `python`** for a doctest session and `console` for a
169-
shell command at a `$` prompt.
170-
171-
**Where examples run.** `testpaths` lists `src/libvt`, `tests`,
172-
`docs`, and `README.md`. `addopts` sets `--doctest-docutils-modules` and
173-
`-p no:doctest`: the stdlib `doctest` pytest plugin is disabled, and
174-
`gp-libs`' docutils-based collector (`pytest_doctest_docutils`, loaded
175-
under the `sphinx` entry-point name) runs in its place. That collector
176-
reads doctests out of `.py` docstrings *and* out of any Markdown or
177-
reStructuredText page docutils parses — which is why a `>>> ` block in
178-
`README.md` or under `docs/` is executed exactly like one in a
179-
docstring. `ELLIPSIS` and `NORMALIZE_WHITESPACE` are enabled globally
180-
(`doctest_optionflags`), so `...` elides variable output and whitespace
181-
differences do not fail a comparison. Reach for an inline
182-
`# doctest: +FLAG` only for the block that needs something more.
183-
184-
**`# doctest: +SKIP` is not permitted.** It is a workaround that tests
185-
nothing. Use the fixtures.
186-
187-
**Do not downgrade a doctest to a non-executed block to make it pass.**
188-
A `.. code-block::` or an unprompted fence does not run. If an example
189-
cannot pass, fix the example or fix the code.
190-
191-
**The `doctest_namespace` fixtures.** The root `conftest.py`'s
192-
`_seed_doctest_namespace` autouse fixture populates `doctest_namespace`
193-
before every doctest in the suite runs, making common entry points
194-
available without boilerplate: `libvt`, `Terminal`, `AnsiColor`,
195-
`assert_screen`, and `assert_screen_box`. Standalone documentation blocks
196-
should still show explicit imports when doing so makes the first example
197-
on a page clear to a reader copying it.
198-
199-
**Cross-platform doctests.** `pytest` executes `README.md` and `docs/`
200-
doctests on Linux, macOS, and Windows in CI. Keep documentation doctests
201-
portable across all three platforms (for example, drive
202-
`AsyncTerminalStream` with an in-memory `asyncio.StreamReader` rather
203-
than calling POSIX-only `open_pty()` inside an unguarded doctest).
204-
205-
**`# doctest: +HIDE`.** A `gp-libs` extension flag: it is a no-op for
206-
execution and checking — the line still runs and its output, if any, is
207-
still verified — but it tells the Sphinx-rendered docs to drop that line
208-
from the page. Use it to set up state a docstring's *Examples* section
209-
does not need to show:
144+
writing one the test suite executes, matching `pyproject.toml`'s
145+
`[tool.pytest.ini_options]`, root `conftest.py`, and
146+
`tests/_docs_codeblocks.py`.
147+
148+
**Three Markdown block forms execute under `pytest`:**
149+
150+
1. **Doctest `python` fences** (`>>> ` prompts) in docstrings, `README.md`,
151+
and `docs/**/*.md` run through `gp-libs`' docutils collector
152+
(`--doctest-docutils-modules`, `-p no:doctest`) with `ELLIPSIS` and
153+
`NORMALIZE_WHITESPACE` enabled globally.
154+
2. **Plain `python` fences** (no `>>> ` prompts) in `README.md` and
155+
`docs/**/*.md` run through `conftest.py`'s `pytest_collect_file` hook
156+
(`tests._docs_codeblocks`, marked `documentation`). Each block runs in
157+
isolation with no implicit globals, so every plain `python` block must
158+
include explicit imports. Blocks that define top-level `def test_*` or
159+
`async def test_*` functions without calling them execute inside a
160+
temporary `pytest` run against the real `libvt.pytest_plugin` fixtures.
161+
3. **`console` fences and `{literalinclude}` directives** in `README.md`
162+
and `docs/**/*.md` run through the same `documentation` collector.
163+
Runnable commands (`python -m libvt`, `printf ... | python -m libvt`,
164+
`examples/`, `scripts/`, and documented `pytest` commands) execute in a
165+
temporary sandbox isolated from `$HOME` and the network; expected output
166+
lines beneath a `$ ` command are compared against stdout. Non-runnable
167+
blocks (package installs, `docs/project/releasing.md` git templates,
168+
interactive TUI loops, and optional external-tool invocations) are
169+
classified explicitly and checked statically. Any unclassified shell or
170+
`console` fence fails `pytest`.
171+
172+
**The fence tag is `python`** for executable Python snippets or doctests
173+
and `console` for shell commands at a `$ ` prompt. Use
174+
`uv run pytest -m documentation` to run only the Markdown code-block and
175+
`{literalinclude}` checks, or target a single page such as
176+
`uv run pytest README.md`.
177+
178+
**Where examples run.** `testpaths` lists `src/libvt`, `tests`, `docs`,
179+
and `README.md`. The docs code-block collector lives in
180+
`tests/_docs_codeblocks.py` (included in sdists, excluded from built wheels
181+
and `pytest11` entry points). Every `python` fence in `MIGRATION` is
182+
classified as a historical `# Before` / `# After` block and checked in
183+
`tests/test_docs_codeblocks.py`.
184+
185+
**`# doctest: +SKIP` is not permitted.** Use fixtures or explicit platform
186+
guards instead.
187+
188+
**Do not downgrade an example to an unexecuted block to make it pass.**
189+
If an example fails, fix the example or fix the code.
190+
191+
**The `doctest_namespace` fixtures.** Root `conftest.py`'s
192+
`_seed_doctest_namespace` autouse fixture populates `doctest_namespace` for
193+
`>>> ` doctests only (`libvt`, `Terminal`, `AnsiColor`, `assert_screen`,
194+
`assert_screen_box`, and `vt_*` fixtures). Plain `python` blocks never
195+
receive `doctest_namespace`; standalone doctest blocks on `README.md`,
196+
`docs/quickstart.md`, and testing/snapshot/API pages also verify explicit
197+
imports in `tests/test_libvt.py`.
198+
199+
**Cross-platform examples.** `pytest` executes `README.md` and `docs/`
200+
blocks on Linux, macOS, Windows, and PyPy in CI. Keep documentation
201+
examples portable across those targets (for example, guard POSIX-only
202+
`open_pty()` calls or drive `AsyncTerminalStream` with an in-memory
203+
`asyncio.StreamReader`).
204+
205+
**`# doctest: +HIDE`.** A `gp-libs` extension flag for `>>> ` doctests: the
206+
line still runs and its output is verified, while Sphinx omits that line
207+
from rendered HTML. Use plain `python` fences instead of `# doctest: +HIDE`
208+
shims for copy-pasteable `pytest` examples.
210209

211210
```python
212211
>>> term = Terminal(rows=2, cols=20) # doctest: +HIDE
213212
>>> term.feed(b"ready") # doctest: +HIDE
214213
```
215214

216-
**Every code block on a `docs/` page is an independent doctest.** Blocks
217-
do not share a session: each one gets a fresh copy of
218-
`doctest_namespace`. A later block cannot use a `term` an earlier block
219-
created — the name is not defined there. Write every block
220-
self-contained. Order is load-bearing for the reader's narrative, not
221-
for state — reorder, add, or drop a block as the prose demands, and keep
222-
the story coherent.
215+
**Every code block on a `docs/` page is independent.** Blocks do not share
216+
state: doctests receive a fresh copy of `doctest_namespace`, and plain
217+
`python` blocks run in a fresh empty namespace. Write every block
218+
self-contained.
223219

224220
**Docstring examples** use the NumPy `Examples` section:
225221

@@ -229,15 +225,6 @@ the story coherent.
229225
>>> add(2, 2)
230226
4
231227

232-
**Room to grow.** The docutils collector reads `.md` and `.rst`
233-
wherever it is loaded, which is everywhere in this repository. A
234-
prompted block added to a documentation page is executed from that
235-
moment with no configuration change. The MyST `{doctest}` directive and
236-
the reStructuredText `.. doctest::` directive are also registered and
237-
available for a case that ever needs an explicitly marked block, rather
238-
than a plain prompted fence. This section is where any additional
239-
executed-block format is documented when one is adopted.
240-
241228
## Documentation pages
242229

243230
Warm the framing, never the facts. Resolution-order lists, value

‎CHANGES‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,19 @@ Add dedicated API reference pages for {mod}`libvt.views`,
175175
`syrupy`) into per-module directories, and add Sphinx `rediraffe` redirects for
176176
moved API URLs.
177177

178+
### Development
179+
180+
#### Execute plain Python and console Markdown code blocks in `pytest` (#217)
181+
182+
`pytest` now collects and runs plain `python` code blocks, runnable `console`
183+
commands, and MyST `{literalinclude}` directives across `README.md` and
184+
`docs/` alongside `>>> ` doctests (`pytest -m documentation`). Plain `python`
185+
blocks run in isolation with explicit imports (and top-level `def test_*`
186+
examples run against the real `libvt.pytest_plugin` fixtures), runnable
187+
`console` blocks execute in a temporary sandbox, and unclassified shell fences
188+
fail CI. The harness lives under `tests/` and stays excluded from built wheels
189+
and `pytest11` entry points.
190+
178191
## libvt 0.0.1a6 (2026-12-05)
179192

180193
`libvt` 0.0.1a6 adds soft-wrapped logical-line reading and `wait_for()`

‎conftest.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import annotations
44

55
import importlib.util
6+
import pathlib
67
import typing as t
78

89
import pytest
@@ -40,3 +41,15 @@ def _seed_doctest_namespace(
4041
"syrupy"
4142
) is not None and request.config.pluginmanager.hasplugin("syrupy"):
4243
doctest_namespace["vt_snapshot"] = request.getfixturevalue("vt_snapshot")
44+
45+
46+
def pytest_collect_file(
47+
file_path: pathlib.Path,
48+
parent: pytest.Collector,
49+
) -> pytest.Collector | None:
50+
"""Collect plain Python, console, and literalinclude blocks from Markdown docs."""
51+
if file_path.suffix.lower() != ".md":
52+
return None
53+
from tests._docs_codeblocks import collect_markdown_codeblocks
54+
55+
return collect_markdown_codeblocks(file_path, parent)

‎docs/api/pytest_plugin.md‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,26 @@ $ uv add --dev "libvt[pytest]>=0.0.1a6,<0.1"
1111
## Quick start
1212

1313
Declare any `vt_*` fixture as a test parameter; `pytest` injects it
14-
automatically. `libvt`'s own `conftest.py` also seeds these fixtures in
15-
`doctest_namespace` so the examples below execute in CI:
14+
automatically:
1615

1716
```python
18-
>>> from libvt.pytest_plugin import TerminalFactory
19-
>>> from libvt.testing import assert_screen_box
20-
>>> def test_inline_status(vt_factory: TerminalFactory) -> None:
21-
... term = vt_factory(rows=2, cols=10)
22-
... term.feed(b"\x1b[1;32mOK\x1b[0m\r\nready")
23-
... assert_screen_box(
24-
... term,
25-
... """
26-
... ┌──────────┐
27-
... │OK │
28-
... │ready │
29-
... └──────────┘
30-
... """,
31-
... cursor=(1, 5),
32-
... )
33-
>>> test_inline_status(vt_factory) # doctest: +HIDE
17+
from libvt.pytest_plugin import TerminalFactory
18+
from libvt.testing import assert_screen_box
19+
20+
21+
def test_inline_status(vt_factory: TerminalFactory) -> None:
22+
term = vt_factory(rows=2, cols=10)
23+
term.feed(b"\x1b[1;32mOK\x1b[0m\r\nready")
24+
assert_screen_box(
25+
term,
26+
"""
27+
┌──────────┐
28+
│OK │
29+
│ready │
30+
└──────────┘
31+
""",
32+
cursor=(1, 5),
33+
)
3434
```
3535

3636
## Which fixture to request

‎docs/quickstart.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -162,13 +162,14 @@ styles:
162162
{fixture}`vt_recorder`, {fixture}`vt_parser`, and POSIX {fixture}`vt_pty`:
163163

164164
```python
165-
>>> from libvt.pytest_plugin import TerminalFactory
166-
>>> from libvt.testing import assert_screen
167-
>>> def test_prompt(vt_factory: TerminalFactory) -> None:
168-
... term = vt_factory(rows=1, cols=10)
169-
... term.feed(b"ready> ")
170-
... assert_screen(term, "ready> ", cursor=(0, 7))
171-
>>> test_prompt(vt_factory) # doctest: +HIDE
165+
from libvt.pytest_plugin import TerminalFactory
166+
from libvt.testing import assert_screen
167+
168+
169+
def test_prompt(vt_factory: TerminalFactory) -> None:
170+
term = vt_factory(rows=1, cols=10)
171+
term.feed(b"ready> ")
172+
assert_screen(term, "ready> ", cursor=(0, 7))
172173
```
173174

174175
## Golden `.ambr` adapter (`libvt[syrupy]`)

‎pyproject.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ convention = "numpy"
254254
[tool.ruff.lint.per-file-ignores]
255255
"*/__init__.py" = ["F401"]
256256
"docs/conf.py" = ["S102"]
257+
"tests/_docs_codeblocks.py" = ["S102"]
257258
"scripts/benchmark.py" = ["B008"]
258259
"scripts/bench_vt.py" = ["T201"]
259260

@@ -280,6 +281,7 @@ asyncio_mode = "auto"
280281
asyncio_default_fixture_loop_scope = "function"
281282
xfail_strict = true
282283
markers = [
284+
"documentation: executable Markdown code-block and literalinclude checks",
283285
"integration: integration tests (require optional system utilities)",
284286
"ghostty: differential tests against compiled libghostty-vt 1.0 shared library",
285287
]

0 commit comments

Comments
 (0)