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.
 
 
 
 

378 lines
18 KiB

  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_insert_before(self):
  112. """test Wikicode.insert_before()"""
  113. code = parse("{{a}}{{b}}{{c}}{{d}}")
  114. code.insert_before("{{b}}", "x", recursive=True)
  115. code.insert_before("{{d}}", "[[y]]", recursive=False)
  116. self.assertEqual("{{a}}x{{b}}{{c}}[[y]]{{d}}", code)
  117. code.insert_before(code.get(2), "z")
  118. self.assertEqual("{{a}}xz{{b}}{{c}}[[y]]{{d}}", code)
  119. self.assertRaises(ValueError, code.insert_before, "{{r}}", "n",
  120. recursive=True)
  121. self.assertRaises(ValueError, code.insert_before, "{{r}}", "n",
  122. recursive=False)
  123. code2 = parse("{{a|{{b}}|{{c|d={{f}}}}}}")
  124. code2.insert_before(code2.get(0).params[0].value.get(0), "x",
  125. recursive=True)
  126. code2.insert_before("{{f}}", "y", recursive=True)
  127. self.assertEqual("{{a|x{{b}}|{{c|d=y{{f}}}}}}", code2)
  128. self.assertRaises(ValueError, code2.insert_before, "{{f}}", "y",
  129. recursive=False)
  130. def test_insert_after(self):
  131. """test Wikicode.insert_after()"""
  132. code = parse("{{a}}{{b}}{{c}}{{d}}")
  133. code.insert_after("{{b}}", "x", recursive=True)
  134. code.insert_after("{{d}}", "[[y]]", recursive=False)
  135. self.assertEqual("{{a}}{{b}}x{{c}}{{d}}[[y]]", code)
  136. code.insert_after(code.get(2), "z")
  137. self.assertEqual("{{a}}{{b}}xz{{c}}{{d}}[[y]]", code)
  138. self.assertRaises(ValueError, code.insert_after, "{{r}}", "n",
  139. recursive=True)
  140. self.assertRaises(ValueError, code.insert_after, "{{r}}", "n",
  141. recursive=False)
  142. code2 = parse("{{a|{{b}}|{{c|d={{f}}}}}}")
  143. code2.insert_after(code2.get(0).params[0].value.get(0), "x",
  144. recursive=True)
  145. code2.insert_after("{{f}}", "y", recursive=True)
  146. self.assertEqual("{{a|{{b}}x|{{c|d={{f}}y}}}}", code2)
  147. self.assertRaises(ValueError, code2.insert_after, "{{f}}", "y",
  148. recursive=False)
  149. def test_replace(self):
  150. """test Wikicode.replace()"""
  151. code = parse("{{a}}{{b}}{{c}}{{d}}")
  152. code.replace("{{b}}", "x", recursive=True)
  153. code.replace("{{d}}", "[[y]]", recursive=False)
  154. self.assertEqual("{{a}}x{{c}}[[y]]", code)
  155. code.replace(code.get(1), "z")
  156. self.assertEqual("{{a}}z{{c}}[[y]]", code)
  157. self.assertRaises(ValueError, code.replace, "{{r}}", "n",
  158. recursive=True)
  159. self.assertRaises(ValueError, code.replace, "{{r}}", "n",
  160. recursive=False)
  161. code2 = parse("{{a|{{b}}|{{c|d={{f}}}}}}")
  162. code2.replace(code2.get(0).params[0].value.get(0), "x", recursive=True)
  163. code2.replace("{{f}}", "y", recursive=True)
  164. self.assertEqual("{{a|x|{{c|d=y}}}}", code2)
  165. self.assertRaises(ValueError, code2.replace, "y", "z", recursive=False)
  166. def test_append(self):
  167. """test Wikicode.append()"""
  168. code = parse("Have a {{template}}")
  169. code.append("{{{argument}}}")
  170. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  171. self.assertIsInstance(code.get(2), Argument)
  172. code.append(None)
  173. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  174. code.append(Text(" foo"))
  175. self.assertEqual("Have a {{template}}{{{argument}}} foo", code)
  176. self.assertRaises(ValueError, code.append, slice(0, 1))
  177. def test_remove(self):
  178. """test Wikicode.remove()"""
  179. code = parse("{{a}}{{b}}{{c}}{{d}}")
  180. code.remove("{{b}}", recursive=True)
  181. code.remove(code.get(1), recursive=True)
  182. self.assertEqual("{{a}}{{d}}", code)
  183. self.assertRaises(ValueError, code.remove, "{{r}}", recursive=True)
  184. self.assertRaises(ValueError, code.remove, "{{r}}", recursive=False)
  185. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  186. code2.remove(code2.get(0).params[0].value.get(0), recursive=True)
  187. code2.remove("{{f}}", recursive=True)
  188. self.assertEqual("{{a||{{c|d={{h}}}}}}", code2)
  189. self.assertRaises(ValueError, code2.remove, "{{h}}", recursive=False)
  190. def test_matches(self):
  191. """test Wikicode.matches()"""
  192. code1 = parse("Cleanup")
  193. code2 = parse("\nstub<!-- TODO: make more specific -->")
  194. self.assertTrue(code1.matches("Cleanup"))
  195. self.assertTrue(code1.matches("cleanup"))
  196. self.assertTrue(code1.matches(" cleanup\n"))
  197. self.assertFalse(code1.matches("CLEANup"))
  198. self.assertFalse(code1.matches("Blah"))
  199. self.assertTrue(code2.matches("stub"))
  200. self.assertTrue(code2.matches("Stub<!-- no, it's fine! -->"))
  201. self.assertFalse(code2.matches("StuB"))
  202. def test_filter_family(self):
  203. """test the Wikicode.i?filter() family of functions"""
  204. def genlist(gen):
  205. self.assertIsInstance(gen, GeneratorType)
  206. return list(gen)
  207. ifilter = lambda code: (lambda **kw: genlist(code.ifilter(**kw)))
  208. code = parse("a{{b}}c[[d]]{{{e}}}{{f}}[[g]]")
  209. for func in (code.filter, ifilter(code)):
  210. self.assertEqual(["a", "{{b}}", "b", "c", "[[d]]", "d", "{{{e}}}",
  211. "e", "{{f}}", "f", "[[g]]", "g"], func())
  212. self.assertEqual(["{{{e}}}"], func(forcetype=Argument))
  213. self.assertIs(code.get(4), func(forcetype=Argument)[0])
  214. self.assertEqual(list("abcdefg"), func(forcetype=Text))
  215. self.assertEqual([], func(forcetype=Heading))
  216. self.assertRaises(TypeError, func, forcetype=True)
  217. funcs = [
  218. lambda name, **kw: getattr(code, "filter_" + name)(**kw),
  219. lambda name, **kw: genlist(getattr(code, "ifilter_" + name)(**kw))
  220. ]
  221. for get_filter in funcs:
  222. self.assertEqual(["{{{e}}}"], get_filter("arguments"))
  223. self.assertIs(code.get(4), get_filter("arguments")[0])
  224. self.assertEqual([], get_filter("comments"))
  225. self.assertEqual([], get_filter("headings"))
  226. self.assertEqual([], get_filter("html_entities"))
  227. self.assertEqual([], get_filter("tags"))
  228. self.assertEqual(["{{b}}", "{{f}}"], get_filter("templates"))
  229. self.assertEqual(list("abcdefg"), get_filter("text"))
  230. self.assertEqual(["[[d]]", "[[g]]"], get_filter("wikilinks"))
  231. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  232. for func in (code2.filter, ifilter(code2)):
  233. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"],
  234. func(recursive=False, forcetype=Template))
  235. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  236. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"],
  237. func(recursive=True, forcetype=Template))
  238. code3 = parse("{{foobar}}{{FOO}}{{baz}}{{bz}}")
  239. for func in (code3.filter, ifilter(code3)):
  240. self.assertEqual(["{{foobar}}", "{{FOO}}"], func(recursive=False, matches=r"foo"))
  241. self.assertEqual(["{{foobar}}", "{{FOO}}"],
  242. func(recursive=False, matches=r"^{{foo.*?}}"))
  243. self.assertEqual(["{{foobar}}"],
  244. func(recursive=False, matches=r"^{{foo.*?}}", flags=re.UNICODE))
  245. self.assertEqual(["{{baz}}", "{{bz}}"], func(recursive=False, matches=r"^{{b.*?z"))
  246. self.assertEqual(["{{baz}}"], func(recursive=False, matches=r"^{{b.+?z}}"))
  247. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"],
  248. code2.filter_templates(recursive=False))
  249. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  250. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"],
  251. code2.filter_templates(recursive=True))
  252. self.assertEqual(["{{baz}}", "{{bz}}"],
  253. code3.filter_templates(matches=r"^{{b.*?z"))
  254. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z"))
  255. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z", flags=0))
  256. self.assertRaises(TypeError, code.filter_templates, 100)
  257. self.assertRaises(TypeError, code.filter_templates, a=42)
  258. self.assertRaises(TypeError, code.filter_templates, forcetype=Template)
  259. def test_get_sections(self):
  260. """test Wikicode.get_sections()"""
  261. page1 = parse("")
  262. page2 = parse("==Heading==")
  263. page3 = parse("===Heading===\nFoo bar baz\n====Gnidaeh====\n")
  264. p4_lead = "This is a lead.\n"
  265. p4_IA = "=== Section I.A ===\nSection I.A [[body]].\n"
  266. p4_IB1 = "==== Section I.B.1 ====\nSection I.B.1 body.\n\n&bull;Some content.\n\n"
  267. p4_IB = "=== Section I.B ===\n" + p4_IB1
  268. p4_I = "== Section I ==\nSection I body. {{and a|template}}\n" + p4_IA + p4_IB
  269. p4_II = "== Section II ==\nSection II body.\n\n"
  270. p4_IIIA1a = "===== Section III.A.1.a =====\nMore text.\n"
  271. p4_IIIA2ai1 = "======= Section III.A.2.a.i.1 =======\nAn invalid section!"
  272. p4_IIIA2 = "==== Section III.A.2 ====\nEven more text.\n" + p4_IIIA2ai1
  273. p4_IIIA = "=== Section III.A ===\nText.\n" + p4_IIIA1a + p4_IIIA2
  274. p4_III = "== Section III ==\n" + p4_IIIA
  275. page4 = parse(p4_lead + p4_I + p4_II + p4_III)
  276. self.assertEqual([], page1.get_sections())
  277. self.assertEqual(["", "==Heading=="], page2.get_sections())
  278. self.assertEqual(["", "===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  279. "====Gnidaeh====\n"], page3.get_sections())
  280. self.assertEqual([p4_lead, p4_IA, p4_I, p4_IB, p4_IB1, p4_II,
  281. p4_IIIA1a, p4_III, p4_IIIA, p4_IIIA2, p4_IIIA2ai1],
  282. page4.get_sections())
  283. self.assertEqual(["====Gnidaeh====\n"], page3.get_sections(levels=[4]))
  284. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n"],
  285. page3.get_sections(levels=(2, 3)))
  286. self.assertEqual([], page3.get_sections(levels=[0]))
  287. self.assertEqual(["", "====Gnidaeh====\n"],
  288. page3.get_sections(levels=[4], include_lead=True))
  289. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  290. "====Gnidaeh====\n"],
  291. page3.get_sections(include_lead=False))
  292. self.assertEqual([p4_IB1, p4_IIIA2], page4.get_sections(levels=[4]))
  293. self.assertEqual([""], page2.get_sections(include_headings=False))
  294. self.assertEqual(["\nSection I.B.1 body.\n\n&bull;Some content.\n\n",
  295. "\nEven more text.\n" + p4_IIIA2ai1],
  296. page4.get_sections(levels=[4],
  297. include_headings=False))
  298. self.assertEqual([], page4.get_sections(matches=r"body"))
  299. self.assertEqual([p4_IA, p4_I, p4_IB, p4_IB1],
  300. page4.get_sections(matches=r"Section\sI[.\s].*?"))
  301. self.assertEqual([p4_IA, p4_IIIA1a, p4_IIIA, p4_IIIA2, p4_IIIA2ai1],
  302. page4.get_sections(matches=r".*?a.*?"))
  303. self.assertEqual([p4_IIIA1a, p4_IIIA2ai1],
  304. page4.get_sections(matches=r".*?a.*?", flags=re.U))
  305. self.assertEqual(["\nMore text.\n", "\nAn invalid section!"],
  306. page4.get_sections(matches=r".*?a.*?", flags=re.U,
  307. include_headings=False))
  308. page5 = parse("X\n== Foo ==\nBar\n== Baz ==\nBuzz")
  309. section = page5.get_sections(matches="Foo")[0]
  310. section.replace("\nBar\n", "\nBarf ")
  311. section.append("{{Haha}}\n")
  312. self.assertEqual("== Foo ==\nBarf {{Haha}}\n", section)
  313. self.assertEqual("X\n== Foo ==\nBarf {{Haha}}\n== Baz ==\nBuzz", page5)
  314. def test_strip_code(self):
  315. """test Wikicode.strip_code()"""
  316. # Since individual nodes have test cases for their __strip__ methods,
  317. # we're only going to do an integration test:
  318. code = parse("Foo [[bar]]\n\n{{baz}}\n\n[[a|b]] &Sigma;")
  319. self.assertEqual("Foo bar\n\nb Σ",
  320. code.strip_code(normalize=True, collapse=True))
  321. self.assertEqual("Foo bar\n\n\n\nb Σ",
  322. code.strip_code(normalize=True, collapse=False))
  323. self.assertEqual("Foo bar\n\nb &Sigma;",
  324. code.strip_code(normalize=False, collapse=True))
  325. self.assertEqual("Foo bar\n\n\n\nb &Sigma;",
  326. code.strip_code(normalize=False, collapse=False))
  327. def test_get_tree(self):
  328. """test Wikicode.get_tree()"""
  329. # Since individual nodes have test cases for their __showtree___
  330. # methods, and the docstring covers all possibilities for the output of
  331. # __showtree__, we'll test it only:
  332. code = parse("Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}")
  333. expected = "Lorem ipsum \n{{\n\t foo\n\t| 1\n\t= bar\n\t| 2\n\t= " + \
  334. "{{\n\t\t\tbaz\n\t }}\n\t| spam\n\t= eggs\n}}"
  335. self.assertEqual(expected.expandtabs(4), code.get_tree())
  336. if __name__ == "__main__":
  337. unittest.main(verbosity=2)