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.
 
 
 
 

449 lines
22 KiB

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