Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,13 @@ Test:
$ uv run pytest
```

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

Use the [test bite gate](../REVIEW.md#4-test-bite) to prove a regression
fails for the reason it claims to catch. For bug fixes and behavioral
Expand Down
156 changes: 74 additions & 82 deletions .github/WRITING.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,85 +141,86 @@ Badges are few and load-bearing.
## Documented examples that run

Examples in this repository are tests. This section is the contract for
writing one the test suite can actually see, and it is this repo's real
mechanism — read from `pyproject.toml`'s `[tool.pytest.ini_options]` and
the root `conftest.py`, not assumed.

**A fence tag is cosmetic. Only a `>>> ` prompt executes.** A block
written as

```python
term = Terminal(rows=2, cols=20)
```

is prose that looks like a test. Nothing collects it, nothing runs it,
and it can be wrong for years. The same block written with prompts is a
test:

```python
>>> term = Terminal(rows=2, cols=20)
```

This is the single most expensive mistake available when editing
documentation, because removing the prompts leaves a green test suite
and a silently deleted test. When editing a file that contains examples,
count the prompts before and after.

**The fence tag is `python`** for a doctest session and `console` for a
shell command at a `$` prompt.

**Where examples run.** `testpaths` lists `src/libvt`, `tests`,
`docs`, and `README.md`. `addopts` sets `--doctest-docutils-modules` and
`-p no:doctest`: the stdlib `doctest` pytest plugin is disabled, and
`gp-libs`' docutils-based collector (`pytest_doctest_docutils`, loaded
under the `sphinx` entry-point name) runs in its place. That collector
reads doctests out of `.py` docstrings *and* out of any Markdown or
reStructuredText page docutils parses — which is why a `>>> ` block in
`README.md` or under `docs/` is executed exactly like one in a
docstring. `ELLIPSIS` and `NORMALIZE_WHITESPACE` are enabled globally
(`doctest_optionflags`), so `...` elides variable output and whitespace
differences do not fail a comparison. Reach for an inline
`# doctest: +FLAG` only for the block that needs something more.

**`# doctest: +SKIP` is not permitted.** It is a workaround that tests
nothing. Use the fixtures.

**Do not downgrade a doctest to a non-executed block to make it pass.**
A `.. code-block::` or an unprompted fence does not run. If an example
cannot pass, fix the example or fix the code.

**The `doctest_namespace` fixtures.** The root `conftest.py`'s
`_seed_doctest_namespace` autouse fixture populates `doctest_namespace`
before every doctest in the suite runs, making common entry points
available without boilerplate: `libvt`, `Terminal`, `AnsiColor`,
`assert_screen`, and `assert_screen_box`. Standalone documentation blocks
should still show explicit imports when doing so makes the first example
on a page clear to a reader copying it.

**Cross-platform doctests.** `pytest` executes `README.md` and `docs/`
doctests on Linux, macOS, and Windows in CI. Keep documentation doctests
portable across all three platforms (for example, drive
`AsyncTerminalStream` with an in-memory `asyncio.StreamReader` rather
than calling POSIX-only `open_pty()` inside an unguarded doctest).

**`# doctest: +HIDE`.** A `gp-libs` extension flag: it is a no-op for
execution and checking — the line still runs and its output, if any, is
still verified — but it tells the Sphinx-rendered docs to drop that line
from the page. Use it to set up state a docstring's *Examples* section
does not need to show:
writing one the test suite executes, matching `pyproject.toml`'s
`[tool.pytest.ini_options]`, root `conftest.py`, and
`tests/_docs_codeblocks.py`.

**Three Markdown block forms execute under `pytest`:**

