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.
 
 
 
 

136 lines
6.0 KiB

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