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.
 
 
 
 

125 Zeilen
5.5 KiB

  1. #
  2. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. import json
  22. from io import StringIO
  23. import os
  24. import unittest
  25. from urllib.parse import urlencode
  26. from urllib.request import urlopen
  27. import mwparserfromhell
  28. class TestDocs(unittest.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. self.assertPrint(templates, "['{{foo|bar|baz|eggs=spam}}']")
  44. template = templates[0]
  45. self.assertPrint(template.name, "foo")
  46. self.assertPrint(template.params, "['bar', 'baz', 'eggs=spam']")
  47. self.assertPrint(template.get(1).value, "bar")
  48. self.assertPrint(template.get("eggs").value, "spam")
  49. def test_readme_2(self):
  50. """test a block of example code in the README"""
  51. text = "{{foo|{{bar}}={{baz|{{spam}}}}}}"
  52. temps = mwparserfromhell.parse(text).filter_templates()
  53. res = "['{{foo|{{bar}}={{baz|{{spam}}}}}}', '{{bar}}', '{{baz|{{spam}}}}', '{{spam}}']"
  54. self.assertPrint(temps, res)
  55. def test_readme_3(self):
  56. """test a block of example code in the README"""
  57. code = mwparserfromhell.parse("{{foo|this {{includes a|template}}}}")
  58. self.assertPrint(code.filter_templates(recursive=False),
  59. "['{{foo|this {{includes a|template}}}}']")
  60. foo = code.filter_templates(recursive=False)[0]
  61. self.assertPrint(foo.get(1).value, "this {{includes a|template}}")
  62. self.assertPrint(foo.get(1).value.filter_templates()[0],
  63. "{{includes a|template}}")
  64. self.assertPrint(foo.get(1).value.filter_templates()[0].get(1).value,
  65. "template")
  66. def test_readme_4(self):
  67. """test a block of example code in the README"""
  68. text = "{{cleanup}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  69. code = mwparserfromhell.parse(text)
  70. for template in code.filter_templates():
  71. if template.name.matches("Cleanup") and not template.has("date"):
  72. template.add("date", "July 2012")
  73. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  74. self.assertPrint(code, res)
  75. code.replace("{{uncategorized}}", "{{bar-stub}}")
  76. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
  77. self.assertPrint(code, res)
  78. res = "['{{cleanup|date=July 2012}}', '{{bar-stub}}']"
  79. self.assertPrint(code.filter_templates(), res)
  80. text = str(code)
  81. res = "{{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}"
  82. self.assertPrint(text, res)
  83. self.assertEqual(text, code)
  84. @unittest.skipIf("NOWEB" in os.environ, "web test disabled by environ var")
  85. def test_readme_5(self):
  86. """test a block of example code in the README; includes a web call"""
  87. url1 = "https://en.wikipedia.org/w/api.php"
  88. url2 = "https://en.wikipedia.org/w/index.php?title={0}&action=raw"
  89. title = "Test"
  90. data = {
  91. "action": "query",
  92. "prop": "revisions",
  93. "rvprop": "content",
  94. "rvslots": "main",
  95. "rvlimit": 1,
  96. "titles": title,
  97. "format": "json",
  98. "formatversion": "2",
  99. }
  100. try:
  101. raw = urlopen(url1, urlencode(data).encode("utf8")).read()
  102. except OSError:
  103. self.skipTest("cannot continue because of unsuccessful web call")
  104. res = json.loads(raw.decode("utf8"))
  105. revision = res["query"]["pages"][0]["revisions"][0]
  106. text = revision["slots"]["main"]["content"]
  107. try:
  108. expected = urlopen(url2.format(title)).read().decode("utf8")
  109. except OSError:
  110. self.skipTest("cannot continue because of unsuccessful web call")
  111. actual = mwparserfromhell.parse(text)
  112. self.assertEqual(expected, actual)
  113. if __name__ == "__main__":
  114. unittest.main(verbosity=2)