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.
 
 
 
 

118 lines
5.3 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  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 unittest
  25. import urllib
  26. import mwparserfromhell
  27. from mwparserfromhell.compat import py3k, str, StringIO
  28. class TestDocs(unittest.TestCase):
  29. def assertPrint(self, input, output):
  30. """Assertion check that *input*, when printed, produces *output*."""
  31. buff = StringIO()
  32. print(input, end="", file=buff)
  33. buff.seek(0)
  34. self.assertEqual(buff.read(), output)
  35. def test_readme_1(self):
  36. text = "I has a template! {{foo|bar|baz|eggs=spam}} See it?"
  37. wikicode = mwparserfromhell.parse(text)
  38. self.assertPrint(wikicode,
  39. "I has a template! {{foo|bar|baz|eggs=spam}} See it?")
  40. templates = wikicode.filter_templates()
  41. if py3k:
  42. self.assertPrint(templates, "['{{foo|bar|baz|eggs=spam}}']")
  43. else:
  44. self.assertPrint(templates, "[u'{{foo|bar|baz|eggs=spam}}']")
  45. template = templates[0]
  46. self.assertPrint(template.name, "foo")
  47. if py3k:
  48. self.assertPrint(template.params, "['bar', 'baz', 'eggs=spam']")
  49. else:
  50. self.assertPrint(template.params, "[u'bar', u'baz', u'eggs=spam']")
  51. self.assertPrint(template.get(1).value, "bar")
  52. self.assertPrint(template.get("eggs").value, "spam")
  53. def test_readme_2(self):
  54. code = mwparserfromhell.parse("{{foo|this {{includes a|template}}}}")
  55. if py3k:
  56. self.assertPrint(code.filter_templates(),
  57. "['{{foo|this {{includes a|template}}}}']")
  58. else:
  59. self.assertPrint(code.filter_templates(),
  60. "[u'{{foo|this {{includes a|template}}}}']")
  61. foo = code.filter_templates()[0]
  62. self.assertPrint(foo.get(1).value, "this {{includes a|template}}")
  63. self.assertPrint(foo.get(1).value.filter_templates()[0],
  64. "{{includes a|template}}")
  65. self.assertPrint(foo.get(1).value.filter_templates()[0].get(1).value,
  66. "template")
  67. def test_readme_3(self):
  68. text = "{{foo|{{bar}}={{baz|{{spam}}}}}}"
  69. temps = mwparserfromhell.parse(text).filter_templates(recursive=True)
  70. if py3k:
  71. res = "['{{foo|{{bar}}={{baz|{{spam}}}}}}', '{{bar}}', '{{baz|{{spam}}}}', '{{spam}}']"
  72. else:
  73. res = "[u'{{foo|{{bar}}={{baz|{{spam}}}}}}', u'{{bar}}', u'{{baz|{{spam}}}}', u'{{spam}}']"
  74. self.assertPrint(temps, res)
  75. def test_readme_4(self):
  76. text = "{{cleanup}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  77. code = mwparserfromhell.parse(text)
  78. for template in code.filter_templates():
  79. if template.name == "cleanup" and not template.has_param("date"):
  80. template.add("date", "July 2012")
  81. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  82. self.assertPrint(code, res)
  83. code.replace("{{uncategorized}}", "{{bar-stub}}")
  84. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
  85. self.assertPrint(code, res)
  86. if py3k:
  87. res = "['{{cleanup|date=July 2012}}', '{{bar-stub}}']"
  88. else:
  89. res = "[u'{{cleanup|date=July 2012}}', u'{{bar-stub}}']"
  90. self.assertPrint(code.filter_templates(), res)
  91. text = str(code)
  92. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
  93. self.assertPrint(text, res)
  94. self.assertEqual(text, code)
  95. def test_readme_5(self):
  96. url1 = "http://en.wikipedia.org/w/api.php"
  97. url2 = "http://en.wikipedia.org/w/index.php?title={0}&action=raw"
  98. title = "Test"
  99. data = {"action": "query", "prop": "revisions", "rvlimit": 1,
  100. "rvprop": "content", "format": "json", "titles": title}
  101. raw = urllib.urlopen(url1, urllib.urlencode(data)).read()
  102. res = json.loads(raw)
  103. text = res["query"]["pages"].values()[0]["revisions"][0]["*"]
  104. actual = mwparserfromhell.parse(text)
  105. expected = urllib.urlopen(url2.format(title)).read().decode("utf8")
  106. self.assertEqual(actual, expected)
  107. if __name__ == "__main__":
  108. unittest.main(verbosity=2)