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.

test_tokenizer.py 5.1 KiB

пре 4 година
пре 4 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright (C) 2012-2016 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 warnings
  23. import pytest
  24. from mwparserfromhell.parser import contexts, tokens
  25. from mwparserfromhell.parser.builder import Builder
  26. from mwparserfromhell.parser.tokenizer import Tokenizer as PyTokenizer
  27. try:
  28. from mwparserfromhell.parser._tokenizer import CTokenizer
  29. except ImportError:
  30. CTokenizer = None
  31. class _TestParseError(Exception):
  32. """Raised internally when a test could not be parsed."""
  33. def _parse_test(test, data):
  34. """Parse an individual *test*, storing its info in *data*."""
  35. for line in test.strip().splitlines():
  36. if line.startswith("name:"):
  37. data["name"] = line[len("name:") :].strip()
  38. elif line.startswith("label:"):
  39. data["label"] = line[len("label:") :].strip()
  40. elif line.startswith("input:"):
  41. raw = line[len("input:") :].strip()
  42. if raw[0] == '"' and raw[-1] == '"':
  43. raw = raw[1:-1]
  44. raw = raw.encode("raw_unicode_escape")
  45. data["input"] = raw.decode("unicode_escape")
  46. elif line.startswith("output:"):
  47. raw = line[len("output:") :].strip()
  48. try:
  49. data["output"] = eval(raw, vars(tokens))
  50. except Exception as err:
  51. raise _TestParseError(err) from err
  52. def _load_tests(filename, name, text):
  53. """Load all tests in *text* from the file *filename*."""
  54. tests = text.split("\n---\n")
  55. for test in tests:
  56. data = {"name": None, "label": None, "input": None, "output": None}
  57. try:
  58. _parse_test(test, data)
  59. except _TestParseError as err:
  60. if data["name"]:
  61. error = "Could not parse test '{0}' in '{1}':\n\t{2}"
  62. warnings.warn(error.format(data["name"], filename, err))
  63. else:
  64. error = "Could not parse a test in '{0}':\n\t{1}"
  65. warnings.warn(error.format(filename, err))
  66. continue
  67. if not data["name"]:
  68. error = "A test in '{0}' was ignored because it lacked a name"
  69. warnings.warn(error.format(filename))
  70. continue
  71. if data["input"] is None or data["output"] is None:
  72. error = (
  73. "Test '{}' in '{}' was ignored because it lacked an input or an output"
  74. )
  75. warnings.warn(error.format(data["name"], filename))
  76. continue
  77. # Include test filename in name
  78. data["name"] = "{}:{}".format(name, data["name"])
  79. yield data
  80. def build():
  81. """Load and install all tests from the 'tokenizer' directory."""
  82. directory = path.join(path.dirname(__file__), "tokenizer")
  83. extension = ".mwtest"
  84. for filename in listdir(directory):
  85. if not filename.endswith(extension):
  86. continue
  87. fullname = path.join(directory, filename)
  88. with codecs.open(fullname, "r", encoding="utf8") as fp:
  89. text = fp.read()
  90. name = path.split(fullname)[1][: -len(extension)]
  91. yield from _load_tests(fullname, name, text)
  92. @pytest.mark.parametrize(
  93. "tokenizer",
  94. filter(None, (CTokenizer, PyTokenizer)),
  95. ids=lambda t: "CTokenizer" if t.USES_C else "PyTokenizer",
  96. )
  97. @pytest.mark.parametrize("data", build(), ids=lambda data: data["name"])
  98. def test_tokenizer(tokenizer, data):
  99. expected = data["output"]
  100. actual = tokenizer().tokenize(data["input"])
  101. assert expected == actual
  102. @pytest.mark.parametrize("data", build(), ids=lambda data: data["name"])
  103. def test_roundtrip(data):
  104. expected = data["input"]
  105. actual = str(Builder().build(data["output"][:]))
  106. assert expected == actual
  107. @pytest.mark.skipif(CTokenizer is None, reason="CTokenizer not available")
  108. def test_c_tokenizer_uses_c():
  109. """make sure the C tokenizer identifies as using a C extension"""
  110. assert CTokenizer.USES_C is True
  111. assert CTokenizer().USES_C is True
  112. def test_describe_context():
  113. assert "" == contexts.describe(0)
  114. ctx = contexts.describe(contexts.TEMPLATE_PARAM_KEY | contexts.HAS_TEXT)
  115. assert "TEMPLATE_PARAM_KEY|HAS_TEXT" == ctx