A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

test_docs.py 5.9 KiB

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