A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

138 Zeilen
6.1 KiB

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