test_wiki_accessibility.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. """Mechanical accessibility checks for the wiki pages in docs/wiki/.
  2. Issue #130 asks for an accessibility pass over the whole wiki. The parts a
  3. machine can hold are held here so the pass does not decay:
  4. - every image has alt text that describes it (not a filename, not a stock word)
  5. and is short enough to be read aloud (long detail belongs in the text beside
  6. the image or in the Mermaid source block);
  7. - no link says only "here" or similar, and no link has empty text or an empty target;
  8. - heading levels never skip (an H2 is followed by an H2 or H3, never an H4);
  9. - every table has a header row with a name in every cell.
  10. The judgment parts (color used as the only signal, jargon expanded on first
  11. use or linked to the Glossary, emoji used as the only meaning) stay a manual
  12. review at each wiki pull request; a regular expression cannot decide them.
  13. Each rule is a function, and the tests also feed it bad text to prove it bites.
  14. """
  15. import re
  16. from pathlib import Path
  17. import pytest
  18. WIKI = Path(__file__).resolve().parent.parent / "docs" / "wiki"
  19. MAX_ALT = 150
  20. FENCE = re.compile(r"^[ ]*(```|~~~).*?^[ ]*\1[^\n]*$", re.MULTILINE | re.DOTALL)
  21. INLINE_CODE = re.compile(r"`[^`\n]*`")
  22. IMAGE = re.compile(r"!\[([^\]\n]*)\]\(([^)\n]*)\)")
  23. # A link is [text](target) not preceded by "!"; text may not contain "]".
  24. LINK = re.compile(r"(?<!!)\[([^\]\n]*)\]\(([^)\n]*)\)")
  25. HEADING = re.compile(r"^(#{1,6})[ \t]+(\S.*?)[ \t]*#*[ \t]*$")
  26. FILENAME_ALT = re.compile(r"^[\w./-]+\.(png|jpe?g|gif|svg|webp)$", re.IGNORECASE)
  27. SLUG_ALT = re.compile(r"^[a-z0-9]+(?:[-_][a-z0-9]+)+$")
  28. STOCK_ALT = {"image", "img", "picture", "photo", "screenshot", "diagram", "figure", "graphic", "icon", "alt", "alt text"}
  29. VAGUE_LINK = {
  30. "here", "click here", "click", "link", "this link", "this page", "this", "read more", "more",
  31. "this document", "this doc", "see here", "go here", "over here", "there",
  32. }
  33. def strip_code(text: str) -> str:
  34. """Page text with fenced blocks removed and each inline code span masked as the word "code".
  35. Masking (not deleting) keeps a link or a table cell that holds only code
  36. from looking empty, and keeps examples such as `![](x.png)` from being counted."""
  37. return INLINE_CODE.sub("code", FENCE.sub("", text))
  38. def alt_problems(page: str, text: str) -> list[str]:
  39. problems = []
  40. for m in IMAGE.finditer(strip_code(text)):
  41. alt = m.group(1).strip()
  42. if not alt:
  43. problems.append(f"{page}: image {m.group(2)!r} has no alt text")
  44. elif FILENAME_ALT.match(alt) or SLUG_ALT.match(alt):
  45. problems.append(f"{page}: alt text {alt!r} is a filename")
  46. elif alt.lower().rstrip(".") in STOCK_ALT:
  47. problems.append(f"{page}: alt text {alt!r} says nothing about the picture")
  48. elif len(alt) > MAX_ALT:
  49. problems.append(f"{page}: alt text is {len(alt)} characters, over {MAX_ALT}: {alt[:50]!r}...")
  50. return problems
  51. def link_problems(page: str, text: str) -> list[str]:
  52. problems = []
  53. for m in LINK.finditer(strip_code(text)):
  54. label, target = m.group(1).strip(), m.group(2).strip()
  55. if not label:
  56. problems.append(f"{page}: link to {target!r} has empty text")
  57. elif label.lower().strip(" .:,;") in VAGUE_LINK:
  58. problems.append(f"{page}: link text {label!r} is not descriptive")
  59. if not target:
  60. problems.append(f"{page}: link {label!r} has an empty target")
  61. return problems
  62. def heading_problems(page: str, text: str) -> list[str]:
  63. problems = []
  64. previous = 0
  65. for line in strip_code(text).splitlines():
  66. m = HEADING.match(line)
  67. if not m:
  68. continue
  69. level = len(m.group(1))
  70. if previous == 0 and level > 1:
  71. problems.append(f"{page}: first heading is H{level}, expected H1: {m.group(2)!r}")
  72. elif previous and level > previous + 1:
  73. problems.append(f"{page}: H{previous} is followed by H{level}: {m.group(2)!r}")
  74. previous = level
  75. return problems
  76. def split_row(line: str) -> list[str]:
  77. """Cells of one table row, ignoring the outer pipes and any escaped pipe."""
  78. body = line.strip().replace("\\|", "\0")
  79. body = body.removeprefix("|").removesuffix("|")
  80. return [c.strip().replace("\0", "|") for c in body.split("|")]
  81. def table_problems(page: str, text: str) -> list[str]:
  82. problems = []
  83. lines = strip_code(text).splitlines()
  84. separator = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$")
  85. for i, line in enumerate(lines):
  86. if not separator.match(line) or "|" not in line:
  87. continue
  88. header = lines[i - 1] if i else ""
  89. cells = split_row(header)
  90. if "|" not in header or not all(cells):
  91. problems.append(f"{page}: table header {header.strip()[:60]!r} has no header row or an unnamed column")
  92. elif len(cells) != len(split_row(line)):
  93. problems.append(
  94. f"{page}: table header {header.strip()[:60]!r} has {len(cells)} columns "
  95. f"but its separator row has {len(split_row(line))}"
  96. )
  97. return problems
  98. def all_problems(page: str, text: str) -> list[str]:
  99. return alt_problems(page, text) + link_problems(page, text) + heading_problems(page, text) + table_problems(page, text)
  100. def pages() -> list[Path]:
  101. return sorted(WIKI.glob("*.md"))
  102. # -- the real tree ---------------------------------------------------------
  103. def test_pages_were_collected():
  104. assert len(pages()) >= 40
  105. @pytest.mark.parametrize(
  106. "check", [alt_problems, link_problems, heading_problems, table_problems], ids=lambda f: f.__name__
  107. )
  108. def test_every_page_passes(check):
  109. problems = []
  110. for page in pages():
  111. problems += check(page.name, page.read_text())
  112. assert not problems, "\n".join(problems)
  113. def test_the_checks_see_something_to_check():
  114. text = "".join(p.read_text() for p in pages())
  115. assert len(IMAGE.findall(strip_code(text))) >= 10
  116. assert len(LINK.findall(strip_code(text))) >= 100
  117. assert sum(1 for line in strip_code(text).splitlines() if HEADING.match(line)) >= 100
  118. # -- the checks bite -------------------------------------------------------
  119. @pytest.mark.parametrize(
  120. "text",
  121. [
  122. "![](images/a.png)",
  123. "![ ](images/a.png)",
  124. "![diagram](images/a.png)",
  125. "![Screenshot.](images/a.png)",
  126. "![a-diagram-name.png](images/a.png)",
  127. "![architecture-overview](images/a.png)",
  128. "![" + "x" * (MAX_ALT + 1) + "](images/a.png)",
  129. ],
  130. )
  131. def test_bad_alt_text_is_caught(text):
  132. assert alt_problems("x.md", text)
  133. def test_good_alt_text_passes_and_code_examples_are_ignored():
  134. assert not alt_problems("x.md", "![The firing alert in the lab's Prometheus](images/a.png)")
  135. assert not alt_problems("x.md", "```\n![](images/a.png)\n```\nand `![](b.png)`")
  136. @pytest.mark.parametrize(
  137. "text",
  138. ["[here](a.md)", "See [Click here](a.md).", "[ ](a.md)", "[](a.md)", "[link](a.md)", "[Here.](a.md)", "[text]()"],
  139. )
  140. def test_bad_links_are_caught(text):
  141. assert link_problems("x.md", text)
  142. def test_good_links_pass_and_images_are_not_links():
  143. assert not link_problems("x.md", "Read the [Glossary](Glossary.md) and ![A real description of it](images/a.png).")
  144. assert not link_problems("x.md", "```\n[here](a.md)\n```")
  145. def test_skipped_heading_levels_are_caught():
  146. assert heading_problems("x.md", "# A\n\n#### D\n")
  147. assert heading_problems("x.md", "## starts at two\n")
  148. assert not heading_problems("x.md", "# A\n## B\n### C\n## D\n# E\n")
  149. assert not heading_problems("x.md", "# A\n```\n#### not a heading\n```\n## B\n")
  150. def test_tables_without_a_named_header_are_caught():
  151. assert table_problems("x.md", "| | |\n|---|---|\n| a | b |\n")
  152. assert table_problems("x.md", "| Name | |\n|---|---|\n| a | b |\n")
  153. assert table_problems("x.md", "just text\n|---|---|\n| a | b |\n")
  154. assert not table_problems("x.md", "| Name | Why |\n|---|---|\n| a | |\n")
  155. def test_header_and_separator_must_have_the_same_number_of_columns():
  156. assert table_problems("x.md", "| Name | Why |\n|---|---|---|\n| a | b |\n")
  157. assert table_problems("x.md", "| Name | Why | Extra |\n|---|---|\n| a | b | c |\n")
  158. assert not table_problems("x.md", "| Name | Why |\n|:---|---:|\n| a | b |\n")
  159. assert not table_problems("x.md", "Name | Why\n---|---\n a | b\n")