A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

134 linhas
5.6 KiB

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