1. **Doctest `python` fences** (`>>> ` prompts) in docstrings, `README.md`,
and `docs/**/*.md` run through `gp-libs`' docutils collector
(`--doctest-docutils-modules`, `-p no:doctest`) with `ELLIPSIS` and
`NORMALIZE_WHITESPACE` enabled globally.
2. **Plain `python` fences** (no `>>> ` prompts) in `README.md` and
`docs/**/*.md` run through `conftest.py`'s `pytest_collect_file` hook
(`tests._docs_codeblocks`, marked `documentation`). Each block runs in
isolation with no implicit globals, so every plain `python` block must
include explicit imports. Blocks that define top-level `def test_*`,
`async def test_*`, or `class Test*` definitions without calling them
execute inside a temporary `pytest` run against the real
`libvt.pytest_plugin` fixtures (and blocks requesting `vt_snapshot` run
`--snapshot-update` followed by a deterministic match pass when `syrupy` is
active).
3. **`console` fences and `{literalinclude}` directives** in `README.md`
and `docs/**/*.md` run through the same `documentation` collector.
Runnable commands (`python -m libvt`, `printf ... | python -m libvt`,
`examples/`, read-only `scripts/`, and explicit non-recursive `pytest`
targets under `tests/` or `examples/`) execute with `$HOME`, `XDG_*`,
and `TMPDIR` redirected into a temporary directory; expected output
lines beneath a runnable `$ ` command are compared against UTF-8 stdout.
Network- or environment-mutating blocks (package installs,
`docs/project/releasing.md` git templates, interactive TUI loops, and
optional external-tool invocations) are classified non-runnable, reject
trailing lines, and run static checks. Any unclassified shell or
`console` fence fails `pytest`.

**The fence tag is `python`** for executable Python snippets or doctests
and `console` for shell commands at a `$ ` prompt. Use
`uv run pytest -m documentation` to run only the Markdown code-block and
`{literalinclude}` checks, or target a single page such as
`uv run pytest README.md`.

**Where examples run.** `testpaths` lists `src/libvt`, `tests`, `docs`,
and `README.md`. The docs code-block collector lives in
`tests/_docs_codeblocks.py` (included in sdists, excluded from built wheels
and `pytest11` entry points). Every `python` fence in `MIGRATION` is
classified as a historical `# Before` / `# After` block and checked in
`tests/test_docs_codeblocks.py`.

**`# doctest: +SKIP` is not permitted.** Use fixtures or explicit platform
guards instead.

**Do not downgrade an example to an unexecuted block to make it pass.**
If an example fails, fix the example or fix the code.

**The `doctest_namespace` fixtures.** Root `conftest.py`'s
`_seed_doctest_namespace` autouse fixture populates `doctest_namespace` for
`>>> ` doctests only (`libvt`, `Terminal`, `AnsiColor`, `assert_screen`,
`assert_screen_box`, and `vt_*` fixtures). Plain `python` blocks never
receive `doctest_namespace`; standalone doctest blocks on `README.md`,
`docs/quickstart.md`, and testing/snapshot/API pages also verify explicit
imports in `tests/test_libvt.py`.

**Cross-platform examples.** `pytest` executes `README.md` and `docs/`
blocks on Linux, macOS, Windows, and PyPy in CI. Keep documentation
examples portable across those targets (for example, guard POSIX-only
`open_pty()` calls or drive `AsyncTerminalStream` with an in-memory
`asyncio.StreamReader`).

**`# doctest: +HIDE`.** A `gp-libs` extension flag for `>>> ` doctests: the
line still runs and its output is verified, while Sphinx omits that line
from rendered HTML. Use plain `python` fences instead of `# doctest: +HIDE`
shims for copy-pasteable `pytest` examples.

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

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

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

Expand All @@ -229,15 +230,6 @@ the story coherent.
>>> add(2, 2)
4

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

## Documentation pages

Warm the framing, never the facts. Resolution-order lists, value
Expand Down
13 changes: 13 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,19 @@ Add dedicated API reference pages for {mod}`libvt.views`,
`syrupy`) into per-module directories, and add Sphinx `rediraffe` redirects for
moved API URLs.

### Development

#### Execute plain Python and console Markdown code blocks in `pytest` (#219)

