A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

148 rader
5.2 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. from collections.abc import Generator
  23. from dataclasses import dataclass
  24. import pytest
  25. from mwparserfromhell.parser import contexts, tokens
  26. from mwparserfromhell.parser.builder import Builder
  27. from mwparserfromhell.parser.tokenizer import Tokenizer as PyTokenizer
  28. try:
  29. from mwparserfromhell.parser._tokenizer import CTokenizer
  30. except ImportError:
  31. CTokenizer = None
  32. class _TestParseError(Exception):
  33. """Raised internally when a test could not be parsed."""
  34. @dataclass
  35. class _TestCase:
  36. name: str
  37. label: str | None
  38. input: str
  39. output: list[tokens.Token]
  40. def _load_tests(file_path, filename, text) -> Generator[_TestCase]:
  41. tests = text.split("\n---\n")
  42. for test in tests:
  43. name = None
  44. label = None
  45. input = None
  46. output = None
  47. for line in test.strip().splitlines():
  48. if line.startswith("name:"):
  49. name = line[len("name:") :].strip()
  50. elif line.startswith("label:"):
  51. label = line[len("label:") :].strip()
  52. elif line.startswith("input:"):
  53. raw = line[len("input:") :].strip()
  54. if raw[0] == '"' and raw[-1] == '"':
  55. raw = raw[1:-1]
  56. raw = raw.encode("raw_unicode_escape")
  57. input = raw.decode("unicode_escape")
  58. elif line.startswith("output:"):
  59. raw = line[len("output:") :].strip()
  60. try:
  61. output = eval(raw, dict(vars(tokens)))
  62. except Exception as err:
  63. raise _TestParseError(
  64. f"Could not parse a test in {file_path!r}:\n\t{err}\n\n"
  65. f"Raw test:\n{test}"
  66. )
  67. if not name:
  68. raise _TestParseError(
  69. f"Test in {filename!r} lacks a name\nRaw test:\n{test}"
  70. )
  71. continue
  72. if input is None or output is None:
  73. raise _TestParseError(
  74. f"Test {name!r} in {file_path!r} lacks an input or an output"
  75. )
  76. continue
  77. if not isinstance(output, list) or not all(
  78. isinstance(tok, tokens.Token) for tok in output
  79. ):
  80. raise _TestParseError(
  81. f"Test {name!r} in {file_path!r} should have a list of tokens as its output"
  82. )
  83. yield _TestCase(
  84. name=f"{filename}:{name}",
  85. label=label,
  86. input=input,
  87. output=output,
  88. )
  89. def build():
  90. """Load and install all tests from the 'tokenizer' directory."""
  91. directory = os.path.join(os.path.dirname(__file__), "tokenizer")
  92. extension = ".mwtest"
  93. for filename in os.listdir(directory):
  94. if not filename.endswith(extension):
  95. continue
  96. fullname = os.path.join(directory, filename)
  97. with open(fullname, encoding="utf8") as fp:
  98. text = fp.read()
  99. name = os.path.split(fullname)[1][: -len(extension)]
  100. yield from _load_tests(fullname, name, text)
  101. @pytest.mark.parametrize(
  102. "tokenizer",
  103. filter(None, (CTokenizer, PyTokenizer)),
  104. ids=lambda t: "CTokenizer" if t.USES_C else "PyTokenizer",
  105. )
  106. @pytest.mark.parametrize("test_case", build(), ids=lambda test_case: test_case.name)
  107. def test_tokenizer(tokenizer, test_case: _TestCase):
  108. actual = tokenizer().tokenize(test_case.input)
  109. assert test_case.output == actual
  110. @pytest.mark.parametrize("test_case", build(), ids=lambda test_case: test_case.name)
  111. def test_roundtrip(test_case: _TestCase):
  112. actual = str(Builder().build(test_case.output[:]))
  113. assert test_case.input == actual
  114. @pytest.mark.skipif(CTokenizer is None, reason="CTokenizer not available")
  115. def test_c_tokenizer_uses_c():
  116. """make sure the C tokenizer identifies as using a C extension"""
  117. assert CTokenizer is not None
  118. assert CTokenizer.USES_C is True
  119. assert CTokenizer().USES_C is True
  120. def test_describe_context():
  121. assert "" == contexts.describe(0)
  122. ctx = contexts.describe(contexts.TEMPLATE_PARAM_KEY | contexts.HAS_TEXT)
  123. assert "TEMPLATE_PARAM_KEY|HAS_TEXT" == ctx