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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ what was asked for.
| `tests/` | Functional, property-fuzz, PTY, CLI, and fixture tests organized by module under test |
| `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs `0001`–`0010`) |
| `scripts/` | Unicode table generator (`generate_ucd.py`) and VT throughput benchmarks (`bench_vt.py`, `benchmark.py`) |
| `README.md` | Doctested quickstart — every `>>> ` block is a real test |
| `README.md` | Executable quickstart — plain `python` and runnable `console` blocks run via `tests/_docs_codeblocks.py` alongside doctests |
| `CHANGES` | The changelog, rendered as a docs page |
| `MIGRATION` | Deprecation and migration notes |
| `conftest.py` | Root fixtures, including `doctest_namespace` seeding |
| `conftest.py` | Root fixtures (`doctest_namespace` seeding) and `pytest_collect_file` hook for `tests/_docs_codeblocks.py` |

## Which policy applies

Expand Down
7 changes: 4 additions & 3 deletions tests/_docs_codeblocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ def _make_sandbox_env(sandbox_dir: pathlib.Path) -> dict[str, str]:
env[_RECURSION_ENV_VAR] = "1"
env.pop("COVERAGE_PROCESS_START", None)
env.pop("COV_CORE_SOURCE", None)
env.pop("PYTEST_ADDOPTS", None)
return env


Expand Down Expand Up @@ -1511,18 +1512,18 @@ def _run_fire_evidence_command(
)
raise CodeBlockError(msg)
normalized = "\n".join(
pathlib.Path(line).as_posix() for line in result.stdout.splitlines()
sorted(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"))
reports = list(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
sorted(p.relative_to(resolved_sandbox).as_posix() for p in reports)
)
_assert_expected_output(cmd.expected_output, actual, location, cmd.command)

Expand Down
158 changes: 158 additions & 0 deletions tests/test_docs_codeblocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
_decode_printf_bytes,
_is_pure_doctest,
_isolated_process_env,
_make_sandbox_env,
_requires_syrupy,
_run_fire_evidence_command,
_run_subprocess,
Expand Down Expand Up @@ -723,6 +724,7 @@ def test_migration_python_blocks_are_explicitly_classified(

def test_pytest_collects_and_runs_readme_and_docs_codeblocks_end_to_end(
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Pytest runs doctests, plain Python, and console blocks together cleanly."""
mini = tmp_path / "mini"
Expand Down Expand Up @@ -789,6 +791,7 @@ def _run_pytest(*extra_args: str) -> subprocess.CompletedProcess[str]:
child_env["PYTHONUTF8"] = "1"
child_env["PYTHONIOENCODING"] = "utf-8"
child_env.pop("LIBVT_DOCS_CODEBLOCK_ACTIVE", None)
child_env.pop("PYTEST_ADDOPTS", None)
return subprocess.run(
[
sys.executable,
Expand All @@ -809,6 +812,7 @@ def _run_pytest(*extra_args: str) -> subprocess.CompletedProcess[str]:
check=False,
)

monkeypatch.setenv("PYTEST_ADDOPTS", "-k unrelated_outer_filter")
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
Expand Down Expand Up @@ -1005,3 +1009,157 @@ def test_plain_python_syrupy_vt_snapshot_verifies_ambr_and_determinism(
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)


def test_python_pytest_runner_ignores_outer_pytest_addopts(
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Exported ``PYTEST_ADDOPTS`` does not leak into plain-Python pytest runs."""
monkeypatch.setenv("PYTEST_ADDOPTS", "-m documentation")

py_doc = tmp_path / "docs" / "py_addopts.md"
py_doc.parent.mkdir(parents=True)
py_doc.write_text(
(
"```python\n"
"def test_runs() -> None:\n"
" assert 1 + 1 == 2\n"
"```\n\n"
"```python\n"
"def test_fails() -> None:\n"
" assert 1 + 1 == 3\n"
"```\n"
),
encoding="utf-8",
)
py_ok, py_fail = parse_markdown_blocks(py_doc, tmp_path)
run_python_codeblock(py_ok, _REPO_ROOT)
with pytest.raises(CodeBlockError, match=r"exit 1"):
run_python_codeblock(py_fail, _REPO_ROOT)

