torben/chemenu#249 in ADRs 0003–0025 zerlegt #35
@@ -0,0 +1,329 @@
|
||||
"""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
|
||||
|
||||
DECISIONS = Path(__file__).resolve().parents[2] / "docs" / "decisions"
|
||||
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]*`")
|
||||
|
||||
|
||||
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
|
||||
Reference in new issue
Block a user