diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 5627977..216f550 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -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 diff --git a/.github/WRITING.md b/.github/WRITING.md index 4902e52..b026885 100644 --- a/.github/WRITING.md +++ b/.github/WRITING.md @@ -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: @@ -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 diff --git a/CHANGES b/CHANGES index 68d2f97..8df32f0 100644 --- a/CHANGES +++ b/CHANGES @@ -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()` diff --git a/conftest.py b/conftest.py index 89eb367..8557f8f 100644 --- a/conftest.py +++ b/conftest.py @@ -3,6 +3,7 @@ from __future__ import annotations import importlib.util +import pathlib import typing as t import pytest @@ -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) diff --git a/docs/api/pytest_plugin.md b/docs/api/pytest_plugin.md index 76aab60..5750158 100644 --- a/docs/api/pytest_plugin.md +++ b/docs/api/pytest_plugin.md @@ -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 diff --git a/docs/quickstart.md b/docs/quickstart.md index a291e55..b815e91 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -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]`) diff --git a/pyproject.toml b/pyproject.toml index ce1c9a9..cf5ce5d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] @@ -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", ] diff --git a/tests/_docs_codeblocks.py b/tests/_docs_codeblocks.py new file mode 100644 index 0000000..3bdceda --- /dev/null +++ b/tests/_docs_codeblocks.py @@ -0,0 +1,1780 @@ +"""Collect and execute Markdown code blocks and literalincludes in pytest. + +This repo-local helper powers documentation verification for ``README.md``, +``docs/**/*.md``, and ``MIGRATION``. It lives under ``tests/`` so it is shipped +in sdists for downstream test runs while staying excluded from built wheels and +``pytest11`` entry points. +""" + +from __future__ import annotations + +import ast +import contextlib +import doctest +import enum +import importlib.util +import json +import os +import pathlib +import re +import shlex +import shutil +import subprocess +import sys +import tempfile +import textwrap +import tomllib +import typing as t +from dataclasses import dataclass + +import pytest + +if t.TYPE_CHECKING: + import collections.abc as cabc + + from _pytest._code.code import TerminalRepr + +_BACKTICK_OR_TILDE_OPEN_RE = re.compile(r"^([ \t]*)(`{3,}|~{3,})([^\r\n]*)$") +_COLON_OPEN_RE = re.compile(r"^([ \t]*)(:{3,})\{([^}\r\n]+)\}([^\r\n]*)$") +_MYST_CODE_DIRECTIVES = frozenset({"{code}", "{code-block}", "{sourcecode}"}) +_MYST_OPTION_RE = re.compile(r"^:[a-zA-Z0-9_-]+:(?:\s.*)?$") +_PACKAGE_SPEC_RE = re.compile( + r"^(?P[A-Za-z0-9._-]+)(?:\[(?P[A-Za-z0-9._,-]+)\])?" + r"(?:[<>=!~].*)?$" +) +_HEX_CHARS = frozenset("0123456789abcdefABCDEF") + +PYTHON_LANGUAGES = frozenset({"python", "py", "python3"}) +SHELL_LANGUAGES = frozenset( + {"console", "bash", "sh", "shell", "zsh", "powershell", "cmd"} +) + +_EXCLUDED_PARTS = frozenset({"_build", "AGENTS.md", "CLAUDE.md"}) +_EXCLUDED_REL_PATHS = frozenset({"docs/project/adr/_template.md"}) +_OPTIONAL_BENCHMARK_DEPS = ("click", "pydantic", "rich", "typer") +_READONLY_BENCHMARK_SUBCOMMANDS = frozenset( + {"list-commands", "list-commits", "show-config"} +) +_HEAVY_BENCHMARK_SUBCOMMANDS = frozenset({"run", "compare"}) +_READONLY_SCRIPTS = frozenset({"scripts/bench_vt.py", "scripts/check_workarounds.py"}) +_RECURSION_ENV_VAR = "LIBVT_DOCS_CODEBLOCK_ACTIVE" +_REPO_RELATIVE_HINTS = ("examples/", "docs/", "tests/", "scripts/") + + +class ConsoleKind(enum.Enum): + """Classification for a Markdown console or shell code block.""" + + RUN = "run" + NON_RUNNABLE = "non-runnable" + UNCLASSIFIED = "unclassified" + + +@dataclass(frozen=True, slots=True) +class MarkdownBlock: + """One fenced block parsed from a Markdown or MyST document. + + Attributes + ---------- + path : pathlib.Path + Absolute path of the source Markdown file. + rel_path : str + Repository-relative POSIX path of the source Markdown file. + index : int + Zero-based fence index within the source file. + start_line : int + One-based line number of the opening fence. + content_line : int + One-based line number of the first line inside the fence. + language : str + Normalized lowercase language or directive name. + info : str + Full fence info string after the fence delimiter. + body : str + Dedented block contents without the opening or closing fences. + has_doctest_prompts : bool + ``True`` when the block is a doctest session starting with ``>>>``. + """ + + path: pathlib.Path + rel_path: str + index: int + start_line: int + content_line: int + language: str + info: str + body: str + has_doctest_prompts: bool + + +@dataclass(frozen=True, slots=True) +class ConsoleCommand: + """One logical ``$`` command and optional expected output lines. + + Attributes + ---------- + command : str + Logical shell command after joining trailing backslash continuations. + expected_output : tuple[str, ...] + Non-prompt lines immediately following the command in the block. + """ + + command: str + expected_output: tuple[str, ...] = () + + +@dataclass(frozen=True, slots=True) +class ConsoleClassification: + """Explicit classification result for a console block. + + Attributes + ---------- + kind : ConsoleKind + Whether the block runs, is explicitly non-runnable, or is unclassified. + category : str + Short category label (e.g. ``package-install``, ``python-script``). + reason : str + Human-readable explanation surfaced in test reports and errors. + """ + + kind: ConsoleKind + category: str + reason: str + + +@dataclass(frozen=True, slots=True) +class _ProcessResult: + """UTF-8 decoded result from a sandboxed subprocess call.""" + + returncode: int + stdout: str + stderr: str + + +class CodeBlockError(AssertionError): + """Failure raised when a documented code block fails verification.""" + + +def is_checked_markdown(file_path: pathlib.Path, repo_root: pathlib.Path) -> bool: + """Return ``True`` when *file_path* is ``README.md`` or a checked ``docs/`` page.""" + if file_path.suffix.lower() != ".md": + return False + try: + rel = file_path.resolve().relative_to(repo_root.resolve()) + except ValueError: + return False + if any(part in _EXCLUDED_PARTS for part in rel.parts): + return False + rel_posix = rel.as_posix() + if rel_posix in _EXCLUDED_REL_PATHS: + return False + return rel_posix == "README.md" or (len(rel.parts) >= 2 and rel.parts[0] == "docs") + + +def _strip_doctest_hide(match: re.Match[str]) -> str: + """Remove ``+HIDE`` from a ``# doctest: ...`` directive, keeping other flags.""" + flags = [ + flag + for flag in re.split(r"[\s,]+", match.group(1).strip()) + if flag and flag != "+HIDE" + ] + if not flags: + return "" + return f" # doctest: {', '.join(flags)}" + + +def _is_pure_doctest(body: str) -> bool: + """Return ``True`` when *body* is purely a doctest session, not plain Python.""" + try: + ast.parse(body) + except SyntaxError: + pass + else: + return False + normalized = re.sub( + r"[ \t]*#[ \t]*doctest:[ \t]*([^\n]+)", + _strip_doctest_hide, + body, + ) + try: + parts = doctest.DocTestParser().parse(normalized) + except ValueError: + return False + has_example = False + for part in parts: + if isinstance(part, doctest.Example): + has_example = True + elif part.strip(): + return False + return has_example + + +def _strip_myst_options(lines: list[str]) -> tuple[list[str], int]: + """Strip leading MyST ``:key: value`` option lines from a code directive.""" + idx = 0 + while idx < len(lines) and _MYST_OPTION_RE.match(lines[idx].strip()): + idx += 1 + while idx < len(lines) and not lines[idx].strip(): + idx += 1 + return lines[idx:], idx + + +_COLON_CODE_DIRECTIVES = frozenset( + {"code", "code-block", "sourcecode", "literalinclude"} +) + + +def _parse_opening_fence( + line: str, +) -> tuple[str, str, int, str] | None: + """Parse a CommonMark backtick/tilde fence or MyST ``:::`` code directive. + + Returns ``(indent, fence_char, fence_len, info)`` or ``None``. + """ + colon = _COLON_OPEN_RE.match(line) + if colon is not None: + indent, fence, directive, arg = ( + colon.group(1), + colon.group(2), + colon.group(3).strip(), + colon.group(4).strip(), + ) + if directive.lower() not in _COLON_CODE_DIRECTIVES: + return None + info = f"{{{directive}}} {arg}".strip() + return (indent, ":", len(fence), info) + + match = _BACKTICK_OR_TILDE_OPEN_RE.match(line) + if match is None: + return None + indent, fence, raw_info = match.group(1), match.group(2), match.group(3) + fence_char = fence[0] + # CommonMark §4.5 forbids backticks in backtick fence info strings. + if fence_char == "`" and "`" in raw_info: + return None + return (indent, fence_char, len(fence), raw_info.strip()) + + +def _normalize_directive_block( + info: str, + body_lines: list[str], + content_line: int, +) -> tuple[str, list[str], int]: + """Normalize MyST ``{code-block}`` / ``{code}`` / ``{sourcecode}`` blocks.""" + tokens = info.split() + if not tokens: + return "", body_lines, content_line + first = tokens[0].lower() + if first in _MYST_CODE_DIRECTIVES: + lang = tokens[1].lower() if len(tokens) > 1 else "" + stripped, offset = _strip_myst_options(body_lines) + return lang, stripped, content_line + offset + return first, body_lines, content_line + + +def parse_markdown_blocks( + path: pathlib.Path, + repo_root: pathlib.Path, +) -> list[MarkdownBlock]: + """Parse all fenced blocks from *path*, raising on unclosed fences.""" + try: + rel_path = path.resolve().relative_to(repo_root.resolve()).as_posix() + except ValueError: + rel_path = path.name + + lines = path.read_text(encoding="utf-8").splitlines() + blocks: list[MarkdownBlock] = [] + idx = 0 + block_index = 0 + while idx < len(lines): + opened = _parse_opening_fence(lines[idx]) + if opened is None: + idx += 1 + continue + indent, fence_char, fence_len, info = opened + # CommonMark §4.5 bounds closing fence indentation to opening indent + 3 spaces. + max_close_indent = len(indent.expandtabs(4)) + 3 + close_re = re.compile( + rf"^([ \t]*){re.escape(fence_char)}{{{fence_len},}}[ \t]*$" + ) + start_line = idx + 1 + content_line = idx + 2 + idx += 1 + body_lines: list[str] = [] + closed = False + while idx < len(lines): + close_match = close_re.match(lines[idx]) + if ( + close_match is not None + and len(close_match.group(1).expandtabs(4)) <= max_close_indent + ): + closed = True + idx += 1 + break + body_lines.append(lines[idx]) + idx += 1 + if not closed: + msg = f"Unclosed Markdown fence at {rel_path}:{start_line}" + raise ValueError(msg) + + # Strip list indentation matching the opening fence. + stripped_lines = [ + ln[len(indent) :] if indent and ln.startswith(indent) else ln + for ln in body_lines + ] + language, norm_lines, norm_content_line = _normalize_directive_block( + info, + stripped_lines, + content_line, + ) + body = textwrap.dedent("\n".join(norm_lines)) + has_doctest = language in PYTHON_LANGUAGES and _is_pure_doctest(body) + blocks.append( + MarkdownBlock( + path=path, + rel_path=rel_path, + index=block_index, + start_line=start_line, + content_line=norm_content_line, + language=language, + info=info, + body=body, + has_doctest_prompts=has_doctest, + ) + ) + block_index += 1 + return blocks + + +def parse_console_commands(body: str) -> list[ConsoleCommand]: + """Parse ``$``-prefixed commands and expected output lines from a console block.""" + lines = body.splitlines() + raw_commands: list[tuple[str, list[str]]] = [] + idx = 0 + while idx < len(lines): + stripped = lines[idx].strip() + if not stripped: + if raw_commands: + raw_commands[-1][1].append("") + idx += 1 + continue + if not stripped.startswith("$ "): + if not raw_commands: + return [] + raw_commands[-1][1].append(lines[idx]) + idx += 1 + continue + + parts = [stripped[2:].rstrip()] + idx += 1 + while parts[-1].endswith("\\") and idx < len(lines): + parts[-1] = parts[-1][:-1].rstrip() + parts.append(lines[idx].strip()) + idx += 1 + logical = " ".join(part for part in parts if part) + raw_commands.append((logical, [])) + + commands: list[ConsoleCommand] = [] + for logical, output_lines in raw_commands: + while output_lines and not output_lines[-1].strip(): + output_lines.pop() + commands.append( + ConsoleCommand(command=logical, expected_output=tuple(output_lines)) + ) + return commands + + +def _make_sandbox_env(sandbox_dir: pathlib.Path) -> dict[str, str]: + """Build an isolated subprocess environment rooted in *sandbox_dir*.""" + home_dir = sandbox_dir / "home" + tmp_dir = sandbox_dir / "tmp" + cfg_dir = sandbox_dir / "config" + cache_dir = sandbox_dir / "cache" + data_dir = sandbox_dir / "data" + tmux_dir = sandbox_dir / "tmux" + for directory in (home_dir, tmp_dir, cfg_dir, cache_dir, data_dir, tmux_dir): + directory.mkdir(parents=True, exist_ok=True) + + env = dict(os.environ) + env["HOME"] = str(home_dir) + env["USERPROFILE"] = str(home_dir) + env["XDG_CONFIG_HOME"] = str(cfg_dir) + env["XDG_CACHE_HOME"] = str(cache_dir) + env["XDG_DATA_HOME"] = str(data_dir) + env["TMPDIR"] = str(tmp_dir) + env["TEMP"] = str(tmp_dir) + env["TMP"] = str(tmp_dir) + env["TMUX_TMPDIR"] = str(tmux_dir) + env["PYTHONDONTWRITEBYTECODE"] = "1" + env["PYTHONUTF8"] = "1" + env["PYTHONIOENCODING"] = "utf-8" + env["COVERAGE_FILE"] = str(sandbox_dir / ".coverage") + env[_RECURSION_ENV_VAR] = "1" + env.pop("COVERAGE_PROCESS_START", None) + env.pop("COV_CORE_SOURCE", None) + return env + + +def _run_subprocess( + argv: list[str], + *, + cwd: pathlib.Path, + env: dict[str, str], + input_bytes: bytes | None = None, + timeout: float = 60.0, +) -> _ProcessResult: + """Run *argv* capturing raw bytes and decoding stdout/stderr as UTF-8.""" + if input_bytes is None: + completed = subprocess.run( + argv, + stdin=subprocess.DEVNULL, + cwd=cwd, + env=env, + capture_output=True, + timeout=timeout, + check=False, + ) + else: + completed = subprocess.run( + argv, + input=input_bytes, + cwd=cwd, + env=env, + capture_output=True, + timeout=timeout, + check=False, + ) + return _ProcessResult( + returncode=completed.returncode, + stdout=completed.stdout.decode("utf-8", errors="replace"), + stderr=completed.stderr.decode("utf-8", errors="replace"), + ) + + +def _safe_sandbox_path( + sandbox_dir: pathlib.Path, + raw_path: str, + location: str, +) -> pathlib.Path: + """Resolve relative *raw_path* inside *sandbox_dir*, rejecting escapes.""" + candidate = pathlib.Path(raw_path) + win_candidate = pathlib.PureWindowsPath(raw_path) + if ( + candidate.is_absolute() + or candidate.drive + or candidate.root + or win_candidate.drive + or win_candidate.root + or raw_path.startswith(("/", "\\")) + ): + msg = f"{location}: sandbox output path must be relative: {raw_path!r}" + raise CodeBlockError(msg) + resolved_root = sandbox_dir.resolve() + resolved = (resolved_root / candidate).resolve() + if resolved == resolved_root or not resolved.is_relative_to(resolved_root): + msg = f"{location}: sandbox output path escapes temporary root: {raw_path!r}" + raise CodeBlockError(msg) + return resolved + + +@contextlib.contextmanager +def _isolated_process_env( + sandbox_dir: pathlib.Path, +) -> cabc.Generator[pathlib.Path, None, None]: + """Temporarily point process HOME/TMP/XDG variables and ``tempfile`` at sandbox.""" + sandbox_env = _make_sandbox_env(sandbox_dir) + tracked_keys = ( + "HOME", + "USERPROFILE", + "XDG_CONFIG_HOME", + "XDG_CACHE_HOME", + "XDG_DATA_HOME", + "TMPDIR", + "TEMP", + "TMP", + "TMUX_TMPDIR", + _RECURSION_ENV_VAR, + ) + previous = {key: os.environ.get(key) for key in tracked_keys} + prev_cwd = pathlib.Path.cwd() + prev_sys_path = list(sys.path) + prev_tempdir = tempfile.tempdir + try: + for key in tracked_keys: + os.environ[key] = sandbox_env[key] + tempfile.tempdir = None + yield sandbox_dir + finally: + os.chdir(prev_cwd) + sys.path[:] = prev_sys_path + tempfile.tempdir = prev_tempdir + for key, old in previous.items(): + if old is None: + os.environ.pop(key, None) + else: + os.environ[key] = old + + +def _needs_pytest_runner(tree: ast.Module) -> bool: + """Return ``True`` when *tree* defines uninvoked ``test_*`` or ``class Test*``.""" + test_names = { + node.name + for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name.startswith("test_") + } + has_test_class = any( + isinstance(node, ast.ClassDef) + and node.name.startswith("Test") + and any( + isinstance(member, (ast.FunctionDef, ast.AsyncFunctionDef)) + and member.name.startswith("test_") + for member in node.body + ) + for node in tree.body + ) + if has_test_class: + return True + if not test_names: + return False + + called_at_top: set[str] = set() + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + continue + for child in ast.walk(node): + if ( + isinstance(child, ast.Call) + and isinstance(child.func, ast.Name) + and child.func.id in test_names + ): + called_at_top.add(child.func.id) + return bool(test_names - called_at_top) + + +def _requires_syrupy(tree: ast.Module) -> bool: + """Return ``True`` when *tree* imports ``syrupy`` or uses ``vt_snapshot``.""" + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if alias.name in {"syrupy", "libvt.contrib.syrupy"} or ( + alias.name.startswith(("syrupy.", "libvt.contrib.syrupy.")) + ): + return True + elif isinstance(node, ast.ImportFrom): + mod = node.module or "" + if ( + mod == "syrupy" + or mod.startswith(("syrupy.", "libvt.contrib.syrupy")) + or ( + mod == "libvt.contrib" + and any(alias.name == "syrupy" for alias in node.names) + ) + ): + return True + elif isinstance(node, ast.arg) and node.arg == "vt_snapshot": + return True + return False + + +def _uses_vt_snapshot(tree: ast.Module) -> bool: + """Return ``True`` when a ``test_*`` callable in *tree* takes ``vt_snapshot``.""" + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and ( + node.name.startswith("test_") + ): + all_args = [ + *node.args.posonlyargs, + *node.args.args, + *node.args.kwonlyargs, + ] + if any(arg.arg == "vt_snapshot" for arg in all_args): + return True + return False + + +def _syrupy_available(config: pytest.Config | None = None) -> bool: + """Return ``True`` when ``syrupy`` is installed and active in pytest.""" + if importlib.util.find_spec("syrupy") is None: + return False + if config is not None: + return bool(config.pluginmanager.hasplugin("syrupy")) + return True + + +def run_python_codeblock( + block: MarkdownBlock, + repo_root: pathlib.Path, + *, + pytest_config: pytest.Config | None = None, +) -> None: + """Compile and execute a plain ``python`` Markdown code block in isolation. + + Parameters + ---------- + block : MarkdownBlock + Parsed plain ``python`` fence without leading ``>>>`` doctest prompts. + repo_root : pathlib.Path + Repository root directory. + pytest_config : pytest.Config | None + Active pytest configuration used to check optional plugin availability. + """ + filename = f"{block.rel_path}:{block.start_line}" + if os.environ.get(_RECURSION_ENV_VAR) == "1": + msg = f"{filename}: recursive documentation code-block invocation" + raise CodeBlockError(msg) + if any(ln.lstrip().startswith(">>>") for ln in block.body.splitlines()): + try: + ast.parse(block.body, filename=filename) + except SyntaxError as exc: + msg = ( + f"Mixed unprompted Python and '>>>' doctest lines at {filename}: {exc}" + ) + raise CodeBlockError(msg) from exc + + padded = ("\n" * (block.content_line - 1)) + block.body + tree = ast.parse(padded, filename=filename) + if not tree.body: + msg = f"Empty plain python code block at {filename}" + raise CodeBlockError(msg) + + if _requires_syrupy(tree) and not _syrupy_available(pytest_config): + pytest.skip(f"{filename}: requires optional syrupy dependency") + + with tempfile.TemporaryDirectory(prefix="libvt-doc-py-") as tmp: + sandbox_dir = pathlib.Path(tmp).resolve() + if _needs_pytest_runner(tree): + test_file = sandbox_dir / "test_doc_example.py" + test_file.write_text(block.body + "\n", encoding="utf-8") + ini_file = sandbox_dir / "pytest.ini" + ini_file.write_text( + ( + "[pytest]\n" + "asyncio_mode = auto\n" + "asyncio_default_fixture_loop_scope = function\n" + ), + encoding="utf-8", + ) + env = _make_sandbox_env(sandbox_dir) + cmd = [ + sys.executable, + "-m", + "pytest", + "-q", + "--no-header", + "--tb=short", + "-c", + str(ini_file), + f"--rootdir={sandbox_dir}", + f"--basetemp={sandbox_dir / 'basetemp'}", + "-o", + f"cache_dir={sandbox_dir / 'pytest_cache'}", + str(test_file), + ] + if _uses_vt_snapshot(tree): + update_cmd = [*cmd[:-1], "--snapshot-update", cmd[-1]] + updated = _run_subprocess( + update_cmd, + cwd=sandbox_dir, + env=env, + timeout=60.0, + ) + if updated.returncode != 0: + msg = ( + f"Plain python syrupy block failed snapshot update at " + f"{filename} (exit {updated.returncode}):\n" + f"{updated.stdout}{updated.stderr}" + ) + raise CodeBlockError(msg) + ambr_files = [ + p + for p in (sandbox_dir / "__snapshots__").glob("*.ambr") + if p.stat().st_size > 0 + ] + if not ambr_files: + msg = ( + f"Plain python syrupy block wrote no .ambr snapshot at " + f"{filename}" + ) + raise CodeBlockError(msg) + result = _run_subprocess(cmd, cwd=sandbox_dir, env=env, timeout=60.0) + if result.returncode != 0: + msg = ( + f"Plain python pytest block failed at {filename} " + f"(exit {result.returncode}):\n" + f"{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + return + + code = compile(tree, filename, "exec") + namespace: dict[str, object] = { + "__name__": "__main__", + "__file__": str(block.path), + } + needs_repo_cwd = any(hint in block.body for hint in _REPO_RELATIVE_HINTS) + run_cwd = repo_root if needs_repo_cwd else sandbox_dir + with _isolated_process_env(sandbox_dir): + os.chdir(run_cwd) + exec(code, namespace, namespace) + + +def _decode_printf_bytes(format_arg: str, location: str) -> bytes: + """Decode common POSIX ``printf`` escapes into raw bytes without a shell.""" + out = bytearray() + idx = 0 + length = len(format_arg) + simple: dict[str, int] = { + "a": 0x07, + "b": 0x08, + "e": 0x1B, + "f": 0x0C, + "n": 0x0A, + "r": 0x0D, + "t": 0x09, + "v": 0x0B, + "\\": 0x5C, + '"': 0x22, + "'": 0x27, + } + while idx < length: + ch = format_arg[idx] + if ch == "%": + if idx + 1 < length and format_arg[idx + 1] == "%": + out.append(ord("%")) + idx += 2 + continue + msg = ( + f"{location}: unexpanded printf format specifier in {format_arg!r}; " + "use '%%' for a literal percent sign" + ) + raise CodeBlockError(msg) + if ch != "\\" or idx + 1 >= length: + out.extend(ch.encode("utf-8")) + idx += 1 + continue + nxt = format_arg[idx + 1] + if nxt in simple: + out.append(simple[nxt]) + idx += 2 + elif nxt == "x": + end = idx + 2 + while end < min(length, idx + 4) and format_arg[end] in _HEX_CHARS: + end += 1 + if end == idx + 2: + msg = f"{location}: invalid \\x escape in printf string {format_arg!r}" + raise CodeBlockError(msg) + out.append(int(format_arg[idx + 2 : end], 16)) + idx = end + elif nxt in "01234567": + end = idx + 2 + while end < min(length, idx + 4) and format_arg[end] in "01234567": + end += 1 + out.append(int(format_arg[idx + 1 : end], 8) & 0xFF) + idx = end + else: + out.extend(format_arg[idx : idx + 2].encode("utf-8")) + idx += 2 + return bytes(out) + + +def _split_pipeline(command: str) -> list[list[str]]: + """Split a shell command on unquoted ``|`` pipe operators, then ``shlex.split``.""" + raw_stages: list[str] = [] + buf: list[str] = [] + in_single = False + in_double = False + escaped = False + for ch in command: + if escaped: + buf.append(ch) + escaped = False + continue + if ch == "\\" and not in_single: + buf.append(ch) + escaped = True + continue + if ch == "'" and not in_double: + in_single = not in_single + buf.append(ch) + continue + if ch == '"' and not in_single: + in_double = not in_double + buf.append(ch) + continue + if ch == "|" and not in_single and not in_double: + raw_stages.append("".join(buf).strip()) + buf = [] + continue + buf.append(ch) + raw_stages.append("".join(buf).strip()) + return [shlex.split(stage, posix=True) for stage in raw_stages] + + +def _strip_uv_run(tokens: list[str]) -> list[str]: + """Strip a leading ``uv run`` prefix when present.""" + if len(tokens) >= 3 and tokens[0] == "uv" and tokens[1] == "run": + return tokens[2:] + return tokens + + +def _known_extras(repo_root: pathlib.Path) -> frozenset[str]: + """Read declared optional dependency extras from ``pyproject.toml``.""" + pyproject_path = repo_root / "pyproject.toml" + if not pyproject_path.is_file(): + return frozenset({"pytest", "syrupy"}) + data = tomllib.loads(pyproject_path.read_text(encoding="utf-8")) + opt = data.get("project", {}).get("optional-dependencies", {}) + if isinstance(opt, dict) and opt: + return frozenset(str(key) for key in opt) + return frozenset({"pytest", "syrupy"}) + + +def _validate_package_install( + tokens: list[str], + location: str, + repo_root: pathlib.Path, +) -> None: + """Validate ``uv add`` / ``pip install`` package specs syntactically.""" + specs = [tok for tok in tokens[2:] if not tok.startswith("-")] + if not specs: + msg = f"{location}: install command specifies no package" + raise CodeBlockError(msg) + known = _known_extras(repo_root) + for spec in specs: + match = _PACKAGE_SPEC_RE.match(spec) + if match is None or match.group("name") != "libvt": + msg = f"{location}: unexpected install package spec {spec!r}" + raise CodeBlockError(msg) + extras = match.group("extras") + if extras is not None: + unknown = set(extras.split(",")) - known + if unknown: + msg = f"{location}: unknown libvt extra(s) {sorted(unknown)}" + raise CodeBlockError(msg) + + +def _validate_python_script(path: pathlib.Path, location: str) -> None: + """Assert that a referenced Python script exists and parses cleanly.""" + if not path.is_file(): + msg = f"{location}: documented script not found: {path}" + raise CodeBlockError(msg) + ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + + +def _is_safe_relative_py_path(raw: str, allowed_roots: tuple[str, ...]) -> bool: + """Return ``True`` when *raw* is a normalized relative ``.py`` path under roots.""" + if not raw or raw.startswith(("/", "\\")) or "\\" in raw: + return False + pure = pathlib.PurePosixPath(raw) + if pure.is_absolute() or ".." in pure.parts or raw != pure.as_posix(): + return False + if len(pure.parts) < 2 or pure.parts[0] not in allowed_roots: + return False + return pure.suffix == ".py" + + +def _is_safe_pytest_target_command(args: list[str]) -> bool: + """Return ``True`` when pytest args target explicit non-recursive ``.py`` files.""" + targets: list[str] = [] + idx = 0 + value_flags = {"-k", "-m", "-c", "-o", "--basetemp", "--vt-replay-dir", "--rootdir"} + while idx < len(args): + arg = args[idx] + if arg == "-m": + if idx + 1 >= len(args) or "documentation" in args[idx + 1]: + return False + idx += 2 + continue + if arg.startswith("-m") and len(arg) > 2: + if "documentation" in arg[2:]: + return False + idx += 1 + continue + if arg in value_flags: + idx += 2 + continue + if arg.startswith("-"): + idx += 1 + continue + targets.append(arg) + idx += 1 + if not targets: + return False + for target in targets: + file_part = target.split("::", 1)[0] + if file_part.lower() == "tests/test_docs_codeblocks.py": + return False + if not _is_safe_relative_py_path(file_part, ("tests", "examples")): + return False + return True + + +def _classify_single_command( + cmd: ConsoleCommand, + block: MarkdownBlock, + *, + block_has_fire_pytest: bool, +) -> ConsoleClassification: + """Classify one logical command inside a ``console`` block.""" + location = f"{block.rel_path}:{block.start_line}" + try: + stages = _split_pipeline(cmd.command) + except ValueError as exc: + msg = f"{location}: invalid shell quoting in {cmd.command!r}: {exc}" + raise CodeBlockError(msg) from exc + if not stages or any(not stage for stage in stages): + return ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "unclassified", + f"empty pipeline stage in {cmd.command!r}", + ) + + # Support two-stage `printf '...' | python -m libvt ...` pipelines. + if len(stages) == 2: + lhs, rhs = stages + rhs_norm = _strip_uv_run(rhs) + if ( + len(lhs) == 2 + and lhs[0] == "printf" + and len(rhs_norm) >= 3 + and rhs_norm[0] == "python" + and rhs_norm[1] == "-m" + and rhs_norm[2] == "libvt" + ): + return ConsoleClassification( + ConsoleKind.RUN, + "cli-pipe", + "runnable printf | python -m libvt pipeline", + ) + return ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "unclassified", + f"unclassified pipeline command {cmd.command!r}", + ) + + if len(stages) > 2: + return ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "unclassified", + f"unclassified multi-stage pipeline {cmd.command!r}", + ) + + tokens = stages[0] + norm = _strip_uv_run(tokens) + + # 1. Package install snippets (uv add / pip install). + if (len(tokens) >= 3 and tokens[0] == "uv" and tokens[1] == "add") or ( + len(tokens) >= 3 and tokens[0] == "pip" and tokens[1] == "install" + ): + return ConsoleClassification( + ConsoleKind.NON_RUNNABLE, + "package-install", + "package installation snippet validated syntactically", + ) + + # 2. Release git commands documented in docs/project/releasing.md only. + if ( + block.rel_path == "docs/project/releasing.md" + and tokens[0] == "git" + and ( + ( + tokens[:2] in (["git", "commit"], ["git", "tag"]) + and "" in cmd.command + ) + or cmd.command == "git push && git push --tags" + ) + ): + return ConsoleClassification( + ConsoleKind.NON_RUNNABLE, + "release-git", + "release git command template (mutates repository/remotes)", + ) + + # 3. Optional external native library (LIBGHOSTTY_VT_PATH=... pytest -m ghostty). + if ( + tokens[0].startswith("LIBGHOSTTY_VT_PATH=") + and len(tokens) >= 4 + and _strip_uv_run(tokens[1:])[:1] == ["pytest"] + and "-m" in tokens + and "ghostty" in tokens + ): + return ConsoleClassification( + ConsoleKind.NON_RUNNABLE, + "optional-native-library", + "requires external compiled libghostty-vt shared library", + ) + + # 4. External just bench runner. + if tokens == ["just", "bench"]: + return ConsoleClassification( + ConsoleKind.NON_RUNNABLE, + "optional-external-tool", + "slow benchmark invocation via optional just binary", + ) + + # 5. Python commands (`python -m libvt ...`, `examples/...`, `scripts/...`). + if len(norm) >= 2 and norm[0] == "python": + if len(norm) >= 3 and norm[1] == "-m" and norm[2] == "libvt": + return ConsoleClassification( + ConsoleKind.RUN, + "cli-module", + "runnable python -m libvt CLI command", + ) + script_rel = norm[1] + if ( + script_rel.lower() == "examples/last_beacon/game.py" + and "--transcript" not in norm + ): + return ConsoleClassification( + ConsoleKind.NON_RUNNABLE, + "interactive-tui", + "interactive TTY game loop (no --transcript flag)", + ) + if script_rel == "scripts/benchmark.py": + subcmd = norm[2] if len(norm) >= 3 else "" + if subcmd in _HEAVY_BENCHMARK_SUBCOMMANDS: + return ConsoleClassification( + ConsoleKind.NON_RUNNABLE, + "heavy-git-worktree-benchmark", + "multi-commit worktree benchmark runner", + ) + if subcmd in _READONLY_BENCHMARK_SUBCOMMANDS: + return ConsoleClassification( + ConsoleKind.RUN, + "python-script", + f"runnable benchmark inspection command ({subcmd})", + ) + return ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "unclassified", + f"unclassified benchmark.py subcommand at {location}: {cmd.command!r}", + ) + if _is_safe_relative_py_path(script_rel, ("examples",)) or ( + script_rel in _READONLY_SCRIPTS + ): + return ConsoleClassification( + ConsoleKind.RUN, + "python-script", + f"runnable documented script {script_rel}", + ) + + # 6. Explicit non-recursive pytest invocations (`tests/...` or `examples/...`). + if norm[0] == "pytest" and _is_safe_pytest_target_command(norm[1:]): + return ConsoleClassification( + ConsoleKind.RUN, + "pytest-command", + "runnable pytest invocation", + ) + + # 7. FIRE evidence discovery following `pytest --basetemp fire-evidence-01`. + if ( + block_has_fire_pytest + and tokens[0] == "rg" + and "fire.json" in tokens + and "fire-evidence-01" in tokens + ): + return ConsoleClassification( + ConsoleKind.RUN, + "fire-evidence-check", + "verify fire.json artifacts produced by prior pytest command", + ) + + return ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "unclassified", + f"unclassified console command at {location}: {cmd.command!r}", + ) + + +def classify_console_block( + block: MarkdownBlock, +) -> tuple[list[ConsoleCommand], list[ConsoleClassification]]: + """Parse and classify every command in a ``console`` or shell fence.""" + location = f"{block.rel_path}:{block.start_line}" + if block.language != "console": + return [], [ + ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "unsupported-shell-language", + f"shell fence at {location} uses unsupported language " + f"{block.language!r}; use 'console' with '$ ' prompts", + ) + ] + + commands = parse_console_commands(block.body) + if not commands: + return [], [ + ConsoleClassification( + ConsoleKind.UNCLASSIFIED, + "empty-console-block", + f"console fence at {location} contains no '$ ' commands", + ) + ] + + has_fire_pytest = any( + "tests/test_fire.py" in cmd.command and "fire-evidence-01" in cmd.command + for cmd in commands + ) + classifications = [ + _classify_single_command( + cmd, + block, + block_has_fire_pytest=has_fire_pytest, + ) + for cmd in commands + ] + return commands, classifications + + +def _assert_expected_output( + expected: tuple[str, ...], + actual_stdout: str, + location: str, + command: str, +) -> None: + """Assert that *actual_stdout* matches documented non-prompt output lines.""" + if not expected: + return + exp_lines = [line.rstrip() for line in expected] + act_lines = [line.rstrip() for line in actual_stdout.splitlines()] + while act_lines and not act_lines[-1]: + act_lines.pop() + if act_lines != exp_lines: + msg = ( + f"Console output mismatch at {location} for {command!r}.\n" + f"Expected:\n{chr(10).join(exp_lines)}\n" + f"Actual:\n{chr(10).join(act_lines)}" + ) + raise CodeBlockError(msg) + + +def _rewrite_pytest_args( + args: list[str], + sandbox_dir: pathlib.Path, + location: str, +) -> tuple[list[str], pathlib.Path | None, bool]: + """Rewrite relative pytest output paths into *sandbox_dir*.""" + rewritten: list[str] = [ + "-o", + f"cache_dir={sandbox_dir / 'pytest_cache'}", + ] + replay_dir: pathlib.Path | None = None + has_basetemp = False + is_replay_demo = False + idx = 0 + while idx < len(args): + arg = args[idx] + if arg.split("::", 1)[0].lower() == "examples/replay_prompt.py": + is_replay_demo = True + rewritten.append(arg) + idx += 1 + elif arg == "--basetemp" and idx + 1 < len(args): + has_basetemp = True + target = _safe_sandbox_path(sandbox_dir, args[idx + 1], location) + rewritten.extend(["--basetemp", str(target)]) + idx += 2 + elif arg.startswith("--basetemp="): + has_basetemp = True + target = _safe_sandbox_path( + sandbox_dir, + arg.split("=", 1)[1], + location, + ) + rewritten.append(f"--basetemp={target}") + idx += 1 + elif arg.startswith("--vt-replay-dir="): + replay_dir = _safe_sandbox_path( + sandbox_dir, + arg.split("=", 1)[1], + location, + ) + rewritten.append(f"--vt-replay-dir={replay_dir}") + idx += 1 + elif arg == "--vt-replay-dir" and idx + 1 < len(args): + replay_dir = _safe_sandbox_path(sandbox_dir, args[idx + 1], location) + rewritten.extend(["--vt-replay-dir", str(replay_dir)]) + idx += 2 + else: + rewritten.append(arg) + idx += 1 + if not has_basetemp: + rewritten.append(f"--basetemp={sandbox_dir / 'basetemp'}") + return rewritten, replay_dir, is_replay_demo + + +def _run_non_runnable_checks( + cmd: ConsoleCommand, + classification: ConsoleClassification, + block: MarkdownBlock, + repo_root: pathlib.Path, +) -> None: + """Run static contract checks on explicitly non-runnable console commands.""" + location = f"{block.rel_path}:{block.start_line}" + if cmd.expected_output: + msg = ( + f"{location}: non-runnable command {cmd.command!r} carries unexpected " + f"trailing lines: {cmd.expected_output!r}" + ) + raise CodeBlockError(msg) + tokens = _split_pipeline(cmd.command)[0] + if classification.category == "package-install": + _validate_package_install(tokens, location, repo_root) + elif classification.category in { + "interactive-tui", + "heavy-git-worktree-benchmark", + }: + norm = _strip_uv_run(tokens) + script_rel = norm[1] + if script_rel.startswith("scripts/") and not (repo_root / "scripts").is_dir(): + pytest.skip(f"{location}: repository scripts/ directory required") + _validate_python_script(repo_root / script_rel, location) + elif classification.category == "optional-external-tool": + justfile = repo_root / "justfile" + if not justfile.is_file() and not (repo_root / ".git").exists(): + pytest.skip(f"{location}: repository justfile required") + if not justfile.is_file() or "bench *args:" not in justfile.read_text( + encoding="utf-8" + ): + msg = f"{location}: 'just bench' recipe missing from justfile" + raise CodeBlockError(msg) + elif classification.category == "optional-native-library": + pyproject = tomllib.loads( + (repo_root / "pyproject.toml").read_text(encoding="utf-8") + ) + markers = pyproject["tool"]["pytest"]["ini_options"]["markers"] + if not any(str(m).startswith("ghostty:") for m in markers): + msg = f"{location}: pytest marker 'ghostty' missing from pyproject.toml" + raise CodeBlockError(msg) + if not (repo_root / "tests" / "test_differential_ghostty.py").is_file(): + msg = f"{location}: tests/test_differential_ghostty.py is missing" + raise CodeBlockError(msg) + + +def _wants_json_format(script_args: list[str]) -> bool: + """Return ``True`` when the final ``--format`` flag requests ``json``.""" + selected: str | None = None + idx = 0 + while idx < len(script_args): + arg = script_args[idx] + if arg.startswith("--format="): + selected = arg.split("=", 1)[1] + idx += 1 + elif arg == "--format" and idx + 1 < len(script_args): + selected = script_args[idx + 1] + idx += 2 + else: + idx += 1 + return selected == "json" + + +def _rewrite_record_args( + script_args: list[str], + sandbox_dir: pathlib.Path, + location: str, +) -> tuple[list[str], pathlib.Path | None]: + """Validate and rewrite ``--record`` output paths into *sandbox_dir* before run.""" + rewritten: list[str] = [] + record_path: pathlib.Path | None = None + idx = 0 + while idx < len(script_args): + arg = script_args[idx] + if arg == "--record": + if idx + 1 >= len(script_args): + msg = f"{location}: --record flag requires an output path" + raise CodeBlockError(msg) + record_path = _safe_sandbox_path( + sandbox_dir, + script_args[idx + 1], + location, + ) + rewritten.extend(["--record", str(record_path)]) + idx += 2 + elif arg.startswith("--record="): + raw = arg.split("=", 1)[1] + record_path = _safe_sandbox_path(sandbox_dir, raw, location) + rewritten.append(f"--record={record_path}") + idx += 1 + else: + rewritten.append(arg) + idx += 1 + return rewritten, record_path + + +def _run_cli_pipe_command( + cmd: ConsoleCommand, + stages: list[list[str]], + sandbox_dir: pathlib.Path, + env: dict[str, str], + location: str, +) -> None: + """Execute a ``printf ... | python -m libvt ...`` console pipeline.""" + stdin_bytes = _decode_printf_bytes(stages[0][1], location) + rhs_norm = _strip_uv_run(stages[1]) + result = _run_subprocess( + [sys.executable, *rhs_norm[1:]], + cwd=sandbox_dir, + env=env, + input_bytes=stdin_bytes, + timeout=30.0, + ) + if result.returncode != 0: + msg = ( + f"Console command failed at {location}: {cmd.command!r} " + f"(exit {result.returncode})\n{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + _assert_expected_output(cmd.expected_output, result.stdout, location, cmd.command) + + +def _run_cli_module_command( + cmd: ConsoleCommand, + norm: list[str], + sandbox_dir: pathlib.Path, + env: dict[str, str], + location: str, +) -> None: + """Execute a standalone ``python -m libvt ...`` console command.""" + result = _run_subprocess( + [sys.executable, *norm[1:]], + cwd=sandbox_dir, + env=env, + timeout=30.0, + ) + if result.returncode != 0: + msg = ( + f"Console CLI failed at {location}: {cmd.command!r} " + f"(exit {result.returncode})\n{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + _assert_expected_output(cmd.expected_output, result.stdout, location, cmd.command) + + +def _run_python_script_command( + cmd: ConsoleCommand, + norm: list[str], + repo_root: pathlib.Path, + sandbox_dir: pathlib.Path, + env: dict[str, str], + location: str, +) -> None: + """Execute a documented ``examples/`` or ``scripts/`` Python script.""" + script_rel = norm[1] + if script_rel.startswith("scripts/") and not (repo_root / "scripts").is_dir(): + pytest.skip(f"{location}: repository scripts/ directory required") + script_path = (repo_root / script_rel).resolve() + if not script_path.is_relative_to(repo_root.resolve()): + msg = f"{location}: documented script escapes repository root: {script_rel!r}" + raise CodeBlockError(msg) + _validate_python_script(script_path, location) + script_args = norm[2:] + record_file: pathlib.Path | None = None + + script_key = script_rel.lower() + if script_key == "examples/tmux_screens.py": + if os.name != "posix" or shutil.which("tmux") is None: + pytest.skip(f"{location}: requires POSIX tmux") + elif script_key == "examples/last_beacon/tour.py": + script_args, record_file = _rewrite_record_args( + script_args, + sandbox_dir, + location, + ) + if "--replay" not in script_args and os.name != "posix": + pytest.skip(f"{location}: requires POSIX PTY") + if "--replay" in script_args and "beacon.json" in script_args: + beacon = sandbox_dir / "beacon.json" + if not beacon.exists(): + shutil.copyfile( + repo_root / "examples/last_beacon/walkthrough.json", + beacon, + ) + elif script_key == "scripts/benchmark.py": + if "list-commits" in script_args and not (repo_root / ".git").exists(): + pytest.skip(f"{location}: git checkout required for list-commits") + missing = [ + dep + for dep in _OPTIONAL_BENCHMARK_DEPS + if importlib.util.find_spec(dep) is None + ] + if missing: + pytest.skip(f"{location}: requires optional benchmark deps {missing}") + + run_cwd = repo_root if script_key == "scripts/benchmark.py" else sandbox_dir + result = _run_subprocess( + [sys.executable, str(script_path), *script_args], + cwd=run_cwd, + env=env, + timeout=60.0, + ) + if result.returncode != 0: + msg = ( + f"Documented script failed at {location}: {cmd.command!r} " + f"(exit {result.returncode})\n{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + if script_key == "scripts/bench_vt.py" and _wants_json_format(script_args): + json.loads(result.stdout) + if record_file is not None and not record_file.is_file(): + msg = f"{location}: expected recording {record_file.name}" + raise CodeBlockError(msg) + _assert_expected_output(cmd.expected_output, result.stdout, location, cmd.command) + + +def _run_pytest_command( + cmd: ConsoleCommand, + norm: list[str], + repo_root: pathlib.Path, + sandbox_dir: pathlib.Path, + env: dict[str, str], + location: str, +) -> None: + """Execute a documented ``pytest`` command against explicit non-recursive paths.""" + pytest_args = norm[1:] + if any( + arg.split("::", 1)[0].lower() == "tests/test_fzf_cookbook.py" + for arg in pytest_args + ) and (os.name != "posix" or shutil.which("fzf") is None): + pytest.skip(f"{location}: requires POSIX fzf") + rewritten, replay_dir, is_replay_demo = _rewrite_pytest_args( + pytest_args, + sandbox_dir, + location, + ) + result = _run_subprocess( + [sys.executable, "-m", "pytest", *rewritten], + cwd=repo_root, + env=env, + timeout=90.0, + ) + if is_replay_demo: + if result.returncode != 1: + msg = ( + f"{location}: expected replay demo to fail with exit 1, " + f"got {result.returncode}\n{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + if replay_dir is None or not replay_dir.is_dir(): + msg = f"{location}: replay demo produced no replay directory" + raise CodeBlockError(msg) + artifacts = sorted(replay_dir.rglob("*.json")) + if not artifacts: + msg = f"{location}: replay demo produced no JSON artifact" + raise CodeBlockError(msg) + replay = _run_subprocess( + [sys.executable, "-m", "libvt", "replay", str(artifacts[0])], + cwd=sandbox_dir, + env=env, + timeout=30.0, + ) + if replay.returncode != 0: + msg = ( + f"{location}: python -m libvt replay failed " + f"(exit {replay.returncode})\n{replay.stdout}{replay.stderr}" + ) + raise CodeBlockError(msg) + _assert_expected_output( + cmd.expected_output, result.stdout, location, cmd.command + ) + return + + if result.returncode != 0: + msg = ( + f"Documented pytest command failed at {location}: " + f"{cmd.command!r} (exit {result.returncode})\n" + f"{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + _assert_expected_output(cmd.expected_output, result.stdout, location, cmd.command) + + +def _run_fire_evidence_command( + cmd: ConsoleCommand, + tokens: list[str], + sandbox_dir: pathlib.Path, + env: dict[str, str], + location: str, +) -> None: + """Verify ``fire.json`` artifacts generated by the preceding FIRE pytest run.""" + evidence_dir = _safe_sandbox_path(sandbox_dir, "fire-evidence-01", location) + rg_bin = shutil.which("rg") + if rg_bin is not None: + result = _run_subprocess( + [rg_bin, *tokens[1:]], + cwd=sandbox_dir, + env=env, + timeout=30.0, + ) + if result.returncode != 0 or not result.stdout.strip(): + msg = ( + f"{location}: rg found no fire.json reports " + f"(exit {result.returncode})\n{result.stdout}{result.stderr}" + ) + raise CodeBlockError(msg) + normalized = "\n".join( + pathlib.Path(line).as_posix() for line in result.stdout.splitlines() + ) + _assert_expected_output(cmd.expected_output, normalized, location, cmd.command) + else: + reports = sorted(evidence_dir.rglob("fire.json")) + if not reports: + msg = f"{location}: no fire.json reports in {evidence_dir}" + raise CodeBlockError(msg) + if cmd.expected_output: + resolved_sandbox = sandbox_dir.resolve() + actual = "\n".join( + p.relative_to(resolved_sandbox).as_posix() for p in reports + ) + _assert_expected_output(cmd.expected_output, actual, location, cmd.command) + + +def run_console_codeblock(block: MarkdownBlock, repo_root: pathlib.Path) -> None: + """Validate and execute all runnable commands in a Markdown console block.""" + location = f"{block.rel_path}:{block.start_line}" + if os.environ.get(_RECURSION_ENV_VAR) == "1": + msg = f"{location}: recursive documentation code-block invocation" + raise CodeBlockError(msg) + + commands, classifications = classify_console_block(block) + unclassified = [ + item.reason for item in classifications if item.kind is ConsoleKind.UNCLASSIFIED + ] + if unclassified: + msg = f"Unclassified console block at {location}: " + "; ".join(unclassified) + raise CodeBlockError(msg) + + with tempfile.TemporaryDirectory(prefix="libvt-doc-console-") as tmp: + sandbox_dir = pathlib.Path(tmp).resolve() + env = _make_sandbox_env(sandbox_dir) + for cmd, classification in zip(commands, classifications, strict=True): + if classification.kind is ConsoleKind.NON_RUNNABLE: + _run_non_runnable_checks(cmd, classification, block, repo_root) + continue + + stages = _split_pipeline(cmd.command) + if classification.category == "cli-pipe": + _run_cli_pipe_command(cmd, stages, sandbox_dir, env, location) + continue + + tokens = stages[0] + norm = _strip_uv_run(tokens) + if classification.category == "cli-module": + _run_cli_module_command(cmd, norm, sandbox_dir, env, location) + elif classification.category == "python-script": + _run_python_script_command( + cmd, norm, repo_root, sandbox_dir, env, location + ) + elif classification.category == "pytest-command": + _run_pytest_command(cmd, norm, repo_root, sandbox_dir, env, location) + elif classification.category == "fire-evidence-check": + _run_fire_evidence_command(cmd, tokens, sandbox_dir, env, location) + + +def run_literalinclude_check(block: MarkdownBlock, repo_root: pathlib.Path) -> None: + """Verify a MyST ``{literalinclude}`` directive target and slice markers.""" + location = f"{block.rel_path}:{block.start_line}" + parts = block.info.split(None, 1) + if len(parts) != 2 or not parts[1].strip(): + msg = f"{location}: literalinclude directive is missing a target path" + raise CodeBlockError(msg) + raw_target = parts[1].strip() + if raw_target.startswith("/"): + # Sphinx resolves leading '/' relative to docs/ srcdir. + target = (repo_root / "docs" / raw_target.lstrip("/")).resolve() + else: + target = (block.path.parent / raw_target).resolve() + if not target.is_relative_to(repo_root.resolve()) or not target.is_file(): + msg = f"{location}: literalinclude target not found: {raw_target}" + raise CodeBlockError(msg) + + options: dict[str, str] = {} + for line in block.body.splitlines(): + opt = re.match(r"^:([a-z-]+):\s*(.*)$", line.strip()) + if opt is not None: + options[opt.group(1)] = opt.group(2).strip() + + text = target.read_text(encoding="utf-8") + if options.get("language") == "python" or target.suffix == ".py": + ast.parse(text, filename=str(target)) + + lines = text.splitlines() + start_idx = 0 + if "start-at" in options: + needle = options["start-at"] + matches = [i for i, ln in enumerate(lines) if needle in ln] + if not matches: + msg = f"{location}: :start-at: {needle!r} not found in {target.name}" + raise CodeBlockError(msg) + start_idx = matches[0] + elif "start-after" in options: + needle = options["start-after"] + matches = [i for i, ln in enumerate(lines) if needle in ln] + if not matches: + msg = f"{location}: :start-after: {needle!r} not found in {target.name}" + raise CodeBlockError(msg) + start_idx = matches[0] + 1 + + end_idx = len(lines) + if "end-before" in options: + needle = options["end-before"] + matches = [i for i in range(start_idx, len(lines)) if needle in lines[i]] + if not matches: + msg = ( + f"{location}: :end-before: {needle!r} not found after start " + f"in {target.name}" + ) + raise CodeBlockError(msg) + end_idx = matches[0] + elif "end-at" in options: + needle = options["end-at"] + matches = [i for i in range(start_idx, len(lines)) if needle in lines[i]] + if not matches: + msg = ( + f"{location}: :end-at: {needle!r} not found after start " + f"in {target.name}" + ) + raise CodeBlockError(msg) + end_idx = matches[0] + 1 + + if end_idx <= start_idx: + msg = f"{location}: literalinclude slice is empty in {target.name}" + raise CodeBlockError(msg) + + +def classify_migration_blocks( + repo_root: pathlib.Path, +) -> list[tuple[MarkdownBlock, str]]: + """Classify every ``python`` fence in ``MIGRATION`` as historical or fail. + + Parameters + ---------- + repo_root : pathlib.Path + Repository root containing ``MIGRATION``. + + Returns + ------- + list[tuple[MarkdownBlock, str]] + Pairs of ``(block, classification)`` for every ``python`` fence found. + """ + migration = repo_root / "MIGRATION" + blocks = parse_markdown_blocks(migration, repo_root) + classified: list[tuple[MarkdownBlock, str]] = [] + for block in blocks: + if block.language not in PYTHON_LANGUAGES: + continue + lines = [ln.strip() for ln in block.body.splitlines() if ln.strip()] + has_before = any(ln.startswith("# Before") for ln in lines) + has_after = any(ln.startswith("# After") for ln in lines) + if not (has_before and has_after): + msg = ( + f"Unclassified python block in {block.rel_path}:{block.start_line}: " + "expected historical '# Before' / '# After' migration block" + ) + raise CodeBlockError(msg) + classified.append((block, "historical-migration-diff")) + return classified + + +class _MarkdownCodeBlockItem(pytest.Item): + """Pytest item representing one Markdown code block or literalinclude.""" + + def __init__( + self, + *, + name: str, + parent: pytest.Collector, + block: MarkdownBlock, + repo_root: pathlib.Path, + runner: cabc.Callable[[MarkdownBlock, pathlib.Path], None], + **kwargs: t.Any, # pytest Node cooperative constructor forwards dynamic kwargs + ) -> None: + super().__init__(name=name, parent=parent, **kwargs) + self._block = block + self._repo_root = repo_root + self._runner = runner + self.add_marker(pytest.mark.documentation) + + def runtest(self) -> None: + """Execute the configured documentation block validator.""" + self._runner(self._block, self._repo_root) + + def repr_failure( + self, + excinfo: pytest.ExceptionInfo[BaseException], + style: t.Literal["long", "short", "line", "no", "native", "value", "auto"] + | None = None, + ) -> str | TerminalRepr: + """Render ``CodeBlockError`` messages cleanly without pytest internals.""" + if isinstance(excinfo.value, CodeBlockError): + return str(excinfo.value) + return super().repr_failure(excinfo, style=style) + + def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]: + """Return Markdown source path, zero-based line, and item label.""" + return ( + self._block.path, + self._block.start_line - 1, + f"{self._block.rel_path}:{self._block.start_line} [{self.name}]", + ) + + +class MarkdownCodeBlocksFile(pytest.File): + """Pytest file collector for plain Python, console, and literalinclude blocks.""" + + def __init__( + self, + *, + path: pathlib.Path, + parent: pytest.Collector, + repo_root: pathlib.Path, + **kwargs: t.Any, # pytest Node cooperative constructor forwards dynamic kwargs + ) -> None: + super().__init__(path=path, parent=parent, **kwargs) + self._repo_root = repo_root + + def _run_python_block(self, block: MarkdownBlock, repo_root: pathlib.Path) -> None: + run_python_codeblock(block, repo_root, pytest_config=self.config) + + def collect(self) -> cabc.Iterable[pytest.Item]: + """Yield pytest items for plain Python, shell, and literalinclude blocks.""" + for block in parse_markdown_blocks(self.path, self._repo_root): + if block.language in PYTHON_LANGUAGES and not block.has_doctest_prompts: + yield _MarkdownCodeBlockItem.from_parent( + self, + name=f"python[L{block.start_line}]", + block=block, + repo_root=self._repo_root, + runner=self._run_python_block, + ) + elif block.language in SHELL_LANGUAGES: + yield _MarkdownCodeBlockItem.from_parent( + self, + name=f"{block.language}[L{block.start_line}]", + block=block, + repo_root=self._repo_root, + runner=run_console_codeblock, + ) + elif block.language == "{literalinclude}": + yield _MarkdownCodeBlockItem.from_parent( + self, + name=f"literalinclude[L{block.start_line}]", + block=block, + repo_root=self._repo_root, + runner=run_literalinclude_check, + ) + + +def collect_markdown_codeblocks( + file_path: pathlib.Path, + parent: pytest.Collector, + *, + repo_root: pathlib.Path | None = None, +) -> MarkdownCodeBlocksFile | None: + """Return a :class:`MarkdownCodeBlocksFile` collector for checked Markdown files.""" + root = repo_root if repo_root is not None else pathlib.Path(parent.config.rootpath) + if not is_checked_markdown(file_path, root): + return None + return MarkdownCodeBlocksFile.from_parent( + parent, + path=file_path, + repo_root=root, + ) diff --git a/tests/test_docs_codeblocks.py b/tests/test_docs_codeblocks.py new file mode 100644 index 0000000..75f8ce2 --- /dev/null +++ b/tests/test_docs_codeblocks.py @@ -0,0 +1,1007 @@ +"""Tests and negative controls for Markdown code-block execution in pytest.""" + +from __future__ import annotations + +import ast +import importlib.util +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile +import tomllib +import traceback + +import pytest + +from tests._docs_codeblocks import ( + _RECURSION_ENV_VAR, + CodeBlockError, + ConsoleCommand, + ConsoleKind, + _decode_printf_bytes, + _is_pure_doctest, + _isolated_process_env, + _requires_syrupy, + _run_fire_evidence_command, + _run_subprocess, + _safe_sandbox_path, + _wants_json_format, + classify_console_block, + classify_migration_blocks, + is_checked_markdown, + parse_console_commands, + parse_markdown_blocks, + run_console_codeblock, + run_literalinclude_check, + run_python_codeblock, +) + +_REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent + + +def test_parse_markdown_blocks_handles_commonmark_myst_and_unclosed( + tmp_path: pathlib.Path, +) -> None: + """Parse backtick, tilde, colon, MyST directive, and CommonMark §4.5 fences.""" + doc = tmp_path / "docs" / "sample.md" + doc.parent.mkdir(parents=True) + doc.write_text( + ( + "# Sample\n" + "\n" + "```python``` is an inline code span, not a fence.\n" + "\n" + "```python\n" + "import libvt\n" + 'text = """\n' + " ```\n" + "\t```\n" + ' """\n' + "assert '```' in text\n" + "```\n" + "\n" + "~~~python\n" + ">>> 1 + 1\n" + "2\n" + "~~~\n" + "\n" + "1. Step:\n" + "\n" + " ```console\n" + " $ python -m libvt strip\n" + " ```\n" + "\n" + "```{code-block} python\n" + ":linenos:\n" + "\n" + "import libvt\n" + "assert libvt.strip(b'hi') == 'hi'\n" + "```\n" + "\n" + ":::{code-block} console\n" + "$ printf 'hi' | python -m libvt strip\n" + "hi\n" + ":::\n" + "\n" + ":::{literalinclude} ../examples/replay_prompt.py\n" + ":language: python\n" + ":::\n" + "\n" + "````markdown\n" + "```python\n" + "not a top-level fence\n" + "```\n" + "````\n" + ), + encoding="utf-8", + ) + + blocks = parse_markdown_blocks(doc, tmp_path) + assert [(b.language, b.has_doctest_prompts) for b in blocks] == [ + ("python", False), + ("python", True), + ("console", False), + ("python", False), + ("console", False), + ("{literalinclude}", False), + ("markdown", False), + ] + assert blocks[0].start_line == 5 + assert "```" in blocks[0].body + assert blocks[2].body == "$ python -m libvt strip" + assert blocks[3].body == "import libvt\nassert libvt.strip(b'hi') == 'hi'" + assert blocks[4].body == "$ printf 'hi' | python -m libvt strip\nhi" + + run_python_codeblock(blocks[0], _REPO_ROOT) + run_python_codeblock(blocks[3], _REPO_ROOT) + run_console_codeblock(blocks[4], _REPO_ROOT) + + unclosed = tmp_path / "docs" / "broken.md" + unclosed.write_text("```python\nx = 1\n", encoding="utf-8") + with pytest.raises(ValueError, match="Unclosed Markdown fence"): + parse_markdown_blocks(unclosed, tmp_path) + + +def test_is_checked_markdown_filters_paths(tmp_path: pathlib.Path) -> None: + """Only ``README.md`` and non-excluded ``docs/**/*.md`` pages are collected.""" + assert is_checked_markdown(tmp_path / "README.md", tmp_path) + assert is_checked_markdown(tmp_path / "docs" / "quickstart.md", tmp_path) + assert is_checked_markdown(tmp_path / "docs" / "topics" / "testing.md", tmp_path) + + assert not is_checked_markdown(tmp_path / "docs" / "_build" / "index.md", tmp_path) + assert not is_checked_markdown(tmp_path / "docs" / "AGENTS.md", tmp_path) + assert not is_checked_markdown(tmp_path / "docs" / "CLAUDE.md", tmp_path) + assert not is_checked_markdown( + tmp_path / "docs" / "project" / "adr" / "_template.md", + tmp_path, + ) + assert not is_checked_markdown(tmp_path / "CHANGELOG.md", tmp_path) + assert not is_checked_markdown(tmp_path / "docs" / "conf.py", tmp_path) + + +def test_plain_python_block_executes_enforces_imports_and_catches_mixed_doctest( + tmp_path: pathlib.Path, +) -> None: + """Plain ``python`` blocks enforce explicit imports and reject mixed doctests.""" + doc = tmp_path / "README.md" + doc.write_text( + ( + "# Demo\n" + "\n" + "```python\n" + "import pathlib\n" + "import tempfile\n" + "import libvt\n" + "term = libvt.Terminal(rows=1, cols=8)\n" + "term.feed(b'>>> ok')\n" + "assert term.committed.lines == ('>>> ok',)\n" + "pathlib.Path('relative_scratch.txt').write_text(" + "'safe', encoding='utf-8')\n" + "assert pathlib.Path(tempfile.gettempdir()).exists()\n" + "```\n" + "\n" + "```python\n" + "term = Terminal(rows=1, cols=8)\n" + "```\n" + "\n" + "```python\n" + "import libvt\n" + "assert libvt.render(b'ok') == 'wrong'\n" + "```\n" + "\n" + "```python\n" + "# comment only\n" + "```\n" + "\n" + "```python\n" + "import nonexistent_pkg\n" + "assert False\n" + ">>> 1 + 1\n" + "2\n" + "```\n" + "\n" + "```python\n" + ">>> 1 + 1\n" + "2\n" + "\n" + "import nonexistent_pkg\n" + "assert False\n" + "```\n" + ), + encoding="utf-8", + ) + ( + good, + missing_import, + bad_assert, + empty, + mixed_leading, + mixed_trailing, + ) = parse_markdown_blocks( + doc, + tmp_path, + ) + + assert not good.has_doctest_prompts + assert not mixed_leading.has_doctest_prompts + assert not mixed_trailing.has_doctest_prompts + + run_python_codeblock(good, _REPO_ROOT) + assert not (_REPO_ROOT / "relative_scratch.txt").exists() + + with pytest.raises(NameError, match="Terminal"): + run_python_codeblock(missing_import, _REPO_ROOT) + + with pytest.raises(AssertionError) as exc_info: + run_python_codeblock(bad_assert, _REPO_ROOT) + tb_text = "".join(traceback.format_tb(exc_info.tb)) + assert f"README.md:{bad_assert.start_line}" in tb_text + assert f"line {bad_assert.content_line + 1}" in tb_text + + with pytest.raises(CodeBlockError, match="Empty plain python code block"): + run_python_codeblock(empty, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Mixed unprompted Python"): + run_python_codeblock(mixed_leading, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Mixed unprompted Python"): + run_python_codeblock(mixed_trailing, _REPO_ROOT) + + +def test_plain_python_pytest_runner_catches_uncalled_siblings_and_test_classes( + tmp_path: pathlib.Path, +) -> None: + """Uncalled ``test_*`` functions and ``class Test*`` methods run via pytest.""" + doc = tmp_path / "docs" / "plugin_demo.md" + doc.parent.mkdir(parents=True) + doc.write_text( + ( + "```python\n" + "from libvt.pytest_plugin import TerminalFactory\n" + "from libvt.testing import assert_screen\n" + "\n" + "def test_ok(vt_factory: TerminalFactory) -> None:\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'hi')\n" + " assert_screen(term, 'hi', cursor=(0, 2))\n" + "```\n" + "\n" + "```python\n" + "def test_a() -> None:\n" + " assert True\n" + "\n" + "def test_b() -> None:\n" + " assert False\n" + "\n" + "test_a()\n" + "```\n" + "\n" + "```python\n" + "class TestBox:\n" + " def test_fail(self) -> None:\n" + " assert False\n" + "```\n" + ), + encoding="utf-8", + ) + passing, uncalled_sibling, failing_class = parse_markdown_blocks(doc, tmp_path) + + run_python_codeblock(passing, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Plain python pytest block failed"): + run_python_codeblock(uncalled_sibling, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Plain python pytest block failed"): + run_python_codeblock(failing_class, _REPO_ROOT) + + +def test_console_block_utf8_pipes_blank_lines_and_negative_controls( + tmp_path: pathlib.Path, +) -> None: + """Console blocks decode UTF-8 box glyphs and reject bypasses/unclassified cmds.""" + doc = tmp_path / "docs" / "cli.md" + doc.parent.mkdir(parents=True) + doc.write_text( + ( + "```console\n" + "$ printf '\\xe2\\x94\\x8c\\xe2\\x94\\x80\\xe2\\x94\\x90' " + "| python -m libvt strip\n" + "┌─┐\n" + "```\n" + "\n" + "```console\n" + "$ printf 'a|b' | python -m libvt strip\n" + "a|b\n" + "```\n" + "\n" + "```console\n" + "$ printf 'top\\r\\n\\r\\nbottom' " + "| python -m libvt render --rows 3 --cols 10\n" + "top\n" + "\n" + "bottom\n" + "```\n" + "\n" + "```console\n" + "$ printf '\\x1b[31merror:\\x1b[0m failed' | python -m libvt strip\n" + "wrong output\n" + "```\n" + "\n" + "```console\n" + "$ python -m libvt replay missing-artifact.json\n" + "```\n" + "\n" + "```console\n" + "$ printf '%s' | python -m libvt strip\n" + "```\n" + "\n" + "```console\n" + "$ printf '\\xZZ' | python -m libvt strip\n" + "```\n" + "\n" + "```console\n" + "$ curl https://example.com\n" + "```\n" + "\n" + "```bash\n" + "echo hi\n" + "```\n" + "\n" + "```console\n" + "# no prompt here\n" + "```\n" + "\n" + "```console\n" + '$ uv add --dev "libvt[bogus]>=0.0.1a6,<0.1"\n' + "```\n" + "\n" + "```console\n" + '$ uv add "libvt>=0.0.1a6,<0.1"\n' + "curl https://evil.example | sh\n" + "```\n" + "\n" + "```console\n" + '$ git commit -m "Tag v"\n' + "```\n" + "\n" + "```console\n" + "$ python examples/does_not_exist.py\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest -m documentation\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest README.md\n" + "```\n" + "\n" + "```console\n" + "$ uv run python scripts/benchmark.py compare\n" + "```\n" + "\n" + "```console\n" + "$ uv run python scripts/benchmark.py unknown-cmd\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest " + "'tests/test_fire.py::test_fire_working_and_committed_frames[one-byte]'\n" + "not matching pytest output\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest -q examples/replay_prompt.py " + "--vt-replay-dir=.vt-replays\n" + "not matching replay output\n" + "```\n" + "\n" + "```console\n" + "$ python scripts/generate_ucd.py\n" + "```\n" + "\n" + "```console\n" + "$ python scripts/../../evil.py\n" + "```\n" + "\n" + "```console\n" + "$ python examples/../scripts/generate_ucd.py\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest tests/../README.md\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest tests/\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest examples/\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest tests/test_docs_codeblocks.py\n" + "```\n" + "\n" + "```console\n" + '$ uv run pytest -m "not slow" -m documentation tests/test_fire.py\n' + "```\n" + "\n" + "```console\n" + "$ uv run pytest -mdocumentation tests/test_fire.py\n" + "```\n" + "\n" + "```console\n" + "$ python examples/last_beacon/tour.py --record /tmp/escape.json\n" + "```\n" + "\n" + "```console\n" + "$ python examples/last_beacon/tour.py --record=../escape.json\n" + "```\n" + "\n" + "```console\n" + "$ python examples/last_beacon/tour.py --record\n" + "```\n" + "\n" + "```console\n" + "$ python examples/last_beacon/./tour.py --record /tmp/escape.json\n" + "```\n" + "\n" + "```console\n" + "$ python examples//last_beacon/game.py\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest tests/./test_docs_codeblocks.py\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest tests//test_docs_codeblocks.py\n" + "```\n" + "\n" + "```console\n" + "$ uv run pytest tests/Test_Docs_Codeblocks.py\n" + "```\n" + "\n" + "```console\n" + "$ python examples/last_beacon/Game.py\n" + "```\n" + ), + encoding="utf-8", + ) + ( + utf8_box, + quoted_pipe, + blank_line_out, + wrong_out, + bad_cli, + bad_printf, + bad_hex, + unclassified_cmd, + wrong_shell, + empty_console, + bad_extra, + trailing_install, + stray_git, + missing_script, + bare_pytest, + recursive_doc_pytest, + readme_pytest, + bench_compare, + bench_unknown, + pytest_wrong_out, + replay_wrong_out, + mutating_ucd, + traverse_scripts, + traverse_examples, + pytest_traverse, + pytest_tests_dir, + pytest_examples_dir, + pytest_self, + pytest_multi_m, + pytest_attached_m, + record_abs, + record_eq_escape, + record_missing_val, + dot_tour, + double_slash_game, + pytest_dot_self, + pytest_double_slash_self, + pytest_mixed_case_self, + mixed_case_game, + ) = parse_markdown_blocks(doc, tmp_path) + + run_console_codeblock(utf8_box, _REPO_ROOT) + run_console_codeblock(quoted_pipe, _REPO_ROOT) + parsed_blank = parse_console_commands(blank_line_out.body) + assert parsed_blank[0].expected_output == ("top", "", "bottom") + run_console_codeblock(blank_line_out, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Console output mismatch"): + run_console_codeblock(wrong_out, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Console CLI failed"): + run_console_codeblock(bad_cli, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="unexpanded printf format"): + run_console_codeblock(bad_printf, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match=r"invalid \\x escape"): + run_console_codeblock(bad_hex, _REPO_ROOT) + + _, unclass_res = classify_console_block(unclassified_cmd) + assert unclass_res[0].kind is ConsoleKind.UNCLASSIFIED + with pytest.raises(CodeBlockError, match="Unclassified console block"): + run_console_codeblock(unclassified_cmd, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="unsupported language 'bash'"): + run_console_codeblock(wrong_shell, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="contains no '\\$ ' commands"): + run_console_codeblock(empty_console, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="unknown libvt extra"): + run_console_codeblock(bad_extra, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="unexpected trailing lines"): + run_console_codeblock(trailing_install, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Unclassified console block"): + run_console_codeblock(stray_git, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="documented script not found"): + run_console_codeblock(missing_script, _REPO_ROOT) + + for blocked in ( + bare_pytest, + recursive_doc_pytest, + readme_pytest, + mutating_ucd, + traverse_scripts, + traverse_examples, + pytest_traverse, + pytest_tests_dir, + pytest_examples_dir, + pytest_self, + pytest_multi_m, + pytest_attached_m, + dot_tour, + double_slash_game, + pytest_dot_self, + pytest_double_slash_self, + pytest_mixed_case_self, + ): + _, cls = classify_console_block(blocked) + assert cls[0].kind is ConsoleKind.UNCLASSIFIED, blocked.body + with pytest.raises(CodeBlockError, match="Unclassified console block"): + run_console_codeblock(blocked, _REPO_ROOT) + + # Validate bench_compare against tmp_path so unpacked sdists do not skip. + bench_root = tmp_path / "bench_repo" + (bench_root / "scripts").mkdir(parents=True) + (bench_root / "scripts" / "benchmark.py").write_text("x = 1\n", encoding="utf-8") + _, cmp_cls = classify_console_block(bench_compare) + assert cmp_cls[0].kind is ConsoleKind.NON_RUNNABLE + assert cmp_cls[0].category == "heavy-git-worktree-benchmark" + run_console_codeblock(bench_compare, bench_root) + + _, unk_cls = classify_console_block(bench_unknown) + assert unk_cls[0].kind is ConsoleKind.UNCLASSIFIED + + with pytest.raises(CodeBlockError, match="Console output mismatch"): + run_console_codeblock(pytest_wrong_out, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="Console output mismatch"): + run_console_codeblock(replay_wrong_out, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="must be relative"): + run_console_codeblock(record_abs, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="escapes temporary root"): + run_console_codeblock(record_eq_escape, _REPO_ROOT) + + with pytest.raises(CodeBlockError, match="requires an output path"): + run_console_codeblock(record_missing_val, _REPO_ROOT) + + _, game_case_cls = classify_console_block(mixed_case_game) + assert game_case_cls[0].kind is ConsoleKind.NON_RUNNABLE + assert game_case_cls[0].category == "interactive-tui" + + +def test_sandbox_isolation_and_sdist_layout_compatibility( + tmp_path: pathlib.Path, +) -> None: + """In-process ``tempfile.tempdir`` is sandboxed, escapes fail, and sdist skips.""" + sandbox = tmp_path / "sb" + sandbox.mkdir() + with _isolated_process_env(sandbox): + resolved_tmp = pathlib.Path(tempfile.gettempdir()).resolve() + assert resolved_tmp.is_relative_to(sandbox.resolve()) + + with pytest.raises(CodeBlockError, match="must be relative"): + _safe_sandbox_path(sandbox, "/tmp/escape", "test:1") + with pytest.raises(CodeBlockError, match="must be relative"): + _safe_sandbox_path(sandbox, r"C:\escape", "test:1") + with pytest.raises(CodeBlockError, match="escapes temporary root"): + _safe_sandbox_path(sandbox, "../escape", "test:1") + with pytest.raises(CodeBlockError, match="escapes temporary root"): + _safe_sandbox_path(sandbox, ".", "test:1") + with pytest.raises(CodeBlockError, match="escapes temporary root"): + _safe_sandbox_path(sandbox, "", "test:1") + + assert _wants_json_format(["--format", "text", "--format", "json"]) + assert not _wants_json_format(["--format=json", "--format=text"]) + + assert _requires_syrupy(ast.parse("import libvt.contrib.syrupy")) + assert _requires_syrupy(ast.parse("from libvt.contrib.syrupy import x")) + assert _requires_syrupy(ast.parse("from libvt.contrib import syrupy")) + + # Simulate an unpacked sdist (docs/ + pyproject.toml, no scripts/justfile/.git). + sdist_root = tmp_path / "sdist" + (sdist_root / "docs" / "project").mkdir(parents=True) + (sdist_root / "pyproject.toml").write_text( + (_REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8"), + encoding="utf-8", + ) + bench_doc = sdist_root / "docs" / "project" / "benchmark.md" + bench_doc.write_text( + (_REPO_ROOT / "docs" / "project" / "benchmark.md").read_text(encoding="utf-8"), + encoding="utf-8", + ) + for block in parse_markdown_blocks(bench_doc, sdist_root): + if block.language == "console": + with pytest.raises(pytest.skip.Exception): + run_console_codeblock(block, sdist_root) + + +def test_literalinclude_check_passes_and_rejects_broken_markers( + tmp_path: pathlib.Path, +) -> None: + """``{literalinclude}`` checks target files, slice markers, and Python syntax.""" + target = tmp_path / "examples" / "demo.py" + target.parent.mkdir(parents=True) + target.write_text("# start\nx = 1\n# end\n", encoding="utf-8") + + bad_syntax = tmp_path / "examples" / "syntax_err.py" + bad_syntax.write_text("def broken(:\n", encoding="utf-8") + + doc = tmp_path / "docs" / "guide.md" + doc.parent.mkdir(parents=True) + doc.write_text( + ( + "```{literalinclude} ../examples/demo.py\n" + ":language: python\n" + ":start-at: # start\n" + ":end-before: # end\n" + "```\n" + "\n" + "```{literalinclude} ../examples/missing.py\n" + ":language: python\n" + "```\n" + "\n" + "```{literalinclude} ../examples/demo.py\n" + ":language: python\n" + ":start-at: # nonexistent\n" + "```\n" + "\n" + "```{literalinclude} ../examples/demo.py\n" + ":language: python\n" + ":start-at: # end\n" + ":end-before: # end\n" + "```\n" + "\n" + "```{literalinclude} ../examples/syntax_err.py\n" + ":language: python\n" + "```\n" + ), + encoding="utf-8", + ) + good, missing, bad_start, empty_slice, syntax_fail = parse_markdown_blocks( + doc, + tmp_path, + ) + + run_literalinclude_check(good, tmp_path) + + with pytest.raises(CodeBlockError, match="target not found"): + run_literalinclude_check(missing, tmp_path) + + with pytest.raises(CodeBlockError, match=":start-at:"): + run_literalinclude_check(bad_start, tmp_path) + + with pytest.raises(CodeBlockError, match="slice is empty"): + run_literalinclude_check(empty_slice, tmp_path) + + with pytest.raises(SyntaxError): + run_literalinclude_check(syntax_fail, tmp_path) + + +def test_migration_python_blocks_are_explicitly_classified( + tmp_path: pathlib.Path, +) -> None: + """Every ``python`` fence in ``MIGRATION`` is a historical Before/After block.""" + classified = classify_migration_blocks(_REPO_ROOT) + assert len(classified) >= 1 + assert all(kind == "historical-migration-diff" for _, kind in classified) + + bad_root = tmp_path / "repo" + bad_root.mkdir() + (bad_root / "MIGRATION").write_text( + "# Migration\n\n```python\nimport libvt\n```\n", + encoding="utf-8", + ) + with pytest.raises(CodeBlockError, match="Unclassified python block in MIGRATION"): + classify_migration_blocks(bad_root) + + +def test_pytest_collects_and_runs_readme_and_docs_codeblocks_end_to_end( + tmp_path: pathlib.Path, +) -> None: + """Pytest runs doctests, plain Python, and console blocks together cleanly.""" + mini = tmp_path / "mini" + (mini / "docs").mkdir(parents=True) + (mini / "tests").mkdir(parents=True) + (mini / "tests" / "__init__.py").write_text("", encoding="utf-8") + (mini / "tests" / "_docs_codeblocks.py").write_text( + (_REPO_ROOT / "tests" / "_docs_codeblocks.py").read_text(encoding="utf-8"), + encoding="utf-8", + ) + (mini / "conftest.py").write_text( + (_REPO_ROOT / "conftest.py").read_text(encoding="utf-8"), + encoding="utf-8", + ) + (mini / "pyproject.toml").write_text( + ( + "[tool.pytest.ini_options]\n" + 'addopts = ["--tb=short", "--no-header", "--strict-markers", ' + '"--doctest-docutils-modules", "-p no:doctest"]\n' + 'asyncio_mode = "auto"\n' + 'asyncio_default_fixture_loop_scope = "function"\n' + 'markers = ["documentation: executable Markdown code-block checks"]\n' + 'testpaths = ["README.md", "docs"]\n' + ), + encoding="utf-8", + ) + + readme = mini / "README.md" + guide = mini / "docs" / "guide.md" + good_readme = ( + "# Mini\n\n" + "```python\n" + "import libvt\n" + "assert libvt.render(b'ready') == 'ready'\n" + "```\n\n" + "```python\n" + ">>> import libvt\n" + ">>> libvt.strip(b'\\x1b[32mok\\x1b[0m')\n" + "'ok'\n" + "```\n\n" + "```console\n" + "$ printf '\\x1b[32mok\\x1b[0m' | python -m libvt strip\n" + "ok\n" + "```\n" + ) + good_guide = ( + "# Guide\n\n" + "```python\n" + "import libvt\n" + "term = libvt.Terminal(rows=1, cols=6)\n" + "term.feed(b'hi')\n" + "assert term.committed.lines == ('hi',)\n" + "```\n\n" + "```console\n" + "$ printf '10%%\\r\\x1b[2K20%%' | python -m libvt render --rows 1 --cols 10\n" + "20%\n" + "```\n" + ) + readme.write_text(good_readme, encoding="utf-8") + guide.write_text(good_guide, encoding="utf-8") + + def _run_pytest(*extra_args: str) -> subprocess.CompletedProcess[str]: + child_env = dict(os.environ) + child_env["PYTHONUTF8"] = "1" + child_env["PYTHONIOENCODING"] = "utf-8" + child_env.pop("LIBVT_DOCS_CODEBLOCK_ACTIVE", None) + return subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-v", + *extra_args, + f"--basetemp={tmp_path / 'bt'}", + "-o", + f"cache_dir={tmp_path / 'cache'}", + ], + cwd=mini, + env=child_env, + capture_output=True, + encoding="utf-8", + errors="replace", + timeout=60, + check=False, + ) + + passed_all = _run_pytest() + assert passed_all.returncode == 0, passed_all.stdout + passed_all.stderr + assert "README.md::python[L3] PASSED" in passed_all.stdout + assert "README.md::console[L14] PASSED" in passed_all.stdout + assert "README.md[0] PASSED" in passed_all.stdout + assert "docs/guide.md::python[L3] PASSED" in passed_all.stdout + assert "docs/guide.md::console[L10] PASSED" in passed_all.stdout + assert "5 passed" in passed_all.stdout + + # Broken plain python block in README.md must fail. + readme.write_text( + good_readme.replace("== 'ready'", "== 'nope'"), + encoding="utf-8", + ) + failed_readme = _run_pytest("-m", "documentation") + assert failed_readme.returncode == 1 + assert "README.md::python[L3] FAILED" in failed_readme.stdout + readme.write_text(good_readme, encoding="utf-8") + + # Missing explicit import in docs/guide.md must fail. + guide.write_text( + good_guide.replace("import libvt\n", ""), + encoding="utf-8", + ) + failed_docs_py = _run_pytest("-m", "documentation") + assert failed_docs_py.returncode == 1 + assert "docs/guide.md::python[L3] FAILED" in failed_docs_py.stdout + + # Unclassified console command in docs/guide.md must fail. + guide.write_text( + good_guide + "\n```console\n$ unknown-tool --flag\n```\n", + encoding="utf-8", + ) + failed_docs_console = _run_pytest("-m", "documentation") + assert failed_docs_console.returncode == 1 + assert "Unclassified console block" in failed_docs_console.stdout + + +def test_docs_codeblocks_harness_not_in_wheel_or_pytest11() -> None: + """Repo-local docs harness stays out of ``src/libvt``, ``pytest11``, and imports.""" + pyproject = tomllib.loads((_REPO_ROOT / "pyproject.toml").read_text("utf-8")) + assert pyproject["project"]["dependencies"] == [] + assert pyproject["tool"]["hatch"]["build"]["targets"]["wheel"]["packages"] == [ + "src/libvt" + ] + entry_points = pyproject["project"]["entry-points"]["pytest11"] + assert not any("docs_codeblocks" in val for val in entry_points.values()) + assert not (_REPO_ROOT / "src" / "libvt" / "_docs_codeblocks.py").exists() + + probe = subprocess.run( + [ + sys.executable, + "-c", + ( + "import sys, libvt, libvt.pytest_plugin; " + "assert 'tests._docs_codeblocks' not in sys.modules" + ), + ], + cwd=_REPO_ROOT, + capture_output=True, + encoding="utf-8", + errors="replace", + timeout=30, + check=False, + ) + assert probe.returncode == 0, probe.stdout + probe.stderr + + +def test_printf_octal_devnull_stdin_symlink_fire_and_runtime_recursion( + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify POSIX octal printf, DEVNULL stdin, symlinked fire fallback, and guard.""" + # POSIX printf format operands consume at most 3 octal digits (so \0337 is ESC 7). + assert _decode_printf_bytes(r"\0337", "test:1") == b"\x1b7" + assert _decode_printf_bytes(r"\0330", "test:1") == b"\x1b0" + assert _decode_printf_bytes(r"\0071", "test:1") == b"\x071" + assert _decode_printf_bytes(r"\033[31m", "test:1") == b"\x1b[31m" + assert _decode_printf_bytes(r"\7", "test:1") == b"\x07" + + # Non-piped subprocesses receive DEVNULL on stdin instead of inheriting parent TTY. + eof_res = _run_subprocess( + [sys.executable, "-c", "import sys; print(repr(sys.stdin.read()))"], + cwd=tmp_path, + env=dict(os.environ), + input_bytes=None, + timeout=10.0, + ) + assert eof_res.returncode == 0 + assert eof_res.stdout.strip() == "''" + + # Multi-flag `# doctest: +ELLIPSIS, +HIDE` still classifies as pure doctest. + assert _is_pure_doctest(">>> 1 + 1 # doctest: +ELLIPSIS, +HIDE\n2\n") + assert _is_pure_doctest(">>> 1 + 1 # doctest: +HIDE +NORMALIZE_WHITESPACE\n2\n") + + # No-rg FIRE evidence fallback resolves symlinked sandbox roots cleanly. + real_sb = tmp_path / "real_sb" + report = real_sb / "fire-evidence-01" / "case-a" / "fire.json" + report.parent.mkdir(parents=True) + report.write_text('{"ok": true}\n', encoding="utf-8") + link_sb = tmp_path / "link_sb" + try: + link_sb.symlink_to(real_sb, target_is_directory=True) + except OSError: + link_sb = real_sb + monkeypatch.setattr(shutil, "which", lambda _name: None) + fire_cmd = ConsoleCommand( + command="rg --files -g 'fire.json' fire-evidence-01", + expected_output=("fire-evidence-01/case-a/fire.json",), + ) + _run_fire_evidence_command( + fire_cmd, + ["rg", "--files", "-g", "fire.json", "fire-evidence-01"], + link_sb, + dict(os.environ), + "test:1", + ) + + # Runtime recursion env var blocks re-entrant python and console execution. + doc = tmp_path / "docs" / "rec.md" + doc.parent.mkdir(parents=True) + doc.write_text( + "```python\nimport libvt\n```\n\n```console\n$ pip install libvt\n```\n", + encoding="utf-8", + ) + py_block, console_block = parse_markdown_blocks(doc, tmp_path) + monkeypatch.setenv(_RECURSION_ENV_VAR, "1") + with pytest.raises(CodeBlockError, match="recursive documentation code-block"): + run_python_codeblock(py_block, _REPO_ROOT) + with pytest.raises(CodeBlockError, match="recursive documentation code-block"): + run_console_codeblock(console_block, _REPO_ROOT) + + +def test_plain_python_syrupy_vt_snapshot_verifies_ambr_and_determinism( + tmp_path: pathlib.Path, + request: pytest.FixtureRequest, +) -> None: + """``vt_snapshot`` blocks write ``.ambr`` files and match deterministically.""" + if importlib.util.find_spec("syrupy") is None or ( + not request.config.pluginmanager.hasplugin("syrupy") + ): + pytest.skip("requires active syrupy plugin") + + doc = tmp_path / "docs" / "syrupy_demo.md" + doc.parent.mkdir(parents=True) + doc.write_text( + ( + "```python\n" + "from libvt.terminal import Terminal\n" + "from libvt.testing import vt_screen\n" + "from syrupy.assertion import SnapshotAssertion\n" + "\n" + "def test_ok(\n" + " vt_terminal: Terminal,\n" + " vt_snapshot: SnapshotAssertion,\n" + ") -> None:\n" + " vt_terminal.feed_str('\\x1b[1;32mREADY\\x1b[0m pid=48210')\n" + " view = vt_screen(\n" + " vt_terminal, scrubbers=[(r'pid=\\d+', 'pid=')]\n" + " )\n" + " assert view == vt_snapshot\n" + "```\n" + "\n" + "```python\n" + "import pathlib\n" + "from libvt.terminal import Terminal\n" + "from libvt.testing import vt_screen\n" + "from syrupy.assertion import SnapshotAssertion\n" + "\n" + "def test_nondeterministic(\n" + " vt_terminal: Terminal,\n" + " vt_snapshot: SnapshotAssertion,\n" + ") -> None:\n" + " marker = pathlib.Path('run.txt')\n" + " count = int(marker.read_text()) + 1 if marker.exists() else 1\n" + " marker.write_text(str(count))\n" + " vt_terminal.feed_str(f'run={count}')\n" + " assert vt_screen(vt_terminal) == vt_snapshot\n" + "```\n" + "\n" + "```python\n" + "from syrupy.assertion import SnapshotAssertion\n" + "\n" + "def test_unused(vt_snapshot: SnapshotAssertion) -> None:\n" + " assert vt_snapshot is not None\n" + "```\n" + ), + encoding="utf-8", + ) + ok_blk, nondet_blk, unused_blk = parse_markdown_blocks(doc, tmp_path) + + run_python_codeblock(ok_blk, _REPO_ROOT, pytest_config=request.config) + with pytest.raises(CodeBlockError, match="Plain python pytest block failed"): + run_python_codeblock(nondet_blk, _REPO_ROOT, pytest_config=request.config) + with pytest.raises(CodeBlockError, match=r"wrote no \.ambr snapshot"): + run_python_codeblock(unused_blk, _REPO_ROOT, pytest_config=request.config) diff --git a/tests/test_libvt.py b/tests/test_libvt.py index 9b8573c..67c57c5 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -350,35 +350,41 @@ def test_cross_platform_classifiers_and_ci_workflows() -> None: assert '--paths "/*"' in docs_txt -def test_markdown_python_fences_carry_doctest_prompts() -> None: - """Every ``python`` fence in ``README.md`` and ``docs/`` executes as a doctest.""" +def test_markdown_code_fences_are_collected_and_classified() -> None: + """Every ``python`` and ``console`` fence in ``README.md`` and ``docs/`` runs.""" + from tests._docs_codeblocks import ( + PYTHON_LANGUAGES, + SHELL_LANGUAGES, + ConsoleKind, + classify_console_block, + is_checked_markdown, + parse_markdown_blocks, + ) + repo_root = pathlib.Path(__file__).resolve().parent.parent - md_files = [repo_root / "README.md", *sorted((repo_root / "docs").rglob("*.md"))] - unprompted: list[str] = [] + candidates = [ + repo_root / "README.md", + *sorted((repo_root / "docs").rglob("*.md")), + ] + md_files = [path for path in candidates if is_checked_markdown(path, repo_root)] + unclassified: list[str] = [] + python_blocks = 0 + console_blocks = 0 for path in md_files: - if "_build" in path.parts or path.name in ("AGENTS.md", "CLAUDE.md"): - continue - lines = path.read_text(encoding="utf-8").splitlines() - idx = 0 - while idx < len(lines): - match = re.match(r"^([`~]{3,})python\s*$", lines[idx]) - if match is None: - idx += 1 - continue - delim = match.group(1) - start_line = idx + 1 - idx += 1 - body: list[str] = [] - while idx < len(lines) and not re.match( - rf"^{re.escape(delim)}\s*$", lines[idx] - ): - body.append(lines[idx]) - idx += 1 - if not any(ln.lstrip().startswith(">>>") for ln in body): - rel = path.relative_to(repo_root).as_posix() - unprompted.append(f"{rel}:{start_line}") - idx += 1 - assert unprompted == [] + for block in parse_markdown_blocks(path, repo_root): + if block.language in PYTHON_LANGUAGES: + python_blocks += 1 + elif block.language in SHELL_LANGUAGES: + console_blocks += 1 + _, classifications = classify_console_block(block) + unclassified.extend( + f"{block.rel_path}:{block.start_line} ({item.reason})" + for item in classifications + if item.kind is ConsoleKind.UNCLASSIFIED + ) + assert python_blocks > 0 + assert console_blocks > 0 + assert unclassified == [] def test_documented_examples_include_explicit_imports( @@ -386,6 +392,11 @@ def test_documented_examples_include_explicit_imports( ) -> None: """Blocks in ``README.md``, ``quickstart``, and topic/API pages carry imports.""" from libvt.parser import Parser + from tests._docs_codeblocks import ( + PYTHON_LANGUAGES, + is_checked_markdown, + parse_markdown_blocks, + ) repo_root = pathlib.Path(__file__).resolve().parent.parent pages = ( @@ -401,14 +412,23 @@ def test_documented_examples_include_explicit_imports( "syrupy" ) is not None and request.config.pluginmanager.hasplugin("syrupy") flags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE - fence_re = re.compile(r"(?m)^([`~]{3,})python\s*\n(.*?)\n\1\s*$", re.DOTALL) for rel in pages: path = repo_root / rel assert path.is_file(), rel - text = path.read_text(encoding="utf-8") - for idx, match in enumerate(fence_re.finditer(text)): - code = re.sub(r"\s*#\s*doctest:\s*\+HIDE\b", "", match.group(2)) + blocks = [ + blk + for blk in parse_markdown_blocks(path, repo_root) + if blk.language in PYTHON_LANGUAGES + ] + assert blocks, f"expected at least one python block in {rel}" + for idx, block in enumerate(blocks): + if not block.has_doctest_prompts: + # Plain python blocks are collected and executed independently + # with zero implicit globals by MarkdownCodeBlocksFile. + assert is_checked_markdown(path, repo_root), rel + continue + code = re.sub(r"\s*#\s*doctest:\s*\+HIDE\b", "", block.body) if "syrupy" in code and not has_syrupy: continue globs: dict[str, object] = {}