A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

8 роки тому
6 роки тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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 print_function, unicode_literals
  23. import json
  24. import os
  25. import unittest
  26. import mwparserfromhell
  27. from mwparserfromhell.compat import py3k, str
  28. from .compat import StringIO, urlencode, urlopen
  29. class TestDocs(unittest.TestCase):
  30. """Integration test cases for mwparserfromhell's documentation."""
  31. def assertPrint(self, input, output):
  32. """Assertion check that *input*, when printed, produces *output*."""
  33. buff = StringIO()
  34. print(input, end="", file=buff)
  35. buff.seek(0)
  36. self.assertEqual(output, buff.read())
  37. def test_readme_1(self):
  38. """test a block of example code in the README"""
  39. text = "I has a template! {{foo|bar|baz|eggs=spam}} See it?"
  40. wikicode = mwparserfromhell.parse(text)
  41. self.assertPrint(wikicode,
  42. "I has a template! {{foo|bar|baz|eggs=spam}} See it?")
  43. templates = wikicode.filter_templates()
  44. if py3k:
  45. self.assertPrint(templates, "['{{foo|bar|baz|eggs=spam}}']")
  46. else:
  47. self.assertPrint(templates, "[u'{{foo|bar|baz|eggs=spam}}']")
  48. template = templates[0]
  49. self.assertPrint(template.name, "foo")
  50. if py3k:
  51. self.assertPrint(template.params, "['bar', 'baz', 'eggs=spam']")
  52. else:
  53. self.assertPrint(template.params, "[u'bar', u'baz', u'eggs=spam']")
  54. self.assertPrint(template.get(1).value, "bar")
  55. self.assertPrint(template.get("eggs").value, "spam")
  56. def test_readme_2(self):
  57. """test a block of example code in the README"""
  58. text = "{{foo|{{bar}}={{baz|{{spam}}}}}}"
  59. temps = mwparserfromhell.parse(text).filter_templates()
  60. if py3k:
  61. res = "['{{foo|{{bar}}={{baz|{{spam}}}}}}', '{{bar}}', '{{baz|{{spam}}}}', '{{spam}}']"
  62. else:
  63. res = "[u'{{foo|{{bar}}={{baz|{{spam}}}}}}', u'{{bar}}', u'{{baz|{{spam}}}}', u'{{spam}}']"
  64. self.assertPrint(temps, res)
  65. def test_readme_3(self):
  66. """test a block of example code in the README"""
  67. code = mwparserfromhell.parse("{{foo|this {{includes a|template}}}}")
  68. if py3k:
  69. self.assertPrint(code.filter_templates(recursive=False),
  70. "['{{foo|this {{includes a|template}}}}']")
  71. else:
  72. self.assertPrint(code.filter_templates(recursive=False),
  73. "[u'{{foo|this {{includes a|template}}}}']")
  74. foo = code.filter_templates(recursive=False)[0]
  75. self.assertPrint(foo.get(1).value, "this {{includes a|template}}")
  76. self.assertPrint(foo.get(1).value.filter_templates()[0],
  77. "{{includes a|template}}")
  78. self.assertPrint(foo.get(1).value.filter_templates()[0].get(1).value,
  79. "template")
  80. def test_readme_4(self):
  81. """test a block of example code in the README"""
  82. text = "{{cleanup}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  83. code = mwparserfromhell.parse(text)
  84. for template in code.filter_templates():
  85. if template.name.matches("Cleanup") and not template.has("date"):
  86. template.add("date", "July 2012")
  87. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  88. self.assertPrint(code, res)
  89. code.replace("{{uncategorized}}", "{{bar-stub}}")
  90. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
  91. self.assertPrint(code, res)
  92. if py3k:
  93. res = "['{{cleanup|date=July 2012}}', '{{bar-stub}}']"
  94. else:
  95. res = "[u'{{cleanup|date=July 2012}}', u'{{bar-stub}}']"
  96. self.assertPrint(code.filter_templates(), res)
  97. text = str(code)
  98. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
  99. self.assertPrint(text, res)
  100. self.assertEqual(text, code)
  101. @unittest.skipIf("NOWEB" in os.environ, "web test disabled by environ var")
  102. def test_readme_5(self):
  103. """test a block of example code in the README; includes a web call"""
  104. url1 = "https://en.wikipedia.org/w/api.php"
  105. url2 = "https://en.wikipedia.org/w/index.php?title={0}&action=raw"
  106. title = "Test"
  107. data = {"action": "query", "prop": "revisions", "rvprop": "content",
  108. "rvslots": "main", "rvlimit": 1, "titles": title,
  109. "format": "json", "formatversion": "2"}
  110. try:
  111. raw = urlopen(url1, urlencode(data).encode("utf8")).read()
  112. except IOError:
  113. self.skipTest("cannot continue because of unsuccessful web call")
  114. res = json.loads(raw.decode("utf8"))
  115. revision = res["query"]["pages"][0]["revisions"][0]
  116. text = revision["slots"]["main"]["content"]
  117. try:
  118. expected = urlopen(url2.format(title)).read().decode("utf8")
  119. except IOError:
  120. self.skipTest("cannot continue because of unsuccessful web call")
  121. actual = mwparserfromhell.parse(text)
  122. self.assertEqual(expected, actual)
  123. if __name__ == "__main__":
  124. unittest.main(verbosity=2)