A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

127 строки
5.1 KiB

  1. # Copyright (C) 2012-2016 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. import codecs
  21. from os import listdir, path
  22. import warnings
  23. import pytest
  24. from mwparserfromhell.parser import contexts, tokens
  25. from mwparserfromhell.parser.builder import Builder
  26. from mwparserfromhell.parser.tokenizer import Tokenizer as PyTokenizer
  27. try:
  28. from mwparserfromhell.parser._tokenizer import CTokenizer
  29. except ImportError:
  30. CTokenizer = None
  31. class _TestParseError(Exception):
  32. """Raised internally when a test could not be parsed."""
  33. def _parse_test(test, data):
  34. """Parse an individual *test*, storing its info in *data*."""
  35. for line in test.strip().splitlines():
  36. if line.startswith("name:"):
  37. data["name"] = line[len("name:"):].strip()
  38. elif line.startswith("label:"):
  39. data["label"] = line[len("label:"):].strip()
  40. elif line.startswith("input:"):
  41. raw = line[len("input:"):].strip()
  42. if raw[0] == '"' and raw[-1] == '"':
  43. raw = raw[1:-1]
  44. raw = raw.encode("raw_unicode_escape")
  45. data["input"] = raw.decode("unicode_escape")
  46. elif line.startswith("output:"):
  47. raw = line[len("output:"):].strip()
  48. try:
  49. data["output"] = eval(raw, vars(tokens))
  50. except Exception as err:
  51. raise _TestParseError(err) from err
  52. def _load_tests(filename, name, text):
  53. """Load all tests in *text* from the file *filename*."""
  54. tests = text.split("\n---\n")
  55. for test in tests:
  56. data = {"name": None, "label": None, "input": None, "output": None}
  57. try:
  58. _parse_test(test, data)
  59. except _TestParseError as err:
  60. if data["name"]:
  61. error = "Could not parse test '{0}' in '{1}':\n\t{2}"
  62. warnings.warn(error.format(data["name"], filename, err))
  63. else:
  64. error = "Could not parse a test in '{0}':\n\t{1}"
  65. warnings.warn(error.format(filename, err))
  66. continue
  67. if not data["name"]:
  68. error = "A test in '{0}' was ignored because it lacked a name"
  69. warnings.warn(error.format(filename))
  70. continue
  71. if data["input"] is None or data["output"] is None:
  72. error = "Test '{}' in '{}' was ignored because it lacked an input or an output"
  73. warnings.warn(error.format(data["name"], filename))
  74. continue
  75. # Include test filename in name
  76. data['name'] = '{}:{}'.format(name, data['name'])
  77. yield data
  78. def build():
  79. """Load and install all tests from the 'tokenizer' directory."""
  80. directory = path.join(path.dirname(__file__), "tokenizer")
  81. extension = ".mwtest"
  82. for filename in listdir(directory):
  83. if not filename.endswith(extension):
  84. continue
  85. fullname = path.join(directory, filename)
  86. with codecs.open(fullname, "r", encoding="utf8") as fp:
  87. text = fp.read()
  88. name = path.split(fullname)[1][:-len(extension)]
  89. yield from _load_tests(fullname, name, text)
  90. @pytest.mark.parametrize("tokenizer", filter(None, (
  91. CTokenizer, PyTokenizer
  92. )), ids=lambda t: 'CTokenizer' if t.USES_C else 'PyTokenizer')
  93. @pytest.mark.parametrize("data", build(), ids=lambda data: data['name'])
  94. def test_tokenizer(tokenizer, data):
  95. expected = data["output"]
  96. actual = tokenizer().tokenize(data["input"])
  97. assert expected == actual
  98. @pytest.mark.parametrize("data", build(), ids=lambda data: data['name'])
  99. def test_roundtrip(data):
  100. expected = data["input"]
  101. actual = str(Builder().build(data["output"][:]))
  102. assert expected == actual
  103. @pytest.mark.skipif(CTokenizer is None, reason='CTokenizer not available')
  104. def test_c_tokenizer_uses_c():
  105. """make sure the C tokenizer identifies as using a C extension"""
  106. assert CTokenizer.USES_C is True
  107. assert CTokenizer().USES_C is True
  108. def test_describe_context():
  109. assert "" == contexts.describe(0)
  110. ctx = contexts.describe(contexts.TEMPLATE_PARAM_KEY|contexts.HAS_TEXT)
  111. assert "TEMPLATE_PARAM_KEY|HAS_TEXT" == ctx