Files
mandy/tests/test_docs_repeated_lines.py
noosko21-a11y 41639e8997 tests/docs: read an indented code block as code, not prose
tests/semantic/README.md shows two commands in an indented code block (four spaces, no fence) whose first
forty characters are identical:

    python -I scripts/run_semantic_tests.py tests/semantic
    python -I scripts/run_semantic_tests.py tests/semantic -j 4 -p 'test_image_*.py'

repeated_lines() skips fenced blocks and said so in its own docstring ("neither a list item, table row, heading or
code"), but it only recognised the fenced kind, so the two command lines were compared as prose and the check went
red on main:

    AssertionError: Lists differ: ['tests/semantic/README.md:5 and :7'] != []

The same-merge habit is what this file exists to catch, so the report was worth a look, but a command block is not a
sentence kept twice and editing the README to dodge the check would leave the next indented block to trip it again.
An indented line is now skipped the way a fenced one already was: four spaces (Markdown's code block) or a tab.

Measured over every tracked Markdown file, old check against new, so this does not quietly buy green by hiding
duplicates:

    files scanned          104
    lines scanned          37,350
    lines indented 4+      1,375
    reported by both       0
    reported by old only   1   tests/semantic/README.md:5:7   (the false positive)
    reported by new only   0

The one report the fix removes is the one that was wrong. No real duplicate was lost.

The test gains the case directly: an indented two-command block is not reported, and a tab-indented one is not
either.

python -I tests/test_docs_repeated_lines.py -> Ran 3 tests, OK  (main: Ran 2, FAILED at tests/semantic/README.md:5)
2026-11-25 19:01:54 +07:00

92 lines
4.5 KiB
Python

"""No two neighbouring prose lines in the Markdown docs start the same way.
python -I tests/test_docs_repeated_lines.py
When two branches rewrite the same sentence and a merge keeps both sides, the page shows the sentence twice on
consecutive lines: the current text and the one it replaced, usually with a different number in it (docs/d3d12_vulkan.md
had "the one left needs `buffer_store_short`" twice, docs/animation.md gave both 350,251 and 382,781 for the same
export, docs/models.md said its test file runs 10 and 15 tests). A reader cannot tell which line is current.
`tests/test_docs_list_items.py` does this for list items and `tests/test_docs_table_rows.py` for table rows; this
flags two prose lines (neither a list item, table row, heading or code) within WINDOW lines of each other whose first
OPENING characters are equal. Reads tracked Markdown only; no game files.
"""
import os
import re
import subprocess
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
WINDOW = 3 # lines between the two (1 = neighbours)
OPENING = 40 # characters, after the indentation, that must match
INDENTED = 4 # spaces of indentation that make a Markdown code block, without a fence
LIST_ITEM = re.compile(r"^(?:[-*+]|\d+[.)])\s")
def repeated_lines(text):
"""[(line a, line b)] for prose lines within WINDOW lines whose first OPENING characters are equal."""
found, in_fence, seen = [], False, {}
for n, line in enumerate(text.split("\n"), 1):
if line.lstrip().startswith("```"):
in_fence = not in_fence
continue
if in_fence or len(line) - len(line.lstrip(" ")) >= INDENTED or line.startswith("\t"):
continue # a code block written by indentation, like the fenced one above: not prose
s = line.strip()
if len(s) < OPENING or s[0] in "|#>" or LIST_ITEM.match(s):
continue
key = s[:OPENING]
if key in seen and n - seen[key] <= WINDOW:
found.append((seen[key], n))
seen[key] = n
return found
def markdown_files():
try:
out = subprocess.run(["git", "ls-files", "*.md"], cwd=ROOT, capture_output=True, text=True, check=True).stdout
files = out.split()
except (OSError, subprocess.CalledProcessError):
files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/")
for r, d, fs in os.walk(ROOT) if ".git" not in r.split(os.sep) for f in fs if f.endswith(".md")]
return [f for f in files if not f.startswith("third_party/")]
class RepeatedLines(unittest.TestCase):
def test_checker_flags_neighbouring_repeats_only(self):
a = "The disassembly count is unchanged: the same 42 programs have no invalid word, and"
text = "\n".join([
a + " 10 do.", a + " ten do.", # 1-2: repeated neighbours
"x", "y", "z", "w",
a + " later.", # 7: four lines on, not flagged
"- " + a, "- " + a, # list items are tests/test_docs_list_items.py's
"| " + a, "| " + a, # table rows are tests/test_docs_table_rows.py's
"```", a, a, "```", # inside a code fence
"short", "short", # shorter than OPENING
])
self.assertEqual(repeated_lines(text), [(1, 2)])
def test_checker_ignores_indented_code_blocks(self):
cmd = "python -I scripts/run_semantic_tests.py tests/semantic"
text = "\n".join([
"Prose above the block.",
"",
" " + cmd,
" " + cmd + " -j 4 -p 'test_image_*.py'",
"",
"Prose after the block.",
])
self.assertEqual(repeated_lines(text), [], "an indented Markdown code block is not prose")
tabbed = "\n".join(["Prose.", "", "\t" + cmd, "\t" + cmd])
self.assertEqual(repeated_lines(tabbed), [], "a tab-indented code block is not prose either")
def test_docs_have_no_repeated_neighbouring_lines(self):
found = []
for path in markdown_files():
with open(os.path.join(ROOT, path), encoding="utf-8") as f:
found += [f"{path}:{a} and :{b}" for a, b in repeated_lines(f.read())]
self.assertEqual(found, [], "a line repeated just below itself (keep the current one): " + "; ".join(found))
if __name__ == "__main__":
unittest.main()