A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

test_docs.py 5.5 KiB

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