Files
chemenu-ng/tests/docs/test_decisions.py
T
torbenandClaude Sonnet 5.5 820a24844b Replace the architecture stub with the overview and add link tests
architecture.md now carries the ADR table, both diagrams, scaling, risks
and the table of inputs from the legacy stack. Tests check contiguous ADR
numbers, that every ADR is linked, and that relative links resolve.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:39:33 +01:00

381 lines
12 KiB
Python

"""Format checks for the architecture decision records in docs/decisions."""
import datetime
import re
from pathlib import Path
from typing import cast
import pytest
import yaml
ROOT = Path(__file__).resolve().parents[2]
DECISIONS = ROOT / "docs" / "decisions"
ARCHITECTURE = ROOT / "docs" / "architecture.md"
REQUIRED_SECTIONS = (
"Kontext und Problemstellung",
"Betrachtete Optionen",
"Entscheidung",
)
SOURCE_REQUIRED = range(3, 26)
SOURCE_PREFIX = "Quelle: torben/chemenu#249 §"
STATUSES = ("proposed", "rejected", "accepted", "deprecated")
SUPERSEDED = re.compile(r"superseded by ADR-\d{4}")
OPEN_HEADING = "### Bewusst offen"
ISSUE_REF = re.compile(r"(?<![\w/])#\d+")
PLACEHOLDER = re.compile(r"\{[^{}\n]+\}")
FENCE = re.compile(r"\s*(`{3,}|~{3,})(.*)")
ADR_NAME = re.compile(r"\d{4}-[a-z0-9-]+\.md")
INLINE_CODE = re.compile(r"`[^`\n]*`")
MARKDOWN_LINK = re.compile(r"\[[^\]\n]*\]\(\s*<?([^)\s>]+)>?(?:\s+\"[^\"]*\")?\s*\)")
EXTERNAL_TARGET = re.compile(r"(https?:|mailto:|#)")
class _PlainLoader(yaml.SafeLoader):
"""Safe loader that leaves dates as strings, so invalid ones stay reportable."""
_PlainLoader.yaml_implicit_resolvers = {
key: [(tag, rx) for tag, rx in resolvers if tag != "tag:yaml.org,2002:timestamp"]
for key, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
}
def adr_files() -> list[Path]:
"""Return all ADR files (NNNN-*.md), sorted by name."""
return sorted(DECISIONS.glob("[0-9][0-9][0-9][0-9]-*.md"))
def _split_frontmatter(text: str) -> tuple[str | None, str]:
match = re.match(r"---\n(.*?)\n---\n?(.*)", text, re.DOTALL)
if match is None:
return None, text
return match.group(1), match.group(2)
def _prose_lines(body: str) -> list[str]:
"""Return the lines of body outside fenced code blocks."""
lines: list[str] = []
fence = ""
for line in body.splitlines():
match = FENCE.match(line)
if fence:
# Only a bare fence of the same kind and at least the same length closes.
if match and match[1].startswith(fence) and not match[2].strip():
fence = ""
elif match:
fence = match[1]
else:
lines.append(line)
return lines
def _frontmatter_problems(raw: str | None) -> list[str]:
if raw is None:
return ["missing frontmatter"]
try:
data: object = yaml.load(raw, Loader=_PlainLoader) # noqa: S506
except yaml.YAMLError:
return ["unparsable frontmatter"]
if not isinstance(data, dict):
return ["unparsable frontmatter"]
fields = cast("dict[str, object]", data)
problems: list[str] = []
status = fields.get("status")
if not isinstance(status, str) or not (status in STATUSES or SUPERSEDED.fullmatch(status)):
problems.append(f"invalid status: {status}")
date = fields.get("date")
try:
if not isinstance(date, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date):
raise ValueError(date)
datetime.date.fromisoformat(date)
except ValueError:
problems.append(f"invalid date: {date}")
return problems
def _section_problems(lines: list[str]) -> list[str]:
headings = [line[3:].strip() for line in lines if line.startswith("## ")]
problems = [f"missing section: ## {name}" for name in REQUIRED_SECTIONS if name not in headings]
if not problems:
positions = [headings.index(name) for name in REQUIRED_SECTIONS]
if positions != sorted(positions):
problems.append("sections out of order")
return problems
def _open_item_problems(lines: list[str]) -> list[str]:
items: list[str] = []
inside = found = in_item = False
for line in lines:
if re.match(r"#{1,3}\s", line):
inside = line.strip() == OPEN_HEADING
found = found or inside
in_item = False
elif not inside:
continue
elif re.match(r"\s*([*+-]|\d+\.)\s", line):
items.append(line.strip())
in_item = True
elif not line.strip():
in_item = False
elif items and (in_item or line[0].isspace()):
items[-1] += " " + line.strip()
in_item = True
if found and not items:
return ["open section without list items"]
return [
f"open item without issue reference: {item}"
for item in items
if ISSUE_REF.search(item) is None
]
def adr_problems(name: str, text: str) -> list[str]:
"""Return the format problems of an ADR; an empty list means valid."""
raw, body = _split_frontmatter(text)
problems = _frontmatter_problems(raw)
lines = _prose_lines(body)
problems += _section_problems(lines)
for line in lines:
for match in PLACEHOLDER.findall(INLINE_CODE.sub("", line)):
problems.append(f"placeholder left: {match}")
number = int(name[:4]) if re.match(r"\d{4}-", name) else None
if number in SOURCE_REQUIRED and not any(line.startswith(SOURCE_PREFIX) for line in lines):
problems.append(f"missing source line: {SOURCE_PREFIX}")
problems += _open_item_problems(lines)
return problems
VALID = """\
---
status: accepted
date: 2026-12-02
---
# Titel
## Kontext und Problemstellung
Quelle: torben/chemenu#249 § Leitprinzip
## Betrachtete Optionen
* A
## Entscheidung
Gewählte Option: „A“.
### Bewusst offen
* Notausgang: #31
"""
@pytest.mark.parametrize("path", adr_files(), ids=lambda p: p.name)
def test_adr_is_valid(path: Path) -> None:
assert adr_problems(path.name, path.read_text(encoding="utf-8")) == []
def test_adr_numbers_are_unique() -> None:
numbers = [path.name[:4] for path in adr_files()]
assert len(numbers) == len(set(numbers))
def test_every_decision_file_is_named_like_an_adr() -> None:
names = {path.name for path in DECISIONS.iterdir()} - {"adr-template.md"}
assert [name for name in sorted(names) if not ADR_NAME.fullmatch(name)] == []
def test_adr_files_found() -> None:
assert {"0001", "0002"} <= {path.name[:4] for path in adr_files()}
def test_valid_text_has_no_problems() -> None:
assert adr_problems("0003-x.md", VALID) == []
@pytest.mark.parametrize(
"status",
['"accepted"', "proposed", "rejected", "deprecated", '"superseded by ADR-0004"'],
)
def test_allowed_statuses(status: str) -> None:
text = VALID.replace("status: accepted", f"status: {status}")
assert adr_problems("0003-x.md", text) == []
def test_source_line_only_required_for_source_range() -> None:
text = VALID.replace("Quelle: torben/chemenu#249 § Leitprinzip\n", "")
assert adr_problems("0002-x.md", text) == []
assert adr_problems("0026-x.md", text) == []
def test_legacy_issue_reference_is_no_issue_reference() -> None:
text = VALID.replace("Notausgang: #31", "Notausgang: torben/chemenu#31")
assert adr_problems("0003-x.md", text) == [
"open item without issue reference: * Notausgang: torben/chemenu#31"
]
def test_placeholder_in_code_is_allowed() -> None:
text = VALID.replace("* A\n", "* A mit `{x}`\n\n```yaml\nops: {a: 1}\n```\n")
assert adr_problems("0003-x.md", text) == []
def test_nested_fences_hide_nothing() -> None:
block = "````\n```\n~~~\n````\n\n~~~\n```\n~~~\n"
text = VALID.replace("* A\n", f"* A\n\n{block}")
assert adr_problems("0003-x.md", text) == []
def test_wrapped_open_item_may_start_with_the_issue() -> None:
text = VALID.replace("* Notausgang: #31", "* Notausgang, siehe\n#31")
assert adr_problems("0003-x.md", text) == []
INVALID = [
pytest.param(
"0003-x.md",
VALID.split("---\n", 2)[2],
["missing frontmatter"],
id="no-frontmatter",
),
pytest.param(
"0003-x.md",
VALID.replace("status: accepted", "status: done"),
["invalid status: done"],
id="bad-status",
),
pytest.param(
"0003-x.md",
VALID.replace("status: accepted", "status: superseded by ADR-4"),
["invalid status: superseded by ADR-4"],
id="bad-superseded",
),
pytest.param(
"0003-x.md",
VALID.replace("date: 2026-12-02", "date: 2026-13-01"),
["invalid date: 2026-13-01"],
id="bad-date",
),
pytest.param(
"0003-x.md",
VALID.replace("## Betrachtete Optionen", "## Optionen"),
["missing section: ## Betrachtete Optionen"],
id="missing-section",
),
pytest.param(
"0003-x.md",
VALID.replace("## Betrachtete Optionen\n\n* A\n\n", "").replace(
"### Bewusst offen", "## Betrachtete Optionen\n\n### Bewusst offen"
),
["sections out of order"],
id="wrong-order",
),
pytest.param(
"0003-x.md",
VALID.replace("## Betrachtete Optionen\n\n* A\n", "```\n## Betrachtete Optionen\n```\n"),
["missing section: ## Betrachtete Optionen"],
id="heading-in-code-block",
),
pytest.param(
"0003-x.md",
VALID.replace("* A\n", "* {Titel von Option 1}\n"),
["placeholder left: {Titel von Option 1}"],
id="placeholder",
),
pytest.param(
"0003-x.md",
VALID.replace("Quelle: torben/chemenu#249 § Leitprinzip", "Quelle: Notiz"),
["missing source line: Quelle: torben/chemenu#249 §"],
id="missing-source",
),
pytest.param(
"0003-x.md",
VALID.replace("* Notausgang: #31", "* Notausgang\n* Zweiter: #32"),
["open item without issue reference: * Notausgang"],
id="open-item-without-issue",
),
pytest.param(
"0003-x.md",
VALID.replace("* Notausgang: #31", "+ Notausgang"),
["open item without issue reference: + Notausgang"],
id="open-item-plus-bullet",
),
pytest.param(
"0003-x.md",
VALID.replace("* Notausgang: #31", "* Notausgang\n\nSiehe #31"),
["open item without issue reference: * Notausgang"],
id="open-item-issue-in-other-paragraph",
),
pytest.param(
"0003-x.md",
VALID.replace("* Notausgang: #31", "#### Punkt\n\n* Notausgang"),
["open item without issue reference: * Notausgang"],
id="open-item-below-subheading",
),
pytest.param(
"0003-x.md",
VALID.replace("* Notausgang: #31", "Notausgang offen, #31"),
["open section without list items"],
id="open-section-without-items",
),
pytest.param(
"0003-x.md",
VALID.replace("status: accepted", "status: [accepted"),
["unparsable frontmatter"],
id="unparsable-frontmatter",
),
]
@pytest.mark.parametrize(("name", "text", "expected"), INVALID)
def test_invalid_adr_is_reported(name: str, text: str, expected: list[str]) -> None:
assert adr_problems(name, text) == expected
def broken_links(path: Path, text: str) -> list[str]:
"""Return relative Markdown link targets in text that do not exist next to path."""
broken: list[str] = []
for line in _prose_lines(text):
for target in MARKDOWN_LINK.findall(INLINE_CODE.sub("", line)):
if EXTERNAL_TARGET.match(target):
continue
file_part = target.split("#", 1)[0]
if not (path.parent / file_part).exists():
broken.append(target)
return broken
def markdown_files() -> list[Path]:
"""Return the Markdown files whose relative links are checked."""
files = sorted((ROOT / "docs").rglob("*.md"))
return [*files, ROOT / "README.md", ROOT / "CLAUDE.md"]
def test_adr_numbers_are_contiguous() -> None:
numbers = [int(path.name[:4]) for path in adr_files()]
assert numbers == list(range(1, len(numbers) + 1))
def test_architecture_links_every_adr() -> None:
text = ARCHITECTURE.read_text(encoding="utf-8")
targets = set(MARKDOWN_LINK.findall(text))
missing = [path.name for path in adr_files() if f"decisions/{path.name}" not in targets]
assert missing == []
@pytest.mark.parametrize("path", markdown_files(), ids=lambda p: str(p.relative_to(ROOT)))
def test_relative_links_resolve(path: Path) -> None:
assert broken_links(path, path.read_text(encoding="utf-8")) == []
def test_broken_link_is_reported(tmp_path: Path) -> None:
(tmp_path / "exists.md").write_text("x", encoding="utf-8")
text = (
"[ok](exists.md) [anchor](exists.md#abschnitt) [self](#oben) "
"[web](https://example.org/x.md) [mail](mailto:a@example.org) "
"`[code](missing-inline.md)` [gone](missing.md#a)\n"
"```\n[fenced](missing-fenced.md)\n```\n"
)
assert broken_links(tmp_path / "doc.md", text) == ["missing.md#a"]