A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

test_wikicode.py 22 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. code7 = parse("{{foo}}{{bar}}{{baz}}{{foo}}{{baz}}")
  171. func = partial(meth, code7)
  172. obj = wrap([code7.get(0), code7.get(2)])
  173. self.assertRaises(ValueError, func, obj, "{{lol}}")
  174. func("{{foo}}{{baz}}", "{{lol}}")
  175. self.assertEqual(expected[6], code7)
  176. def test_insert_before(self):
  177. """test Wikicode.insert_before()"""
  178. meth = lambda code, *args, **kw: code.insert_before(*args, **kw)
  179. expected = [
  180. "{{a}}xz{{b}}{{c}}[[y]]{{d}}{{e}}",
  181. "d{{a}}cd{{a}}d{{a}}f{{b}}f{{b}}ef{{b}}",
  182. "{{a|x{{b}}|{{c|d=y{{f}}}}}}",
  183. "{{a}}w{{b}}{{c}}x{{d}}{{e}}{{f}}{{g}}{{h}}yz{{i}}{{j}}",
  184. "{{a|x{{b}}{{c}}|{{f|{{g}}=y{{h}}{{i}}}}}}",
  185. "here cdis {{some abtext and a {{template}}}}",
  186. "{{foo}}{{bar}}{{baz}}{{lol}}{{foo}}{{baz}}"]
  187. self._test_search(meth, expected)
  188. def test_insert_after(self):
  189. """test Wikicode.insert_after()"""
  190. meth = lambda code, *args, **kw: code.insert_after(*args, **kw)
  191. expected = [
  192. "{{a}}{{b}}xz{{c}}{{d}}[[y]]{{e}}",
  193. "{{a}}d{{a}}dc{{a}}d{{b}}f{{b}}f{{b}}fe",
  194. "{{a|{{b}}x|{{c|d={{f}}y}}}}",
  195. "{{a}}{{b}}{{c}}w{{d}}{{e}}x{{f}}{{g}}{{h}}{{i}}{{j}}yz",
  196. "{{a|{{b}}{{c}}x|{{f|{{g}}={{h}}{{i}}y}}}}",
  197. "here is {{somecd text andab a {{template}}}}",
  198. "{{foo}}{{bar}}{{baz}}{{foo}}{{baz}}{{lol}}"]
  199. self._test_search(meth, expected)
  200. def test_replace(self):
  201. """test Wikicode.replace()"""
  202. meth = lambda code, *args, **kw: code.replace(*args, **kw)
  203. expected = [
  204. "{{a}}xz[[y]]{{e}}", "dcdffe", "{{a|x|{{c|d=y}}}}",
  205. "{{a}}wx{{f}}{{g}}z", "{{a|x|{{f|{{g}}=y}}}}",
  206. "here cd ab a {{template}}}}", "{{foo}}{{bar}}{{baz}}{{lol}}"]
  207. self._test_search(meth, expected)
  208. def test_append(self):
  209. """test Wikicode.append()"""
  210. code = parse("Have a {{template}}")
  211. code.append("{{{argument}}}")
  212. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  213. self.assertIsInstance(code.get(2), Argument)
  214. code.append(None)
  215. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  216. code.append(Text(" foo"))
  217. self.assertEqual("Have a {{template}}{{{argument}}} foo", code)
  218. self.assertRaises(ValueError, code.append, slice(0, 1))
  219. def test_remove(self):
  220. """test Wikicode.remove()"""
  221. meth = lambda code, obj, value, **kw: code.remove(obj, **kw)
  222. expected = [
  223. "{{a}}{{c}}", "", "{{a||{{c|d=}}}}", "{{a}}{{f}}",
  224. "{{a||{{f|{{g}}=}}}}", "here a {{template}}}}",
  225. "{{foo}}{{bar}}{{baz}}"]
  226. self._test_search(meth, expected)
  227. def test_matches(self):
  228. """test Wikicode.matches()"""
  229. code1 = parse("Cleanup")
  230. code2 = parse("\nstub<!-- TODO: make more specific -->")
  231. code3 = parse("")
  232. self.assertTrue(code1.matches("Cleanup"))
  233. self.assertTrue(code1.matches("cleanup"))
  234. self.assertTrue(code1.matches(" cleanup\n"))
  235. self.assertFalse(code1.matches("CLEANup"))
  236. self.assertFalse(code1.matches("Blah"))
  237. self.assertTrue(code2.matches("stub"))
  238. self.assertTrue(code2.matches("Stub<!-- no, it's fine! -->"))
  239. self.assertFalse(code2.matches("StuB"))
  240. self.assertTrue(code1.matches(("cleanup", "stub")))
  241. self.assertTrue(code2.matches(("cleanup", "stub")))
  242. self.assertFalse(code2.matches(("StuB", "sTUb", "foobar")))
  243. self.assertFalse(code2.matches(["StuB", "sTUb", "foobar"]))
  244. self.assertTrue(code2.matches(("StuB", "sTUb", "foo", "bar", "Stub")))
  245. self.assertTrue(code2.matches(["StuB", "sTUb", "foo", "bar", "Stub"]))
  246. self.assertTrue(code3.matches(""))
  247. self.assertTrue(code3.matches("<!-- nothing -->"))
  248. self.assertTrue(code3.matches(("a", "b", "")))
  249. def test_filter_family(self):
  250. """test the Wikicode.i?filter() family of functions"""
  251. def genlist(gen):
  252. self.assertIsInstance(gen, GeneratorType)
  253. return list(gen)
  254. ifilter = lambda code: (lambda *a, **k: genlist(code.ifilter(*a, **k)))
  255. code = parse("a{{b}}c[[d]]{{{e}}}{{f}}[[g]]")
  256. for func in (code.filter, ifilter(code)):
  257. self.assertEqual(["a", "{{b}}", "b", "c", "[[d]]", "d", "{{{e}}}",
  258. "e", "{{f}}", "f", "[[g]]", "g"], func())
  259. self.assertEqual(["{{{e}}}"], func(forcetype=Argument))
  260. self.assertIs(code.get(4), func(forcetype=Argument)[0])
  261. self.assertEqual(list("abcdefg"), func(forcetype=Text))
  262. self.assertEqual([], func(forcetype=Heading))
  263. self.assertRaises(TypeError, func, forcetype=True)
  264. funcs = [
  265. lambda name, **kw: getattr(code, "filter_" + name)(**kw),
  266. lambda name, **kw: genlist(getattr(code, "ifilter_" + name)(**kw))
  267. ]
  268. for get_filter in funcs:
  269. self.assertEqual(["{{{e}}}"], get_filter("arguments"))
  270. self.assertIs(code.get(4), get_filter("arguments")[0])
  271. self.assertEqual([], get_filter("comments"))
  272. self.assertEqual([], get_filter("external_links"))
  273. self.assertEqual([], get_filter("headings"))
  274. self.assertEqual([], get_filter("html_entities"))
  275. self.assertEqual([], get_filter("tags"))
  276. self.assertEqual(["{{b}}", "{{f}}"], get_filter("templates"))
  277. self.assertEqual(list("abcdefg"), get_filter("text"))
  278. self.assertEqual(["[[d]]", "[[g]]"], get_filter("wikilinks"))
  279. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  280. for func in (code2.filter, ifilter(code2)):
  281. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"],
  282. func(recursive=False, forcetype=Template))
  283. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  284. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"],
  285. func(recursive=True, forcetype=Template))
  286. code3 = parse("{{foobar}}{{FOO}}{{baz}}{{bz}}{{barfoo}}")
  287. for func in (code3.filter, ifilter(code3)):
  288. self.assertEqual(["{{foobar}}", "{{barfoo}}"],
  289. func(False, matches=lambda node: "foo" in node))
  290. self.assertEqual(["{{foobar}}", "{{FOO}}", "{{barfoo}}"],
  291. func(False, matches=r"foo"))
  292. self.assertEqual(["{{foobar}}", "{{FOO}}"],
  293. func(matches=r"^{{foo.*?}}"))
  294. self.assertEqual(["{{foobar}}"],
  295. func(matches=r"^{{foo.*?}}", flags=re.UNICODE))
  296. self.assertEqual(["{{baz}}", "{{bz}}"], func(matches=r"^{{b.*?z"))
  297. self.assertEqual(["{{baz}}"], func(matches=r"^{{b.+?z}}"))
  298. exp_rec = ["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  299. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"]
  300. exp_unrec = ["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"]
  301. self.assertEqual(exp_rec, code2.filter_templates())
  302. self.assertEqual(exp_unrec, code2.filter_templates(recursive=False))
  303. self.assertEqual(exp_rec, code2.filter_templates(recursive=True))
  304. self.assertEqual(exp_rec, code2.filter_templates(True))
  305. self.assertEqual(exp_unrec, code2.filter_templates(False))
  306. self.assertEqual(["{{foobar}}"], code3.filter_templates(
  307. matches=lambda node: node.name.matches("Foobar")))
  308. self.assertEqual(["{{baz}}", "{{bz}}"],
  309. code3.filter_templates(matches=r"^{{b.*?z"))
  310. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z"))
  311. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z", flags=0))
  312. self.assertRaises(TypeError, code.filter_templates, a=42)
  313. self.assertRaises(TypeError, code.filter_templates, forcetype=Template)
  314. self.assertRaises(TypeError, code.filter_templates, 1, 0, 0, Template)
  315. code4 = parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
  316. actual1 = code4.filter_templates(recursive=code4.RECURSE_OTHERS)
  317. actual2 = code4.filter_templates(code4.RECURSE_OTHERS)
  318. self.assertEqual(["{{foo}}", "{{foo|{{bar}}}}"], actual1)
  319. self.assertEqual(["{{foo}}", "{{foo|{{bar}}}}"], actual2)
  320. def test_get_sections(self):
  321. """test Wikicode.get_sections()"""
  322. page1 = parse("")
  323. page2 = parse("==Heading==")
  324. page3 = parse("===Heading===\nFoo bar baz\n====Gnidaeh====\n")
  325. p4_lead = "This is a lead.\n"
  326. p4_IA = "=== Section I.A ===\nSection I.A [[body]].\n"
  327. p4_IB1 = "==== Section I.B.1 ====\nSection I.B.1 body.\n\n&bull;Some content.\n\n"
  328. p4_IB = "=== Section I.B ===\n" + p4_IB1
  329. p4_I = "== Section I ==\nSection I body. {{and a|template}}\n" + p4_IA + p4_IB
  330. p4_II = "== Section II ==\nSection II body.\n\n"
  331. p4_IIIA1a = "===== Section III.A.1.a =====\nMore text.\n"
  332. p4_IIIA2ai1 = "======= Section III.A.2.a.i.1 =======\nAn invalid section!"
  333. p4_IIIA2 = "==== Section III.A.2 ====\nEven more text.\n" + p4_IIIA2ai1
  334. p4_IIIA = "=== Section III.A ===\nText.\n" + p4_IIIA1a + p4_IIIA2
  335. p4_III = "== Section III ==\n" + p4_IIIA
  336. page4 = parse(p4_lead + p4_I + p4_II + p4_III)
  337. self.assertEqual([""], page1.get_sections())
  338. self.assertEqual(["", "==Heading=="], page2.get_sections())
  339. self.assertEqual(["", "===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  340. "====Gnidaeh====\n"], page3.get_sections())
  341. self.assertEqual([p4_lead, p4_I, p4_IA, p4_IB, p4_IB1, p4_II,
  342. p4_III, p4_IIIA, p4_IIIA1a, p4_IIIA2, p4_IIIA2ai1],
  343. page4.get_sections())
  344. self.assertEqual(["====Gnidaeh====\n"], page3.get_sections(levels=[4]))
  345. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n"],
  346. page3.get_sections(levels=(2, 3)))
  347. self.assertEqual(["===Heading===\nFoo bar baz\n"],
  348. page3.get_sections(levels=(2, 3), flat=True))
  349. self.assertEqual([], page3.get_sections(levels=[0]))
  350. self.assertEqual(["", "====Gnidaeh====\n"],
  351. page3.get_sections(levels=[4], include_lead=True))
  352. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  353. "====Gnidaeh====\n"],
  354. page3.get_sections(include_lead=False))
  355. self.assertEqual(["===Heading===\nFoo bar baz\n", "====Gnidaeh====\n"],
  356. page3.get_sections(flat=True, include_lead=False))
  357. self.assertEqual([p4_IB1, p4_IIIA2], page4.get_sections(levels=[4]))
  358. self.assertEqual([p4_IA, p4_IB, p4_IIIA], page4.get_sections(levels=[3]))
  359. self.assertEqual([p4_IA, "=== Section I.B ===\n",
  360. "=== Section III.A ===\nText.\n"],
  361. page4.get_sections(levels=[3], flat=True))
  362. self.assertEqual(["", ""], page2.get_sections(include_headings=False))
  363. self.assertEqual(["\nSection I.B.1 body.\n\n&bull;Some content.\n\n",
  364. "\nEven more text.\n" + p4_IIIA2ai1],
  365. page4.get_sections(levels=[4],
  366. include_headings=False))
  367. self.assertEqual([], page4.get_sections(matches=r"body"))
  368. self.assertEqual([p4_I, p4_IA, p4_IB, p4_IB1],
  369. page4.get_sections(matches=r"Section\sI[.\s].*?"))
  370. self.assertEqual([p4_IA, p4_IIIA, p4_IIIA1a, p4_IIIA2, p4_IIIA2ai1],
  371. page4.get_sections(matches=r".*?a.*?"))
  372. self.assertEqual([p4_IIIA1a, p4_IIIA2ai1],
  373. page4.get_sections(matches=r".*?a.*?", flags=re.U))
  374. self.assertEqual(["\nMore text.\n", "\nAn invalid section!"],
  375. page4.get_sections(matches=r".*?a.*?", flags=re.U,
  376. include_headings=False))
  377. sections = page2.get_sections(include_headings=False)
  378. sections[0].append("Lead!\n")
  379. sections[1].append("\nFirst section!")
  380. self.assertEqual("Lead!\n==Heading==\nFirst section!", page2)
  381. page5 = parse("X\n== Foo ==\nBar\n== Baz ==\nBuzz")
  382. section = page5.get_sections(matches="Foo")[0]
  383. section.replace("\nBar\n", "\nBarf ")
  384. section.append("{{Haha}}\n")
  385. self.assertEqual("== Foo ==\nBarf {{Haha}}\n", section)
  386. self.assertEqual("X\n== Foo ==\nBarf {{Haha}}\n== Baz ==\nBuzz", page5)
  387. def test_strip_code(self):
  388. """test Wikicode.strip_code()"""
  389. # Since individual nodes have test cases for their __strip__ methods,
  390. # we're only going to do an integration test:
  391. code = parse("Foo [[bar]]\n\n{{baz}}\n\n[[a|b]] &Sigma;")
  392. self.assertEqual("Foo bar\n\nb Σ",
  393. code.strip_code(normalize=True, collapse=True))
  394. self.assertEqual("Foo bar\n\n\n\nb Σ",
  395. code.strip_code(normalize=True, collapse=False))
  396. self.assertEqual("Foo bar\n\nb &Sigma;",
  397. code.strip_code(normalize=False, collapse=True))
  398. self.assertEqual("Foo bar\n\n\n\nb &Sigma;",
  399. code.strip_code(normalize=False, collapse=False))
  400. def test_get_tree(self):
  401. """test Wikicode.get_tree()"""
  402. # Since individual nodes have test cases for their __showtree___
  403. # methods, and the docstring covers all possibilities for the output of
  404. # __showtree__, we'll test it only:
  405. code = parse("Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}")
  406. expected = "Lorem ipsum \n{{\n\t foo\n\t| 1\n\t= bar\n\t| 2\n\t= " + \
  407. "{{\n\t\t\tbaz\n\t }}\n\t| spam\n\t= eggs\n}}"
  408. self.assertEqual(expected.expandtabs(4), code.get_tree())
  409. if __name__ == "__main__":
  410. unittest.main(verbosity=2)