sandbox_env = _make_sandbox_env(tmp_path / "sb")
assert "PYTEST_ADDOPTS" not in sandbox_env


def test_console_pytest_runner_ignores_outer_pytest_addopts(
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Exported ``PYTEST_ADDOPTS`` does not leak into console pytest commands."""
monkeypatch.setenv("PYTEST_ADDOPTS", "-m documentation")

mini_repo = tmp_path / "mini_repo"
(mini_repo / "tests").mkdir(parents=True)
(mini_repo / "pyproject.toml").write_text(
(
"[tool.pytest.ini_options]\n"
'asyncio_default_fixture_loop_scope = "function"\n'
'markers = ["documentation: executable Markdown code-block checks"]\n'
),
encoding="utf-8",
)
(mini_repo / "tests" / "test_ok.py").write_text(
"def test_ok() -> None:\n assert True\n",
encoding="utf-8",
)
(mini_repo / "tests" / "test_fail.py").write_text(
"def test_fail() -> None:\n assert False\n",
encoding="utf-8",
)
console_doc = mini_repo / "docs" / "console_addopts.md"
console_doc.parent.mkdir(parents=True)
console_doc.write_text(
(
"```console\n"
"$ uv run pytest tests/test_ok.py\n"
"```\n\n"
"```console\n"
"$ uv run pytest tests/test_fail.py\n"
"```\n"
),
encoding="utf-8",
)
con_ok, con_fail = parse_markdown_blocks(console_doc, mini_repo)
run_console_codeblock(con_ok, mini_repo)
with pytest.raises(CodeBlockError, match=r"exit 1"):
run_console_codeblock(con_fail, mini_repo)


def test_fire_evidence_sorts_rg_and_rglob_posix_paths_identically(
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Both ``rg`` and ``rglob`` FIRE evidence paths sort by POSIX path order."""
real_sb = tmp_path / "real_sb"
rel_paths = (
("fire-evidence-01", "a-b", "fire.json"),
("fire-evidence-01", "a", "b", "fire.json"),
("fire-evidence-01", "case-a", "fire.json"),
("fire-evidence-01", "case-b", "fire.json"),
)
for parts in rel_paths:
report = real_sb.joinpath(*parts)
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text('{"ok": true}\n', encoding="utf-8")

expected = (
"fire-evidence-01/a-b/fire.json",
"fire-evidence-01/a/b/fire.json",
"fire-evidence-01/case-a/fire.json",
"fire-evidence-01/case-b/fire.json",
)
cmd = ConsoleCommand(
command="rg --files --hidden --no-ignore --glob fire.json fire-evidence-01",
expected_output=expected,
)
bad_cmd = ConsoleCommand(
command=cmd.command,
expected_output=expected[:-1],
)

# Cross-platform stub rg emitting unsorted paths with native OS separators.
emit_script = (
"import os; "
"rows = ["
"os.path.join('fire-evidence-01', 'case-b', 'fire.json'), "
"os.path.join('fire-evidence-01', 'a', 'b', 'fire.json'), "
"os.path.join('fire-evidence-01', 'case-a', 'fire.json'), "
"os.path.join('fire-evidence-01', 'a-b', 'fire.json')"
"]; "
"print('\\n'.join(rows))"
)
stub_tokens = ["rg", "-c", emit_script]
monkeypatch.setattr(shutil, "which", lambda _name: sys.executable)
_run_fire_evidence_command(cmd, stub_tokens, real_sb, dict(os.environ), "test:1")
with pytest.raises(CodeBlockError, match="Console output mismatch"):
_run_fire_evidence_command(
bad_cmd, stub_tokens, real_sb, dict(os.environ), "test:1"
)

# Fallback branch without rg must match the exact same POSIX sort order.
fallback_tokens = [
"rg",
"--files",
"--hidden",
"--no-ignore",
"--glob",
"fire.json",
"fire-evidence-01",
]
monkeypatch.setattr(shutil, "which", lambda _name: None)
_run_fire_evidence_command(
cmd,
fallback_tokens,
real_sb,
dict(os.environ),
"test:1",
)
with pytest.raises(CodeBlockError, match="Console output mismatch"):
_run_fire_evidence_command(
bad_cmd,
fallback_tokens,
real_sb,
dict(os.environ),
"test:1",
)
Loading