A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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