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.

test_wikicode.py 17 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 unicode_literals
  23. import re
  24. from types import GeneratorType
  25. import unittest
  26. from mwparserfromhell.nodes import (Argument, Comment, Heading, HTMLEntity,
  27. Node, Tag, Template, Text, Wikilink)
  28. from mwparserfromhell.smart_list import SmartList
  29. from mwparserfromhell.wikicode import Wikicode
  30. from mwparserfromhell import parse
  31. from mwparserfromhell.compat import py3k, str
  32. from ._test_tree_equality import TreeEqualityTestCase, wrap, wraptext
  33. class TestWikicode(TreeEqualityTestCase):
  34. """Tests for the Wikicode class, which manages a list of nodes."""
  35. def test_unicode(self):
  36. """test Wikicode.__unicode__()"""
  37. code1 = parse("foobar")
  38. code2 = parse("Have a {{template}} and a [[page|link]]")
  39. self.assertEqual("foobar", str(code1))
  40. self.assertEqual("Have a {{template}} and a [[page|link]]", str(code2))
  41. def test_nodes(self):
  42. """test getter/setter for the nodes attribute"""
  43. code = parse("Have a {{template}}")
  44. self.assertEqual(["Have a ", "{{template}}"], code.nodes)
  45. L1 = SmartList([Text("foobar"), Template(wraptext("abc"))])
  46. L2 = [Text("barfoo"), Template(wraptext("cba"))]
  47. L3 = "abc{{def}}"
  48. code.nodes = L1
  49. self.assertIs(L1, code.nodes)
  50. code.nodes = L2
  51. self.assertIs(L2, code.nodes)
  52. code.nodes = L3
  53. self.assertEqual(["abc", "{{def}}"], code.nodes)
  54. self.assertRaises(ValueError, setattr, code, "nodes", object)
  55. def test_get(self):
  56. """test Wikicode.get()"""
  57. code = parse("Have a {{template}} and a [[page|link]]")
  58. self.assertIs(code.nodes[0], code.get(0))
  59. self.assertIs(code.nodes[2], code.get(2))
  60. self.assertRaises(IndexError, code.get, 4)
  61. def test_set(self):
  62. """test Wikicode.set()"""
  63. code = parse("Have a {{template}} and a [[page|link]]")
  64. code.set(1, "{{{argument}}}")
  65. self.assertEqual("Have a {{{argument}}} and a [[page|link]]", code)
  66. self.assertIsInstance(code.get(1), Argument)
  67. code.set(2, None)
  68. self.assertEqual("Have a {{{argument}}}[[page|link]]", code)
  69. code.set(-3, "This is an ")
  70. self.assertEqual("This is an {{{argument}}}[[page|link]]", code)
  71. self.assertRaises(ValueError, code.set, 1, "foo {{bar}}")
  72. self.assertRaises(IndexError, code.set, 3, "{{baz}}")
  73. self.assertRaises(IndexError, code.set, -4, "{{baz}}")
  74. def test_index(self):
  75. """test Wikicode.index()"""
  76. code = parse("Have a {{template}} and a [[page|link]]")
  77. self.assertEqual(0, code.index("Have a "))
  78. self.assertEqual(3, code.index("[[page|link]]"))
  79. self.assertEqual(1, code.index(code.get(1)))
  80. self.assertRaises(ValueError, code.index, "foo")
  81. code = parse("{{foo}}{{bar|{{baz}}}}")
  82. self.assertEqual(1, code.index("{{bar|{{baz}}}}"))
  83. self.assertEqual(1, code.index("{{baz}}", recursive=True))
  84. self.assertEqual(1, code.index(code.get(1).get(1).value,
  85. recursive=True))
  86. self.assertRaises(ValueError, code.index, "{{baz}}", recursive=False)
  87. self.assertRaises(ValueError, code.index,
  88. code.get(1).get(1).value, recursive=False)
  89. def test_insert(self):
  90. """test Wikicode.insert()"""
  91. code = parse("Have a {{template}} and a [[page|link]]")
  92. code.insert(1, "{{{argument}}}")
  93. self.assertEqual(
  94. "Have a {{{argument}}}{{template}} and a [[page|link]]", code)
  95. self.assertIsInstance(code.get(1), Argument)
  96. code.insert(2, None)
  97. self.assertEqual(
  98. "Have a {{{argument}}}{{template}} and a [[page|link]]", code)
  99. code.insert(-3, Text("foo"))
  100. self.assertEqual(
  101. "Have a {{{argument}}}foo{{template}} and a [[page|link]]", code)
  102. code2 = parse("{{foo}}{{bar}}{{baz}}")
  103. code2.insert(1, "abc{{def}}ghi[[jk]]")
  104. self.assertEqual("{{foo}}abc{{def}}ghi[[jk]]{{bar}}{{baz}}", code2)
  105. self.assertEqual(["{{foo}}", "abc", "{{def}}", "ghi", "[[jk]]",
  106. "{{bar}}", "{{baz}}"], code2.nodes)
  107. code3 = parse("{{foo}}bar")
  108. code3.insert(1000, "[[baz]]")
  109. code3.insert(-1000, "derp")
  110. self.assertEqual("derp{{foo}}bar[[baz]]", code3)
  111. def _test_search(self, meth, expected):
  112. """Base test for insert_before(), insert_after(), and replace()."""
  113. code = parse("{{a}}{{b}}{{c}}{{d}}")
  114. func = getattr(code, meth)
  115. func("{{b}}", "x", recursive=True)
  116. func("{{d}}", "[[y]]", recursive=False)
  117. self.assertEqual(expected[0], code)
  118. func(code.get(2), "z")
  119. self.assertEqual(expected[1], code)
  120. self.assertRaises(ValueError, func, "{{r}}", "n", recursive=True)
  121. self.assertRaises(ValueError, func, "{{r}}", "n", recursive=False)
  122. code2 = parse("{{a|{{b}}|{{c|d={{f}}}}}}")
  123. func = getattr(code2, meth)
  124. func(code2.get(0).params[0].value.get(0), "x", recursive=True)
  125. func("{{f}}", "y", recursive=True)
  126. self.assertEqual(expected[2], code2)
  127. self.assertRaises(ValueError, func, "{{f}}", "y", recursive=False)
  128. def test_insert_before(self):
  129. """test Wikicode.insert_before()"""
  130. expected = [
  131. "{{a}}x{{b}}{{c}}[[y]]{{d}}", "{{a}}xz{{b}}{{c}}[[y]]{{d}}",
  132. "{{a|x{{b}}|{{c|d=y{{f}}}}}}"]
  133. self._test_search("insert_before", expected)
  134. def test_insert_after(self):
  135. """test Wikicode.insert_after()"""
  136. expected = [
  137. "{{a}}{{b}}x{{c}}{{d}}[[y]]", "{{a}}{{b}}xz{{c}}{{d}}[[y]]",
  138. "{{a|{{b}}x|{{c|d={{f}}y}}}}"]
  139. self._test_search("insert_after", expected)
  140. def test_replace(self):
  141. """test Wikicode.replace()"""
  142. expected = [
  143. "{{a}}x{{c}}[[y]]", "{{a}}xz[[y]]", "{{a|x|{{c|d=y}}}}"
  144. ]
  145. self._test_search("replace", expected)
  146. def test_append(self):
  147. """test Wikicode.append()"""
  148. code = parse("Have a {{template}}")
  149. code.append("{{{argument}}}")
  150. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  151. self.assertIsInstance(code.get(2), Argument)
  152. code.append(None)
  153. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  154. code.append(Text(" foo"))
  155. self.assertEqual("Have a {{template}}{{{argument}}} foo", code)
  156. self.assertRaises(ValueError, code.append, slice(0, 1))
  157. def test_remove(self):
  158. """test Wikicode.remove()"""
  159. code = parse("{{a}}{{b}}{{c}}{{d}}")
  160. code.remove("{{b}}", recursive=True)
  161. code.remove(code.get(1), recursive=True)
  162. self.assertEqual("{{a}}{{d}}", code)
  163. self.assertRaises(ValueError, code.remove, "{{r}}", recursive=True)
  164. self.assertRaises(ValueError, code.remove, "{{r}}", recursive=False)
  165. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  166. code2.remove(code2.get(0).params[0].value.get(0), recursive=True)
  167. code2.remove("{{f}}", recursive=True)
  168. self.assertEqual("{{a||{{c|d={{h}}}}}}", code2)
  169. self.assertRaises(ValueError, code2.remove, "{{h}}", recursive=False)
  170. def test_matches(self):
  171. """test Wikicode.matches()"""
  172. code1 = parse("Cleanup")
  173. code2 = parse("\nstub<!-- TODO: make more specific -->")
  174. self.assertTrue(code1.matches("Cleanup"))
  175. self.assertTrue(code1.matches("cleanup"))
  176. self.assertTrue(code1.matches(" cleanup\n"))
  177. self.assertFalse(code1.matches("CLEANup"))
  178. self.assertFalse(code1.matches("Blah"))
  179. self.assertTrue(code2.matches("stub"))
  180. self.assertTrue(code2.matches("Stub<!-- no, it's fine! -->"))
  181. self.assertFalse(code2.matches("StuB"))
  182. def test_filter_family(self):
  183. """test the Wikicode.i?filter() family of functions"""
  184. def genlist(gen):
  185. self.assertIsInstance(gen, GeneratorType)
  186. return list(gen)
  187. ifilter = lambda code: (lambda **kw: genlist(code.ifilter(**kw)))
  188. code = parse("a{{b}}c[[d]]{{{e}}}{{f}}[[g]]")
  189. for func in (code.filter, ifilter(code)):
  190. self.assertEqual(["a", "{{b}}", "b", "c", "[[d]]", "d", "{{{e}}}",
  191. "e", "{{f}}", "f", "[[g]]", "g"], func())
  192. self.assertEqual(["{{{e}}}"], func(forcetype=Argument))
  193. self.assertIs(code.get(4), func(forcetype=Argument)[0])
  194. self.assertEqual(list("abcdefg"), func(forcetype=Text))
  195. self.assertEqual([], func(forcetype=Heading))
  196. self.assertRaises(TypeError, func, forcetype=True)
  197. funcs = [
  198. lambda name, **kw: getattr(code, "filter_" + name)(**kw),
  199. lambda name, **kw: genlist(getattr(code, "ifilter_" + name)(**kw))
  200. ]
  201. for get_filter in funcs:
  202. self.assertEqual(["{{{e}}}"], get_filter("arguments"))
  203. self.assertIs(code.get(4), get_filter("arguments")[0])
  204. self.assertEqual([], get_filter("comments"))
  205. self.assertEqual([], get_filter("headings"))
  206. self.assertEqual([], get_filter("html_entities"))
  207. self.assertEqual([], get_filter("tags"))
  208. self.assertEqual(["{{b}}", "{{f}}"], get_filter("templates"))
  209. self.assertEqual(list("abcdefg"), get_filter("text"))
  210. self.assertEqual(["[[d]]", "[[g]]"], get_filter("wikilinks"))
  211. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  212. for func in (code2.filter, ifilter(code2)):
  213. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"],
  214. func(recursive=False, forcetype=Template))
  215. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  216. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"],
  217. func(recursive=True, forcetype=Template))
  218. code3 = parse("{{foobar}}{{FOO}}{{baz}}{{bz}}")
  219. for func in (code3.filter, ifilter(code3)):
  220. self.assertEqual(["{{foobar}}", "{{FOO}}"], func(recursive=False, matches=r"foo"))
  221. self.assertEqual(["{{foobar}}", "{{FOO}}"],
  222. func(recursive=False, matches=r"^{{foo.*?}}"))
  223. self.assertEqual(["{{foobar}}"],
  224. func(recursive=False, matches=r"^{{foo.*?}}", flags=re.UNICODE))
  225. self.assertEqual(["{{baz}}", "{{bz}}"], func(recursive=False, matches=r"^{{b.*?z"))
  226. self.assertEqual(["{{baz}}"], func(recursive=False, matches=r"^{{b.+?z}}"))
  227. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"],
  228. code2.filter_templates(recursive=False))
  229. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  230. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"],
  231. code2.filter_templates(recursive=True))
  232. self.assertEqual(["{{baz}}", "{{bz}}"],
  233. code3.filter_templates(matches=r"^{{b.*?z"))
  234. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z"))
  235. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z", flags=0))
  236. self.assertRaises(TypeError, code.filter_templates, 100)
  237. self.assertRaises(TypeError, code.filter_templates, a=42)
  238. self.assertRaises(TypeError, code.filter_templates, forcetype=Template)
  239. def test_get_sections(self):
  240. """test Wikicode.get_sections()"""
  241. page1 = parse("")
  242. page2 = parse("==Heading==")
  243. page3 = parse("===Heading===\nFoo bar baz\n====Gnidaeh====\n")
  244. p4_lead = "This is a lead.\n"
  245. p4_IA = "=== Section I.A ===\nSection I.A [[body]].\n"
  246. p4_IB1 = "==== Section I.B.1 ====\nSection I.B.1 body.\n\n&bull;Some content.\n\n"
  247. p4_IB = "=== Section I.B ===\n" + p4_IB1
  248. p4_I = "== Section I ==\nSection I body. {{and a|template}}\n" + p4_IA + p4_IB
  249. p4_II = "== Section II ==\nSection II body.\n\n"
  250. p4_IIIA1a = "===== Section III.A.1.a =====\nMore text.\n"
  251. p4_IIIA2ai1 = "======= Section III.A.2.a.i.1 =======\nAn invalid section!"
  252. p4_IIIA2 = "==== Section III.A.2 ====\nEven more text.\n" + p4_IIIA2ai1
  253. p4_IIIA = "=== Section III.A ===\nText.\n" + p4_IIIA1a + p4_IIIA2
  254. p4_III = "== Section III ==\n" + p4_IIIA
  255. page4 = parse(p4_lead + p4_I + p4_II + p4_III)
  256. self.assertEqual([], page1.get_sections())
  257. self.assertEqual(["", "==Heading=="], page2.get_sections())
  258. self.assertEqual(["", "===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  259. "====Gnidaeh====\n"], page3.get_sections())
  260. self.assertEqual([p4_lead, p4_IA, p4_I, p4_IB, p4_IB1, p4_II,
  261. p4_IIIA1a, p4_III, p4_IIIA, p4_IIIA2, p4_IIIA2ai1],
  262. page4.get_sections())
  263. self.assertEqual(["====Gnidaeh====\n"], page3.get_sections(levels=[4]))
  264. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n"],
  265. page3.get_sections(levels=(2, 3)))
  266. self.assertEqual([], page3.get_sections(levels=[0]))
  267. self.assertEqual(["", "====Gnidaeh====\n"],
  268. page3.get_sections(levels=[4], include_lead=True))
  269. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  270. "====Gnidaeh====\n"],
  271. page3.get_sections(include_lead=False))
  272. self.assertEqual([p4_IB1, p4_IIIA2], page4.get_sections(levels=[4]))
  273. self.assertEqual([""], page2.get_sections(include_headings=False))
  274. self.assertEqual(["\nSection I.B.1 body.\n\n&bull;Some content.\n\n",
  275. "\nEven more text.\n" + p4_IIIA2ai1],
  276. page4.get_sections(levels=[4],
  277. include_headings=False))
  278. self.assertEqual([], page4.get_sections(matches=r"body"))
  279. self.assertEqual([p4_IA, p4_I, p4_IB, p4_IB1],
  280. page4.get_sections(matches=r"Section\sI[.\s].*?"))
  281. self.assertEqual([p4_IA, p4_IIIA1a, p4_IIIA, p4_IIIA2, p4_IIIA2ai1],
  282. page4.get_sections(matches=r".*?a.*?"))
  283. self.assertEqual([p4_IIIA1a, p4_IIIA2ai1],
  284. page4.get_sections(matches=r".*?a.*?", flags=re.U))
  285. self.assertEqual(["\nMore text.\n", "\nAn invalid section!"],
  286. page4.get_sections(matches=r".*?a.*?", flags=re.U,
  287. include_headings=False))
  288. page5 = parse("X\n== Foo ==\nBar\n== Baz ==\nBuzz")
  289. section = page5.get_sections(matches="Foo")[0]
  290. section.replace("\nBar\n", "\nBarf ")
  291. section.append("{{Haha}}\n")
  292. self.assertEqual("== Foo ==\nBarf {{Haha}}\n", section)
  293. self.assertEqual("X\n== Foo ==\nBarf {{Haha}}\n== Baz ==\nBuzz", page5)
  294. def test_strip_code(self):
  295. """test Wikicode.strip_code()"""
  296. # Since individual nodes have test cases for their __strip__ methods,
  297. # we're only going to do an integration test:
  298. code = parse("Foo [[bar]]\n\n{{baz}}\n\n[[a|b]] &Sigma;")
  299. self.assertEqual("Foo bar\n\nb Σ",
  300. code.strip_code(normalize=True, collapse=True))
  301. self.assertEqual("Foo bar\n\n\n\nb Σ",
  302. code.strip_code(normalize=True, collapse=False))
  303. self.assertEqual("Foo bar\n\nb &Sigma;",
  304. code.strip_code(normalize=False, collapse=True))
  305. self.assertEqual("Foo bar\n\n\n\nb &Sigma;",
  306. code.strip_code(normalize=False, collapse=False))
  307. def test_get_tree(self):
  308. """test Wikicode.get_tree()"""
  309. # Since individual nodes have test cases for their __showtree___
  310. # methods, and the docstring covers all possibilities for the output of
  311. # __showtree__, we'll test it only:
  312. code = parse("Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}")
  313. expected = "Lorem ipsum \n{{\n\t foo\n\t| 1\n\t= bar\n\t| 2\n\t= " + \
  314. "{{\n\t\t\tbaz\n\t }}\n\t| spam\n\t= eggs\n}}"
  315. self.assertEqual(expected.expandtabs(4), code.get_tree())
  316. if __name__ == "__main__":
  317. unittest.main(verbosity=2)