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.
 
 
 
 

121 rivejä
5.2 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from __future__ import print_function, unicode_literals
  23. from os import listdir, path
  24. from mwparserfromhell.compat import py3k
  25. from mwparserfromhell.parser import tokens
  26. class _TestParseError(Exception):
  27. """Raised internally when a test could not be parsed."""
  28. pass
  29. class TokenizerTestCase(object):
  30. """A base test case for tokenizers, whose tests are loaded dynamically.
  31. Subclassed along with unittest.TestCase to form TestPyTokenizer and
  32. TestCTokenizer. Tests are loaded dynamically from files in the 'tokenizer'
  33. directory.
  34. """
  35. @classmethod
  36. def _build_test_method(cls, funcname, data):
  37. """Create and return a method to be treated as a test case method.
  38. *data* is a dict containing multiple keys: the *input* text to be
  39. tokenized, the expected list of tokens as *output*, and an optional
  40. *label* for the method's docstring.
  41. """
  42. def inner(self):
  43. expected = data["output"]
  44. actual = self.tokenizer().tokenize(data["input"])
  45. self.assertEqual(expected, actual)
  46. if not py3k:
  47. inner.__name__ = funcname.encode("utf8")
  48. inner.__doc__ = data["label"]
  49. return inner
  50. @classmethod
  51. def _load_tests(cls, filename, text):
  52. """Load all tests in *text* from the file *filename*."""
  53. tests = text.split("\n---\n")
  54. counter = 1
  55. digits = len(str(len(tests)))
  56. for test in tests:
  57. data = {"name": None, "label": None, "input": None, "output": None}
  58. try:
  59. for line in test.strip().splitlines():
  60. if line.startswith("name:"):
  61. data["name"] = line[len("name:"):].strip()
  62. elif line.startswith("label:"):
  63. data["label"] = line[len("label:"):].strip()
  64. elif line.startswith("input:"):
  65. raw = line[len("input:"):].strip()
  66. if raw[0] == '"' and raw[-1] == '"':
  67. raw = raw[1:-1]
  68. raw = raw.encode("raw_unicode_escape")
  69. data["input"] = raw.decode("unicode_escape")
  70. elif line.startswith("output:"):
  71. raw = line[len("output:"):].strip()
  72. try:
  73. data["output"] = eval(raw, vars(tokens))
  74. except Exception as err:
  75. raise _TestParseError(err)
  76. except _TestParseError as err:
  77. if data["name"]:
  78. error = "Could not parse test '{0}' in '{1}':\n\t{2}"
  79. print(error.format(data["name"], filename, err))
  80. else:
  81. error = "Could not parse a test in '{0}':\n\t{1}"
  82. print(error.format(filename, err))
  83. continue
  84. if not data["name"]:
  85. error = "A test in '{0}' was ignored because it lacked a name"
  86. print(error.format(filename))
  87. continue
  88. if data["input"] is None or data["output"] is None:
  89. error = "Test '{0}' in '{1}' was ignored because it lacked an input or an output"
  90. print(error.format(data["name"], filename))
  91. continue
  92. number = str(counter).zfill(digits)
  93. fname = "test_{0}{1}_{2}".format(filename, number, data["name"])
  94. meth = cls._build_test_method(fname, data)
  95. setattr(cls, fname, meth)
  96. counter += 1
  97. @classmethod
  98. def build(cls):
  99. """Load and install all tests from the 'tokenizer' directory."""
  100. directory = path.join(path.dirname(__file__), "tokenizer")
  101. extension = ".mwtest"
  102. for filename in listdir(directory):
  103. if not filename.endswith(extension):
  104. continue
  105. with open(path.join(directory, filename), "r") as fp:
  106. text = fp.read()
  107. if not py3k:
  108. text = text.decode("utf8")
  109. cls._load_tests(filename[:0-len(extension)], text)
  110. TokenizerTestCase.build()