A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

179 rivejä
6.4 KiB

  1. # Copyright (C) 2012-2025 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. from __future__ import annotations
  21. import os
  22. import subprocess
  23. import sys
  24. import textwrap
  25. from collections.abc import Generator
  26. from dataclasses import dataclass
  27. import pytest
  28. from mwparserfromhell.parser import contexts, tokens
  29. from mwparserfromhell.parser.builder import Builder
  30. from mwparserfromhell.parser.tokenizer import Tokenizer as PyTokenizer
  31. try:
  32. from mwparserfromhell.parser._tokenizer import CTokenizer
  33. except ImportError:
  34. CTokenizer = None
  35. class _TestParseError(Exception):
  36. """Raised internally when a test could not be parsed."""
  37. @dataclass
  38. class _TestCase:
  39. name: str
  40. label: str | None
  41. input: str
  42. output: list[tokens.Token]
  43. def _load_tests(file_path, filename, text) -> Generator[_TestCase]:
  44. tests = text.split("\n---\n")
  45. for test in tests:
  46. name = None
  47. label = None
  48. input = None
  49. output = None
  50. for line in test.strip().splitlines():
  51. if line.startswith("name:"):
  52. name = line[len("name:") :].strip()
  53. elif line.startswith("label:"):
  54. label = line[len("label:") :].strip()
  55. elif line.startswith("input:"):
  56. raw = line[len("input:") :].strip()
  57. if raw[0] == '"' and raw[-1] == '"':
  58. raw = raw[1:-1]
  59. raw = raw.encode("raw_unicode_escape")
  60. input = raw.decode("unicode_escape")
  61. elif line.startswith("output:"):
  62. raw = line[len("output:") :].strip()
  63. try:
  64. output = eval(raw, dict(vars(tokens)))
  65. except Exception as err:
  66. raise _TestParseError(
  67. f"Could not parse a test in {file_path!r}:\n\t{err}\n\n"
  68. f"Raw test:\n{test}"
  69. )
  70. if not name:
  71. raise _TestParseError(
  72. f"Test in {filename!r} lacks a name\nRaw test:\n{test}"
  73. )
  74. continue
  75. if input is None or output is None:
  76. raise _TestParseError(
  77. f"Test {name!r} in {file_path!r} lacks an input or an output"
  78. )
  79. continue
  80. if not isinstance(output, list) or not all(
  81. isinstance(tok, tokens.Token) for tok in output
  82. ):
  83. raise _TestParseError(
  84. f"Test {name!r} in {file_path!r} should have a list of tokens as its output"
  85. )
  86. yield _TestCase(
  87. name=f"{filename}:{name}",
  88. label=label,
  89. input=input,
  90. output=output,
  91. )
  92. def build():
  93. """Load and install all tests from the 'tokenizer' directory."""
  94. directory = os.path.join(os.path.dirname(__file__), "tokenizer")
  95. extension = ".mwtest"
  96. for filename in os.listdir(directory):
  97. if not filename.endswith(extension):
  98. continue
  99. fullname = os.path.join(directory, filename)
  100. with open(fullname, encoding="utf8") as fp:
  101. text = fp.read()
  102. name = os.path.split(fullname)[1][: -len(extension)]
  103. yield from _load_tests(fullname, name, text)
  104. @pytest.mark.parametrize(
  105. "tokenizer",
  106. filter(None, (CTokenizer, PyTokenizer)),
  107. ids=lambda t: "CTokenizer" if t.USES_C else "PyTokenizer",
  108. )
  109. @pytest.mark.parametrize("test_case", build(), ids=lambda test_case: test_case.name)
  110. def test_tokenizer(tokenizer, test_case: _TestCase):
  111. actual = tokenizer().tokenize(test_case.input)
  112. assert test_case.output == actual
  113. @pytest.mark.parametrize("test_case", build(), ids=lambda test_case: test_case.name)
  114. def test_roundtrip(test_case: _TestCase):
  115. actual = str(Builder().build(test_case.output[:]))
  116. assert test_case.input == actual
  117. @pytest.mark.skipif(CTokenizer is None, reason="CTokenizer not available")
  118. def test_c_tokenizer_uses_c():
  119. """make sure the C tokenizer identifies as using a C extension"""
  120. assert CTokenizer is not None
  121. assert CTokenizer.USES_C is True
  122. assert CTokenizer().USES_C is True
  123. def test_describe_context():
  124. assert "" == contexts.describe(0)
  125. ctx = contexts.describe(contexts.TEMPLATE_PARAM_KEY | contexts.HAS_TEXT)
  126. assert "TEMPLATE_PARAM_KEY|HAS_TEXT" == ctx
  127. @pytest.mark.skipif(CTokenizer is None, reason="CTokenizer not available")
  128. def test_entity_does_not_corrupt_heap():
  129. """Regression test: the C tokenizer must not mix raw libc calloc with
  130. PyObject_Free when handling an ampersand that is not a valid entity.
  131. Run in a subprocess with PYTHONMALLOC=debug so any allocator mismatch on
  132. the entity-parsing path is reported as a fatal error rather than silent
  133. heap corruption.
  134. """
  135. program = textwrap.dedent(
  136. """
  137. import mwparserfromhell
  138. from mwparserfromhell.parser._tokenizer import CTokenizer
  139. assert isinstance(mwparserfromhell.parser.Parser()._tokenizer, CTokenizer)
  140. for text in ("a & b", "{{T|p=a & b}}", "&amp;", "&#42;", "&#x2A;"):
  141. assert str(mwparserfromhell.parse(text)) == text
  142. """
  143. )
  144. env = {**os.environ, "PYTHONMALLOC": "debug"}
  145. result = subprocess.run(
  146. [sys.executable, "-c", program], env=env, capture_output=True, text=True
  147. )
  148. assert result.returncode == 0, (
  149. "C tokenizer triggered allocator mismatch under PYTHONMALLOC=debug:\n"
  150. f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}"
  151. )