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.
 
 
 
 

149 regels
6.0 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 sys
  24. import warnings
  25. from mwparserfromhell.parser import tokens
  26. from mwparserfromhell.parser.builder import Builder
  27. class _TestParseError(Exception):
  28. """Raised internally when a test could not be parsed."""
  29. pass
  30. class TokenizerTestCase:
  31. """A base test case for tokenizers, whose tests are loaded dynamically.
  32. Subclassed along with unittest.TestCase to form TestPyTokenizer and
  33. TestCTokenizer. Tests are loaded dynamically from files in the 'tokenizer'
  34. directory.
  35. """
  36. @staticmethod
  37. def _build_test_method(funcname, data):
  38. """Create and return a method to be treated as a test case method.
  39. *data* is a dict containing multiple keys: the *input* text to be
  40. tokenized, the expected list of tokens as *output*, and an optional
  41. *label* for the method's docstring.
  42. """
  43. def inner(self):
  44. if hasattr(self, "roundtrip"):
  45. expected = data["input"]
  46. actual = str(Builder().build(data["output"][:]))
  47. else:
  48. expected = data["output"]
  49. actual = self.tokenizer().tokenize(data["input"])
  50. self.assertEqual(expected, actual)
  51. inner.__doc__ = data["label"]
  52. return inner
  53. @staticmethod
  54. def _parse_test(test, data):
  55. """Parse an individual *test*, storing its info in *data*."""
  56. for line in test.strip().splitlines():
  57. if line.startswith("name:"):
  58. data["name"] = line[len("name:"):].strip()
  59. elif line.startswith("label:"):
  60. data["label"] = line[len("label:"):].strip()
  61. elif line.startswith("input:"):
  62. raw = line[len("input:"):].strip()
  63. if raw[0] == '"' and raw[-1] == '"':
  64. raw = raw[1:-1]
  65. raw = raw.encode("raw_unicode_escape")
  66. data["input"] = raw.decode("unicode_escape")
  67. elif line.startswith("output:"):
  68. raw = line[len("output:"):].strip()
  69. try:
  70. data["output"] = eval(raw, vars(tokens))
  71. except Exception as err:
  72. raise _TestParseError(err)
  73. @classmethod
  74. def _load_tests(cls, filename, name, text, restrict=None):
  75. """Load all tests in *text* from the file *filename*."""
  76. tests = text.split("\n---\n")
  77. counter = 1
  78. digits = len(str(len(tests)))
  79. for test in tests:
  80. data = {"name": None, "label": None, "input": None, "output": None}
  81. try:
  82. cls._parse_test(test, data)
  83. except _TestParseError as err:
  84. if data["name"]:
  85. error = "Could not parse test '{0}' in '{1}':\n\t{2}"
  86. warnings.warn(error.format(data["name"], filename, err))
  87. else:
  88. error = "Could not parse a test in '{0}':\n\t{1}"
  89. warnings.warn(error.format(filename, err))
  90. continue
  91. if not data["name"]:
  92. error = "A test in '{0}' was ignored because it lacked a name"
  93. warnings.warn(error.format(filename))
  94. continue
  95. if data["input"] is None or data["output"] is None:
  96. error = "Test '{}' in '{}' was ignored because it lacked an input or an output"
  97. warnings.warn(error.format(data["name"], filename))
  98. continue
  99. number = str(counter).zfill(digits)
  100. counter += 1
  101. if restrict and data["name"] != restrict:
  102. continue
  103. fname = "test_{}{}_{}".format(name, number, data["name"])
  104. meth = cls._build_test_method(fname, data)
  105. setattr(cls, fname, meth)
  106. @classmethod
  107. def build(cls):
  108. """Load and install all tests from the 'tokenizer' directory."""
  109. def load_file(filename, restrict=None):
  110. with codecs.open(filename, "r", encoding="utf8") as fp:
  111. text = fp.read()
  112. name = path.split(filename)[1][:-len(extension)]
  113. cls._load_tests(filename, name, text, restrict)
  114. directory = path.join(path.dirname(__file__), "tokenizer")
  115. extension = ".mwtest"
  116. if len(sys.argv) > 2 and sys.argv[1] == "--use":
  117. for name in sys.argv[2:]:
  118. if "." in name:
  119. name, test = name.split(".", 1)
  120. else:
  121. test = None
  122. load_file(path.join(directory, name + extension), test)
  123. sys.argv = [sys.argv[0]] # So unittest doesn't try to parse this
  124. cls.skip_others = True
  125. else:
  126. for filename in listdir(directory):
  127. if not filename.endswith(extension):
  128. continue
  129. load_file(path.join(directory, filename))
  130. cls.skip_others = False
  131. TokenizerTestCase.build()