test_glossary_terms.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Every term in the wiki Glossary is defined once (issue #409).
  3. The same term with two definitions can contradict itself, so the first column of the Glossary table must hold
  4. each term at most once, compared case-insensitively after HTML anchors and Markdown are stripped. The check
  5. collects loosely (every table row after the header) and asserts strictly (no repeat, and enough rows were seen).
  6. """
  7. import re
  8. from pathlib import Path
  9. from wikitext import glossary_pages, page_text
  10. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  11. HTML_TAG = re.compile(r"<[^>]*>")
  12. MD_LINK = re.compile(r"\[([^\]]*)\]\([^)]*\)")
  13. def clean_term(cell: str) -> str:
  14. """A first-column cell reduced to its comparable term: no anchors, links or emphasis, lower case."""
  15. text = HTML_TAG.sub("", cell)
  16. text = MD_LINK.sub(r"\1", text)
  17. text = re.sub(r"[*_`]", "", text)
  18. return " ".join(text.split()).lower()
  19. def first_column_terms(markdown: str) -> list[str]:
  20. """The cleaned first-column term of every body row of the first table in the text."""
  21. terms = []
  22. in_table = False
  23. for line in markdown.splitlines():
  24. if line.startswith("|"):
  25. cells = line.split("|")
  26. first = cells[1].strip() if len(cells) > 2 else ""
  27. if set(first) <= set("-: ") and first:
  28. in_table = True
  29. continue
  30. if in_table:
  31. terms.append(clean_term(first))
  32. elif in_table and terms:
  33. break
  34. return terms
  35. def repeated(terms: list[str]) -> list[str]:
  36. return sorted({t for t in terms if terms.count(t) > 1})
  37. def test_no_glossary_term_is_defined_twice():
  38. terms = [t for page in glossary_pages(WIKI) for t in first_column_terms(page_text(page))]
  39. assert len(terms) > 500, f"the guard collected too few rows: {len(terms)}"
  40. assert all(terms), "a row has an empty first cell"
  41. assert repeated(terms) == []
  42. def test_the_guard_bites_on_case_anchors_and_markdown():
  43. table = (
  44. "| Term | Meaning |\n|---|---|\n"
  45. "| **Patch** | one |\n"
  46. "| **patch** | two |\n"
  47. "| <a id=\"x\"></a>**[PATCH](A.md)** | three |\n"
  48. "| **`PHP-FPM`** | four |\n"
  49. "| **php-fpm** | five |\n"
  50. "| **Other** | six |\n"
  51. )
  52. assert first_column_terms(table) == ["patch", "patch", "patch", "php-fpm", "php-fpm", "other"]
  53. assert repeated(first_column_terms(table)) == ["patch", "php-fpm"]
  54. assert repeated(first_column_terms("| T | M |\n|---|---|\n| **A** | x |\n| **B** | y |\n")) == []