A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

_test_tokenizer.py 6.0 KiB

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