diff --git a/tests/mdsections.py b/tests/mdsections.py new file mode 100644 index 000000000..893bd962e --- /dev/null +++ b/tests/mdsections.py @@ -0,0 +1,28 @@ +"""Sections of the markdown pages, for the tests that read them.""" + +from __future__ import annotations + +import re + +FENCED = re.compile(r"^```.*?^```", re.S | re.M) + + +def blank_fences(text: str) -> str: + """The text with each fenced block's characters turned to spaces, lines + kept: a shell comment in a fence is no heading.""" + return FENCED.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), text) + + +def section(text: str, heading: str, *, stop: int | None = None) -> str: + """The body under a heading, up to the next heading of level stop or + higher (the heading's own level by default). + + The heading is its text, or the full line with its hashes, which then + fix its level; a trailing ``{ #anchor }`` is optional either way.""" + hashes, title = re.fullmatch(r"(#*)\s*(.*)", heading).groups() + start = re.search(rf"(?m)^({hashes or '#+'}) {re.escape(title)}(?:\s*\{{[^}}]*\}})?\n", text) + if start is None: + raise AssertionError(f"no section {heading!r}") + rest = text[start.end():] + end = re.search(rf"(?m)^#{{1,{stop or len(start.group(1))}}} ", blank_fences(rest)) + return rest[: end.start()] if end else rest diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index 3fcee1dd5..ebcc7594d 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -8,9 +8,12 @@ code moves, and nothing else notices. from __future__ import annotations import tests +from tests import mdsections +from tests.mdsections import FENCED from tests.sources import script_source import ast +import functools import hashlib import inspect import io @@ -26,7 +29,6 @@ from tests.test_prose_style import _python_prose, _sentence_case ROOT = Path(__file__).resolve().parent.parent WIKI = ROOT / "wiki" -FENCED = re.compile(r"^```.*?^```", re.S | re.M) PUBLISHED = sorted(WIKI.glob("*.md")) + [ROOT / "README.md", ROOT / "CONTRIBUTING.md"] @@ -34,15 +36,8 @@ def _page(name: str) -> str: return (WIKI / name).read_text(encoding="utf-8") -def _section(text: str, heading: str) -> str: - """Body of a markdown section, up to the next heading of any level.""" - start = re.search(rf"(?m)^#+ {re.escape(heading)}\n", text) - if start is None: - raise AssertionError(f"no section {heading!r}") - rest = text[start.end():] - blanked = FENCED.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), rest) - end = re.search(r"(?m)^#+ ", blanked) - return rest[: end.start()] if end else rest +# A section runs to the next heading of any level. +_section = functools.partial(mdsections.section, stop=6) def _table_rows(text: str) -> list[list[str]]: diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 05410935b..3a1c4b0dc 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -10,6 +10,7 @@ tool prints, and a size is the one the release record holds. from __future__ import annotations import tests +from tests import mdsections from tests.sources import declared_options, script_source import contextlib @@ -62,15 +63,6 @@ def _read(relative: str) -> str: return (REPO_ROOT / relative).read_text(encoding="utf-8") -def _section(text: str, heading: str) -> str: - """The text under a markdown heading, up to the next heading of its level.""" - level = len(heading) - len(heading.lstrip("#")) - start = text.index(heading + "\n") - rest = text[start + len(heading) + 1:] - stop = re.search(rf"^#{{1,{level}}} ", rest, re.MULTILINE) - return rest[: stop.start()] if stop else rest - - def _which_pack() -> str: from sitegen import whichpack @@ -197,7 +189,7 @@ class DownloadLinksKeepTheirAddress(unittest.TestCase): from model.registry import list_registered_platforms, list_release_pack_platforms readme = _read("README.md") - table = _section(readme, "## Or download a ZIP") + table = mdsections.section(readme, "## Or download a ZIP") self.assertNotIn("/releases/download/", table) released = set(list_release_pack_platforms("platforms")) rows = [line for line in table.splitlines() if line.startswith("| ")] @@ -287,10 +279,15 @@ class EndUsersCheckTheirOwnFolder(unittest.TestCase): def test_user_sections_never_send_to_verify(self): for page, heading in self.USER_SECTIONS: with self.subTest(page=page, heading=heading): - section = _section(_read(page), heading) + section = mdsections.section(_read(page), heading) self.assertNotIn("verify.py", section) self.assertNotIn("python install.py --check", section) + def test_a_shell_comment_in_a_fence_does_not_end_the_section(self): + text = ("## 2. Fix the files\n\n```bash\n# from a checkout\n" + "python scripts/verify.py --all\n```\n\n## Next\n") + self.assertIn("verify.py", mdsections.section(text, "## 2. Fix the files")) + def test_the_download_page_gives_the_one_liner_check(self): page = _which_pack() self.assertNotIn("from a checkout", page) @@ -357,7 +354,7 @@ class ShownOutputIsPrintedOutput(unittest.TestCase): self.assertIn(literal, source) def test_samples_match_a_shape(self): - section = _section(_read("wiki/reading-reports.md"), "### Reading the output") + section = mdsections.section(_read("wiki/reading-reports.md"), "### Reading the output") blocks = re.findall(r"```\n(.*?)```", section, re.DOTALL) self.assertTrue(blocks) for block in blocks: @@ -401,7 +398,7 @@ class ContributorChecksMatchCi(unittest.TestCase): contributing_text(lambda page: page, "# C", "here"), _read("CONTRIBUTING.md"), ): - block = _section(text, "## Before opening a PR") + block = mdsections.section(text, "## Before opening a PR") self.assertIn("python scripts/refresh_data_dirs.py", block) self.assertLess( block.index("refresh_data_dirs.py"), block.index("run_tests.py") @@ -426,7 +423,7 @@ class ContributorChecksMatchCi(unittest.TestCase): contributing_text(lambda page: page, "# C", "here"), _read("CONTRIBUTING.md"), ): - block = _section(text, "## Before opening a PR") + block = mdsections.section(text, "## Before opening a PR") self.assertIn("python scripts/generate_site.py", block) self.assertLess( block.index("generate_site.py"), block.index("run_tests.py") @@ -634,7 +631,7 @@ class ContributorChecksFetchThePlatformsFiles(unittest.TestCase): contributing_text(lambda page: page, "# C", "here"), _read("CONTRIBUTING.md"), ): - block = _section(text, "## Before opening a PR") + block = mdsections.section(text, "## Before opening a PR") self.assertIn("python scripts/export_native.py --all --refresh-cache", block) self.assertLess( block.index("export_native.py"), block.index("run_tests.py") diff --git a/tests/test_site_integration.py b/tests/test_site_integration.py index a779912f1..107197013 100644 --- a/tests/test_site_integration.py +++ b/tests/test_site_integration.py @@ -10,6 +10,7 @@ Node's compile cache into /tmp. from __future__ import annotations import tests +from tests import mdsections import glob import json @@ -213,7 +214,7 @@ class FaqInstallsFromWhatYouHold(unittest.TestCase): self.faq = (REPO_ROOT / "wiki" / "faq.md").read_text(encoding="utf-8") def _section(self, heading: str) -> str: - return self.faq.split(f"## {heading}\n", 1)[1].split("\n## ", 1)[0] + return mdsections.section(self.faq, heading, stop=2) def test_no_unzip_before_from_pack(self): section = " ".join(self._section("No internet on the device?").split()) diff --git a/tests/test_site_wiki.py b/tests/test_site_wiki.py index 2689871b5..e816d7fa1 100644 --- a/tests/test_site_wiki.py +++ b/tests/test_site_wiki.py @@ -32,9 +32,12 @@ setup guides or the generator that writes the page a link opens. from __future__ import annotations import tests +from tests import mdsections +from tests.mdsections import FENCED from tests.sources import script_source import fnmatch +import functools import json import re import unittest @@ -52,7 +55,6 @@ REPO_ROOT = Path(__file__).resolve().parents[1] WIKI = REPO_ROOT / "wiki" -FENCED = re.compile(r"^```.*?^```", re.S | re.M) def _front(text: str) -> dict: @@ -65,13 +67,9 @@ def _h1(text: str) -> str: return match.group(1) if match else "" -def _section(text: str, heading: str) -> str: - start = re.search(rf"(?m)^#+ {re.escape(heading)}(?:\s*\{{[^}}]*\}})?\n", text) - if start is None: - raise AssertionError(f"no section {heading!r}") - rest = text[start.end():] - end = re.search(r"(?m)^#{1,2} ", FENCED.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), rest)) - return rest[: end.start()] if end else rest +# A section runs to the next heading of level 1 or 2, its subsections +# included. +_section = functools.partial(mdsections.section, stop=2) def _wiki(name: str) -> str: