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.
 
 
 
 

135 lines
5.1 KiB

  1. #
  2. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. import codecs
  22. from os import listdir, path
  23. import pytest
  24. import warnings
  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. pass
  35. def _parse_test(test, data):
  36. """Parse an individual *test*, storing its info in *data*."""
  37. for line in test.strip().splitlines():
  38. if line.startswith("name:"):
  39. data["name"] = line[len("name:"):].strip()
  40. elif line.startswith("label:"):
  41. data["label"] = line[len("label:"):].strip()
  42. elif line.startswith("input:"):
  43. raw = line[len("input:"):].strip()
  44. if raw[0] == '"' and raw[-1] == '"':
  45. raw = raw[1:-1]
  46. raw = raw.encode("raw_unicode_escape")
  47. data["input"] = raw.decode("unicode_escape")
  48. elif line.startswith("output:"):
  49. raw = line[len("output:"):].strip()
  50. try:
  51. data["output"] = eval(raw, vars(tokens))
  52. except Exception as err:
  53. raise _TestParseError(err)
  54. def _load_tests(filename, name, text):
  55. """Load all tests in *text* from the file *filename*."""
  56. tests = text.split("\n---\n")
  57. for test in tests:
  58. data = {"name": None, "label": None, "input": None, "output": None}
  59. try:
  60. _parse_test(test, data)
  61. except _TestParseError as err:
  62. if data["name"]:
  63. error = "Could not parse test '{0}' in '{1}':\n\t{2}"
  64. warnings.warn(error.format(data["name"], filename, err))
  65. else:
  66. error = "Could not parse a test in '{0}':\n\t{1}"
  67. warnings.warn(error.format(filename, err))
  68. continue
  69. if not data["name"]:
  70. error = "A test in '{0}' was ignored because it lacked a name"
  71. warnings.warn(error.format(filename))
  72. continue
  73. if data["input"] is None or data["output"] is None:
  74. error = "Test '{}' in '{}' was ignored because it lacked an input or an output"
  75. warnings.warn(error.format(data["name"], filename))
  76. continue
  77. # Include test filename in name
  78. data['name'] = '{}:{}'.format(name, data['name'])
  79. yield data
  80. def build():
  81. """Load and install all tests from the 'tokenizer' directory."""
  82. directory = path.join(path.dirname(__file__), "tokenizer")
  83. extension = ".mwtest"
  84. for filename in listdir(directory):
  85. if not filename.endswith(extension):
  86. continue
  87. fullname = path.join(directory, filename)
  88. with codecs.open(fullname, "r", encoding="utf8") as fp:
  89. text = fp.read()
  90. name = path.split(fullname)[1][:-len(extension)]
  91. yield from _load_tests(fullname, name, text)
  92. @pytest.mark.parametrize("tokenizer", filter(None, (
  93. CTokenizer, PyTokenizer
  94. )), ids=lambda t: 'CTokenizer' if t.USES_C else 'PyTokenizer')
  95. @pytest.mark.parametrize("data", build(), ids=lambda data: data['name'])
  96. def test_tokenizer(tokenizer, data):
  97. expected = data["output"]
  98. actual = tokenizer().tokenize(data["input"])
  99. assert expected == actual
  100. @pytest.mark.parametrize("data", build(), ids=lambda data: data['name'])
  101. def test_roundtrip(data):
  102. expected = data["input"]
  103. actual = str(Builder().build(data["output"][:]))
  104. assert expected == actual
  105. @pytest.mark.skipif(CTokenizer is None, reason='CTokenizer not available')
  106. def test_c_tokenizer_uses_c():
  107. """make sure the C tokenizer identifies as using a C extension"""
  108. assert CTokenizer.USES_C is True
  109. assert CTokenizer().USES_C is True
  110. def test_describe_context():
  111. assert "" == contexts.describe(0)
  112. ctx = contexts.describe(contexts.TEMPLATE_PARAM_KEY|contexts.HAS_TEXT)
  113. assert "TEMPLATE_PARAM_KEY|HAS_TEXT" == ctx