`pytest` now collects and runs plain `python` code blocks, runnable `console`
commands, and MyST `{literalinclude}` directives across `README.md` and
`docs/` alongside `>>> ` doctests (`pytest -m documentation`). Plain `python`
blocks run in isolation with explicit imports (and top-level `def test_*`
examples run against the real {mod}`libvt.pytest_plugin` fixtures), runnable
`console` blocks execute in a temporary sandbox, and unclassified shell fences
fail CI. The harness lives under `tests/` and stays excluded from built wheels
and `pytest11` entry points.

## libvt 0.0.1a6 (2026-12-05)

`libvt` 0.0.1a6 adds soft-wrapped logical-line reading and `wait_for()`
Expand Down
13 changes: 13 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import importlib.util
import pathlib
import typing as t

import pytest
Expand Down Expand Up @@ -40,3 +41,15 @@ def _seed_doctest_namespace(
"syrupy"
) is not None and request.config.pluginmanager.hasplugin("syrupy"):
doctest_namespace["vt_snapshot"] = request.getfixturevalue("vt_snapshot")


def pytest_collect_file(
file_path: pathlib.Path,
parent: pytest.Collector,
) -> pytest.Collector | None:
"""Collect plain Python, console, and literalinclude blocks from Markdown docs."""
if file_path.suffix.lower() != ".md":
return None
from tests._docs_codeblocks import collect_markdown_codeblocks

return collect_markdown_codeblocks(file_path, parent)
36 changes: 18 additions & 18 deletions docs/api/pytest_plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,26 @@ $ uv add --dev "libvt[pytest]>=0.0.1a6,<0.1"
## Quick start

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

```python
>>> from libvt.pytest_plugin import TerminalFactory
>>> from libvt.testing import assert_screen_box
>>> def test_inline_status(vt_factory: TerminalFactory) -> None:
... term = vt_factory(rows=2, cols=10)
... term.feed(b"\x1b[1;32mOK\x1b[0m\r\nready")
... assert_screen_box(
... term,
... """
... ┌──────────┐
... │OK │
... │ready │
... └──────────┘
... """,
... cursor=(1, 5),
... )
>>> test_inline_status(vt_factory) # doctest: +HIDE
from libvt.pytest_plugin import TerminalFactory
from libvt.testing import assert_screen_box


def test_inline_status(vt_factory: TerminalFactory) -> None:
term = vt_factory(rows=2, cols=10)
term.feed(b"\x1b[1;32mOK\x1b[0m\r\nready")
assert_screen_box(
term,
"""
┌──────────┐
│OK │
│ready │
└──────────┘
""",
cursor=(1, 5),
)
```

## Which fixture to request
Expand Down
15 changes: 8 additions & 7 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,14 @@ styles:
{fixture}`vt_recorder`, {fixture}`vt_parser`, and POSIX {fixture}`vt_pty`:

```python
>>> from libvt.pytest_plugin import TerminalFactory
>>> from libvt.testing import assert_screen
>>> def test_prompt(vt_factory: TerminalFactory) -> None:
... term = vt_factory(rows=1, cols=10)
... term.feed(b"ready> ")
... assert_screen(term, "ready> ", cursor=(0, 7))
>>> test_prompt(vt_factory) # doctest: +HIDE
from libvt.pytest_plugin import TerminalFactory
from libvt.testing import assert_screen


def test_prompt(vt_factory: TerminalFactory) -> None:
term = vt_factory(rows=1, cols=10)
term.feed(b"ready> ")
assert_screen(term, "ready> ", cursor=(0, 7))
```

## Golden `.ambr` adapter (`libvt[syrupy]`)
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ convention = "numpy"
[tool.ruff.lint.per-file-ignores]
"*/__init__.py" = ["F401"]
"docs/conf.py" = ["S102"]
"tests/_docs_codeblocks.py" = ["S102"]
"scripts/benchmark.py" = ["B008"]
"scripts/bench_vt.py" = ["T201"]

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