A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

_test_tokenizer.py 6.2 KiB

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