A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

test_wikicode.py 25 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. #
  2. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. from functools import partial
  22. import re
  23. from types import GeneratorType
  24. import unittest
  25. from mwparserfromhell.nodes import (Argument, Comment, Heading, HTMLEntity,
  26. Node, Tag, Template, Text, Wikilink)
  27. from mwparserfromhell.smart_list import SmartList
  28. from mwparserfromhell.wikicode import Wikicode
  29. from mwparserfromhell import parse
  30. from ._test_tree_equality import TreeEqualityTestCase, wrap, wraptext
  31. class TestWikicode(TreeEqualityTestCase):
  32. """Tests for the Wikicode class, which manages a list of nodes."""
  33. def test_unicode(self):
  34. """test Wikicode.__unicode__()"""
  35. code1 = parse("foobar")
  36. code2 = parse("Have a {{template}} and a [[page|link]]")
  37. self.assertEqual("foobar", str(code1))
  38. self.assertEqual("Have a {{template}} and a [[page|link]]", str(code2))
  39. def test_nodes(self):
  40. """test getter/setter for the nodes attribute"""
  41. code = parse("Have a {{template}}")
  42. self.assertEqual(["Have a ", "{{template}}"], code.nodes)
  43. L1 = SmartList([Text("foobar"), Template(wraptext("abc"))])
  44. L2 = [Text("barfoo"), Template(wraptext("cba"))]
  45. L3 = "abc{{def}}"
  46. code.nodes = L1
  47. self.assertIs(L1, code.nodes)
  48. code.nodes = L2
  49. self.assertIs(L2, code.nodes)
  50. code.nodes = L3
  51. self.assertEqual(["abc", "{{def}}"], code.nodes)
  52. self.assertRaises(ValueError, setattr, code, "nodes", object)
  53. def test_get(self):
  54. """test Wikicode.get()"""
  55. code = parse("Have a {{template}} and a [[page|link]]")
  56. self.assertIs(code.nodes[0], code.get(0))
  57. self.assertIs(code.nodes[2], code.get(2))
  58. self.assertRaises(IndexError, code.get, 4)
  59. def test_set(self):
  60. """test Wikicode.set()"""
  61. code = parse("Have a {{template}} and a [[page|link]]")
  62. code.set(1, "{{{argument}}}")
  63. self.assertEqual("Have a {{{argument}}} and a [[page|link]]", code)
  64. self.assertIsInstance(code.get(1), Argument)
  65. code.set(2, None)
  66. self.assertEqual("Have a {{{argument}}}[[page|link]]", code)
  67. code.set(-3, "This is an ")
  68. self.assertEqual("This is an {{{argument}}}[[page|link]]", code)
  69. self.assertRaises(ValueError, code.set, 1, "foo {{bar}}")
  70. self.assertRaises(IndexError, code.set, 3, "{{baz}}")
  71. self.assertRaises(IndexError, code.set, -4, "{{baz}}")
  72. def test_contains(self):
  73. """test Wikicode.contains()"""
  74. code = parse("Here is {{aaa|{{bbb|xyz{{ccc}}}}}} and a [[page|link]]")
  75. tmpl1, tmpl2, tmpl3 = code.filter_templates()
  76. tmpl4 = parse("{{ccc}}").filter_templates()[0]
  77. self.assertTrue(code.contains(tmpl1))
  78. self.assertTrue(code.contains(tmpl3))
  79. self.assertFalse(code.contains(tmpl4))
  80. self.assertTrue(code.contains(str(tmpl4)))
  81. self.assertTrue(code.contains(tmpl2.params[0].value))
  82. def test_index(self):
  83. """test Wikicode.index()"""
  84. code = parse("Have a {{template}} and a [[page|link]]")
  85. self.assertEqual(0, code.index("Have a "))
  86. self.assertEqual(3, code.index("[[page|link]]"))
  87. self.assertEqual(1, code.index(code.get(1)))
  88. self.assertRaises(ValueError, code.index, "foo")
  89. code = parse("{{foo}}{{bar|{{baz}}}}")
  90. self.assertEqual(1, code.index("{{bar|{{baz}}}}"))
  91. self.assertEqual(1, code.index("{{baz}}", recursive=True))
  92. self.assertEqual(1, code.index(code.get(1).get(1).value,
  93. recursive=True))
  94. self.assertRaises(ValueError, code.index, "{{baz}}", recursive=False)
  95. self.assertRaises(ValueError, code.index,
  96. code.get(1).get(1).value, recursive=False)
  97. def test_get_ancestors_parent(self):
  98. """test Wikicode.get_ancestors() and Wikicode.get_parent()"""
  99. code = parse("{{a|{{b|{{d|{{e}}{{f}}}}{{g}}}}}}{{c}}")
  100. tmpl = code.filter_templates(matches=lambda n: n.name == "f")[0]
  101. parent1 = code.filter_templates(matches=lambda n: n.name == "d")[0]
  102. parent2 = code.filter_templates(matches=lambda n: n.name == "b")[0]
  103. parent3 = code.filter_templates(matches=lambda n: n.name == "a")[0]
  104. fake = parse("{{f}}").get(0)
  105. self.assertEqual([parent3, parent2, parent1], code.get_ancestors(tmpl))
  106. self.assertIs(parent1, code.get_parent(tmpl))
  107. self.assertEqual([], code.get_ancestors(parent3))
  108. self.assertIs(None, code.get_parent(parent3))
  109. self.assertRaises(ValueError, code.get_ancestors, fake)
  110. self.assertRaises(ValueError, code.get_parent, fake)
  111. def test_insert(self):
  112. """test Wikicode.insert()"""
  113. code = parse("Have a {{template}} and a [[page|link]]")
  114. code.insert(1, "{{{argument}}}")
  115. self.assertEqual(
  116. "Have a {{{argument}}}{{template}} and a [[page|link]]", code)
  117. self.assertIsInstance(code.get(1), Argument)
  118. code.insert(2, None)
  119. self.assertEqual(
  120. "Have a {{{argument}}}{{template}} and a [[page|link]]", code)
  121. code.insert(-3, Text("foo"))
  122. self.assertEqual(
  123. "Have a {{{argument}}}foo{{template}} and a [[page|link]]", code)
  124. code2 = parse("{{foo}}{{bar}}{{baz}}")
  125. code2.insert(1, "abc{{def}}ghi[[jk]]")
  126. self.assertEqual("{{foo}}abc{{def}}ghi[[jk]]{{bar}}{{baz}}", code2)
  127. self.assertEqual(["{{foo}}", "abc", "{{def}}", "ghi", "[[jk]]",
  128. "{{bar}}", "{{baz}}"], code2.nodes)
  129. code3 = parse("{{foo}}bar")
  130. code3.insert(1000, "[[baz]]")
  131. code3.insert(-1000, "derp")
  132. self.assertEqual("derp{{foo}}bar[[baz]]", code3)
  133. def _test_search(self, meth, expected):
  134. """Base test for insert_before(), insert_after(), and replace()."""
  135. code = parse("{{a}}{{b}}{{c}}{{d}}{{e}}")
  136. func = partial(meth, code)
  137. func("{{b}}", "x", recursive=True)
  138. func("{{d}}", "[[y]]", recursive=False)
  139. func(code.get(2), "z")
  140. self.assertEqual(expected[0], code)
  141. self.assertRaises(ValueError, func, "{{r}}", "n", recursive=True)
  142. self.assertRaises(ValueError, func, "{{r}}", "n", recursive=False)
  143. fake = parse("{{a}}").get(0)
  144. self.assertRaises(ValueError, func, fake, "n", recursive=True)
  145. self.assertRaises(ValueError, func, fake, "n", recursive=False)
  146. code2 = parse("{{a}}{{a}}{{a}}{{b}}{{b}}{{b}}")
  147. func = partial(meth, code2)
  148. func(code2.get(1), "c", recursive=False)
  149. func("{{a}}", "d", recursive=False)
  150. func(code2.get(-1), "e", recursive=True)
  151. func("{{b}}", "f", recursive=True)
  152. self.assertEqual(expected[1], code2)
  153. code3 = parse("{{a|{{b}}|{{c|d={{f}}}}}}")
  154. func = partial(meth, code3)
  155. obj = code3.get(0).params[0].value.get(0)
  156. self.assertRaises(ValueError, func, obj, "x", recursive=False)
  157. func(obj, "x", recursive=True)
  158. self.assertRaises(ValueError, func, "{{f}}", "y", recursive=False)
  159. func("{{f}}", "y", recursive=True)
  160. self.assertEqual(expected[2], code3)
  161. code4 = parse("{{a}}{{b}}{{c}}{{d}}{{e}}{{f}}{{g}}{{h}}{{i}}{{j}}")
  162. func = partial(meth, code4)
  163. fake = parse("{{b}}{{c}}")
  164. self.assertRaises(ValueError, func, fake, "q", recursive=False)
  165. self.assertRaises(ValueError, func, fake, "q", recursive=True)
  166. func("{{b}}{{c}}", "w", recursive=False)
  167. func("{{d}}{{e}}", "x", recursive=True)
  168. func(Wikicode(code4.nodes[-2:]), "y", recursive=False)
  169. func(Wikicode(code4.nodes[-2:]), "z", recursive=True)
  170. self.assertEqual(expected[3], code4)
  171. self.assertRaises(ValueError, func, "{{c}}{{d}}", "q", recursive=False)
  172. self.assertRaises(ValueError, func, "{{c}}{{d}}", "q", recursive=True)
  173. code5 = parse("{{a|{{b}}{{c}}|{{f|{{g}}={{h}}{{i}}}}}}")
  174. func = partial(meth, code5)
  175. self.assertRaises(ValueError, func, "{{b}}{{c}}", "x", recursive=False)
  176. func("{{b}}{{c}}", "x", recursive=True)
  177. obj = code5.get(0).params[1].value.get(0).params[0].value
  178. self.assertRaises(ValueError, func, obj, "y", recursive=False)
  179. func(obj, "y", recursive=True)
  180. self.assertEqual(expected[4], code5)
  181. code6 = parse("here is {{some text and a {{template}}}}")
  182. func = partial(meth, code6)
  183. self.assertRaises(ValueError, func, "text and", "ab", recursive=False)
  184. func("text and", "ab", recursive=True)
  185. self.assertRaises(ValueError, func, "is {{some", "cd", recursive=False)
  186. func("is {{some", "cd", recursive=True)
  187. self.assertEqual(expected[5], code6)
  188. code7 = parse("{{foo}}{{bar}}{{baz}}{{foo}}{{baz}}")
  189. func = partial(meth, code7)
  190. obj = wrap([code7.get(0), code7.get(2)])
  191. self.assertRaises(ValueError, func, obj, "{{lol}}")
  192. func("{{foo}}{{baz}}", "{{lol}}")
  193. self.assertEqual(expected[6], code7)
  194. code8 = parse("== header ==")
  195. func = partial(meth, code8)
  196. sec1, sec2 = code8.get_sections(include_headings=False)
  197. func(sec1, "lead\n")
  198. func(sec2, "\nbody")
  199. self.assertEqual(expected[7], code8)
  200. code9 = parse("{{foo}}")
  201. meth(code9.get_sections()[0], code9.get_sections()[0], "{{bar}}")
  202. meth(code9.get_sections()[0], code9, "{{baz}}")
  203. meth(code9, code9, "{{qux}}")
  204. meth(code9, code9.get_sections()[0], "{{quz}}")
  205. self.assertEqual(expected[8], code9)
  206. def test_insert_before(self):
  207. """test Wikicode.insert_before()"""
  208. meth = lambda code, *args, **kw: code.insert_before(*args, **kw)
  209. expected = [
  210. "{{a}}xz{{b}}{{c}}[[y]]{{d}}{{e}}",
  211. "d{{a}}cd{{a}}d{{a}}f{{b}}f{{b}}ef{{b}}",
  212. "{{a|x{{b}}|{{c|d=y{{f}}}}}}",
  213. "{{a}}w{{b}}{{c}}x{{d}}{{e}}{{f}}{{g}}{{h}}yz{{i}}{{j}}",
  214. "{{a|x{{b}}{{c}}|{{f|{{g}}=y{{h}}{{i}}}}}}",
  215. "here cdis {{some abtext and a {{template}}}}",
  216. "{{foo}}{{bar}}{{baz}}{{lol}}{{foo}}{{baz}}",
  217. "lead\n== header ==\nbody",
  218. "{{quz}}{{qux}}{{baz}}{{bar}}{{foo}}",
  219. ]
  220. self._test_search(meth, expected)
  221. def test_insert_after(self):
  222. """test Wikicode.insert_after()"""
  223. meth = lambda code, *args, **kw: code.insert_after(*args, **kw)
  224. expected = [
  225. "{{a}}{{b}}xz{{c}}{{d}}[[y]]{{e}}",
  226. "{{a}}d{{a}}dc{{a}}d{{b}}f{{b}}f{{b}}fe",
  227. "{{a|{{b}}x|{{c|d={{f}}y}}}}",
  228. "{{a}}{{b}}{{c}}w{{d}}{{e}}x{{f}}{{g}}{{h}}{{i}}{{j}}yz",
  229. "{{a|{{b}}{{c}}x|{{f|{{g}}={{h}}{{i}}y}}}}",
  230. "here is {{somecd text andab a {{template}}}}",
  231. "{{foo}}{{bar}}{{baz}}{{foo}}{{baz}}{{lol}}",
  232. "lead\n== header ==\nbody",
  233. "{{foo}}{{bar}}{{baz}}{{qux}}{{quz}}",
  234. ]
  235. self._test_search(meth, expected)
  236. def test_replace(self):
  237. """test Wikicode.replace()"""
  238. meth = lambda code, *args, **kw: code.replace(*args, **kw)
  239. expected = [
  240. "{{a}}xz[[y]]{{e}}",
  241. "dcdffe",
  242. "{{a|x|{{c|d=y}}}}",
  243. "{{a}}wx{{f}}{{g}}z",
  244. "{{a|x|{{f|{{g}}=y}}}}",
  245. "here cd ab a {{template}}}}",
  246. "{{foo}}{{bar}}{{baz}}{{lol}}",
  247. "lead\n== header ==\nbody",
  248. "{{quz}}",
  249. ]
  250. self._test_search(meth, expected)
  251. def test_append(self):
  252. """test Wikicode.append()"""
  253. code = parse("Have a {{template}}")
  254. code.append("{{{argument}}}")
  255. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  256. self.assertIsInstance(code.get(2), Argument)
  257. code.append(None)
  258. self.assertEqual("Have a {{template}}{{{argument}}}", code)
  259. code.append(Text(" foo"))
  260. self.assertEqual("Have a {{template}}{{{argument}}} foo", code)
  261. self.assertRaises(ValueError, code.append, slice(0, 1))
  262. def test_remove(self):
  263. """test Wikicode.remove()"""
  264. meth = lambda code, obj, value, **kw: code.remove(obj, **kw)
  265. expected = [
  266. "{{a}}{{c}}",
  267. "",
  268. "{{a||{{c|d=}}}}",
  269. "{{a}}{{f}}",
  270. "{{a||{{f|{{g}}=}}}}",
  271. "here a {{template}}}}",
  272. "{{foo}}{{bar}}{{baz}}",
  273. "== header ==",
  274. "",
  275. ]
  276. self._test_search(meth, expected)
  277. def test_matches(self):
  278. """test Wikicode.matches()"""
  279. code1 = parse("Cleanup")
  280. code2 = parse("\nstub<!-- TODO: make more specific -->")
  281. code3 = parse("Hello world!")
  282. code4 = parse("World,_hello?")
  283. code5 = parse("")
  284. self.assertTrue(code1.matches("Cleanup"))
  285. self.assertTrue(code1.matches("cleanup"))
  286. self.assertTrue(code1.matches(" cleanup\n"))
  287. self.assertFalse(code1.matches("CLEANup"))
  288. self.assertFalse(code1.matches("Blah"))
  289. self.assertTrue(code2.matches("stub"))
  290. self.assertTrue(code2.matches("Stub<!-- no, it's fine! -->"))
  291. self.assertFalse(code2.matches("StuB"))
  292. self.assertTrue(code1.matches(("cleanup", "stub")))
  293. self.assertTrue(code2.matches(("cleanup", "stub")))
  294. self.assertFalse(code2.matches(("StuB", "sTUb", "foobar")))
  295. self.assertFalse(code2.matches(["StuB", "sTUb", "foobar"]))
  296. self.assertTrue(code2.matches(("StuB", "sTUb", "foo", "bar", "Stub")))
  297. self.assertTrue(code2.matches(["StuB", "sTUb", "foo", "bar", "Stub"]))
  298. self.assertTrue(code3.matches("hello world!"))
  299. self.assertTrue(code3.matches("hello_world!"))
  300. self.assertFalse(code3.matches("hello__world!"))
  301. self.assertTrue(code4.matches("World,_hello?"))
  302. self.assertTrue(code4.matches("World, hello?"))
  303. self.assertFalse(code4.matches("World, hello?"))
  304. self.assertTrue(code5.matches(""))
  305. self.assertTrue(code5.matches("<!-- nothing -->"))
  306. self.assertTrue(code5.matches(("a", "b", "")))
  307. def test_filter_family(self):
  308. """test the Wikicode.i?filter() family of functions"""
  309. def genlist(gen):
  310. self.assertIsInstance(gen, GeneratorType)
  311. return list(gen)
  312. ifilter = lambda code: (lambda *a, **k: genlist(code.ifilter(*a, **k)))
  313. code = parse("a{{b}}c[[d]]{{{e}}}{{f}}[[g]]")
  314. for func in (code.filter, ifilter(code)):
  315. self.assertEqual(["a", "{{b}}", "b", "c", "[[d]]", "d", "{{{e}}}",
  316. "e", "{{f}}", "f", "[[g]]", "g"], func())
  317. self.assertEqual(["{{{e}}}"], func(forcetype=Argument))
  318. self.assertIs(code.get(4), func(forcetype=Argument)[0])
  319. self.assertEqual(list("abcdefg"), func(forcetype=Text))
  320. self.assertEqual([], func(forcetype=Heading))
  321. self.assertRaises(TypeError, func, forcetype=True)
  322. funcs = [
  323. lambda name, **kw: getattr(code, "filter_" + name)(**kw),
  324. lambda name, **kw: genlist(getattr(code, "ifilter_" + name)(**kw))
  325. ]
  326. for get_filter in funcs:
  327. self.assertEqual(["{{{e}}}"], get_filter("arguments"))
  328. self.assertIs(code.get(4), get_filter("arguments")[0])
  329. self.assertEqual([], get_filter("comments"))
  330. self.assertEqual([], get_filter("external_links"))
  331. self.assertEqual([], get_filter("headings"))
  332. self.assertEqual([], get_filter("html_entities"))
  333. self.assertEqual([], get_filter("tags"))
  334. self.assertEqual(["{{b}}", "{{f}}"], get_filter("templates"))
  335. self.assertEqual(list("abcdefg"), get_filter("text"))
  336. self.assertEqual(["[[d]]", "[[g]]"], get_filter("wikilinks"))
  337. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  338. for func in (code2.filter, ifilter(code2)):
  339. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"],
  340. func(recursive=False, forcetype=Template))
  341. self.assertEqual(["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  342. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"],
  343. func(recursive=True, forcetype=Template))
  344. code3 = parse("{{foobar}}{{FOO}}{{baz}}{{bz}}{{barfoo}}")
  345. for func in (code3.filter, ifilter(code3)):
  346. self.assertEqual(["{{foobar}}", "{{barfoo}}"],
  347. func(False, matches=lambda node: "foo" in node))
  348. self.assertEqual(["{{foobar}}", "{{FOO}}", "{{barfoo}}"],
  349. func(False, matches=r"foo"))
  350. self.assertEqual(["{{foobar}}", "{{FOO}}"],
  351. func(matches=r"^{{foo.*?}}"))
  352. self.assertEqual(["{{foobar}}"],
  353. func(matches=r"^{{foo.*?}}", flags=re.UNICODE))
  354. self.assertEqual(["{{baz}}", "{{bz}}"], func(matches=r"^{{b.*?z"))
  355. self.assertEqual(["{{baz}}"], func(matches=r"^{{b.+?z}}"))
  356. exp_rec = ["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}", "{{b}}",
  357. "{{c|d={{f}}{{h}}}}", "{{f}}", "{{h}}"]
  358. exp_unrec = ["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"]
  359. self.assertEqual(exp_rec, code2.filter_templates())
  360. self.assertEqual(exp_unrec, code2.filter_templates(recursive=False))
  361. self.assertEqual(exp_rec, code2.filter_templates(recursive=True))
  362. self.assertEqual(exp_rec, code2.filter_templates(True))
  363. self.assertEqual(exp_unrec, code2.filter_templates(False))
  364. self.assertEqual(["{{foobar}}"], code3.filter_templates(
  365. matches=lambda node: node.name.matches("Foobar")))
  366. self.assertEqual(["{{baz}}", "{{bz}}"],
  367. code3.filter_templates(matches=r"^{{b.*?z"))
  368. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z"))
  369. self.assertEqual([], code3.filter_tags(matches=r"^{{b.*?z", flags=0))
  370. self.assertRaises(TypeError, code.filter_templates, a=42)
  371. self.assertRaises(TypeError, code.filter_templates, forcetype=Template)
  372. self.assertRaises(TypeError, code.filter_templates, 1, 0, 0, Template)
  373. code4 = parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
  374. actual1 = code4.filter_templates(recursive=code4.RECURSE_OTHERS)
  375. actual2 = code4.filter_templates(code4.RECURSE_OTHERS)
  376. self.assertEqual(["{{foo}}", "{{foo|{{bar}}}}"], actual1)
  377. self.assertEqual(["{{foo}}", "{{foo|{{bar}}}}"], actual2)
  378. def test_get_sections(self):
  379. """test Wikicode.get_sections()"""
  380. page1 = parse("")
  381. page2 = parse("==Heading==")
  382. page3 = parse("===Heading===\nFoo bar baz\n====Gnidaeh====\n")
  383. p4_lead = "This is a lead.\n"
  384. p4_IA = "=== Section I.A ===\nSection I.A [[body]].\n"
  385. p4_IB1 = "==== Section I.B.1 ====\nSection I.B.1 body.\n\n&bull;Some content.\n\n"
  386. p4_IB = "=== Section I.B ===\n" + p4_IB1
  387. p4_I = "== Section I ==\nSection I body. {{and a|template}}\n" + p4_IA + p4_IB
  388. p4_II = "== Section II ==\nSection II body.\n\n"
  389. p4_IIIA1a = "===== Section III.A.1.a =====\nMore text.\n"
  390. p4_IIIA2ai1 = "======= Section III.A.2.a.i.1 =======\nAn invalid section!"
  391. p4_IIIA2 = "==== Section III.A.2 ====\nEven more text.\n" + p4_IIIA2ai1
  392. p4_IIIA = "=== Section III.A ===\nText.\n" + p4_IIIA1a + p4_IIIA2
  393. p4_III = "== Section III ==\n" + p4_IIIA
  394. page4 = parse(p4_lead + p4_I + p4_II + p4_III)
  395. self.assertEqual([""], page1.get_sections())
  396. self.assertEqual(["", "==Heading=="], page2.get_sections())
  397. self.assertEqual(["", "===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  398. "====Gnidaeh====\n"], page3.get_sections())
  399. self.assertEqual([p4_lead, p4_I, p4_IA, p4_IB, p4_IB1, p4_II,
  400. p4_III, p4_IIIA, p4_IIIA1a, p4_IIIA2, p4_IIIA2ai1],
  401. page4.get_sections())
  402. self.assertEqual(["====Gnidaeh====\n"], page3.get_sections(levels=[4]))
  403. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n"],
  404. page3.get_sections(levels=(2, 3)))
  405. self.assertEqual(["===Heading===\nFoo bar baz\n"],
  406. page3.get_sections(levels=(2, 3), flat=True))
  407. self.assertEqual([], page3.get_sections(levels=[0]))
  408. self.assertEqual(["", "====Gnidaeh====\n"],
  409. page3.get_sections(levels=[4], include_lead=True))
  410. self.assertEqual(["===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  411. "====Gnidaeh====\n"],
  412. page3.get_sections(include_lead=False))
  413. self.assertEqual(["===Heading===\nFoo bar baz\n", "====Gnidaeh====\n"],
  414. page3.get_sections(flat=True, include_lead=False))
  415. self.assertEqual([p4_IB1, p4_IIIA2], page4.get_sections(levels=[4]))
  416. self.assertEqual([p4_IA, p4_IB, p4_IIIA], page4.get_sections(levels=[3]))
  417. self.assertEqual([p4_IA, "=== Section I.B ===\n",
  418. "=== Section III.A ===\nText.\n"],
  419. page4.get_sections(levels=[3], flat=True))
  420. self.assertEqual(["", ""], page2.get_sections(include_headings=False))
  421. self.assertEqual(["\nSection I.B.1 body.\n\n&bull;Some content.\n\n",
  422. "\nEven more text.\n" + p4_IIIA2ai1],
  423. page4.get_sections(levels=[4],
  424. include_headings=False))
  425. self.assertEqual([], page4.get_sections(matches=r"body"))
  426. self.assertEqual([p4_I, p4_IA, p4_IB, p4_IB1],
  427. page4.get_sections(matches=r"Section\sI[.\s].*?"))
  428. self.assertEqual([p4_IA, p4_IIIA, p4_IIIA1a, p4_IIIA2, p4_IIIA2ai1],
  429. page4.get_sections(matches=r".*?a.*?"))
  430. self.assertEqual([p4_IIIA1a, p4_IIIA2ai1],
  431. page4.get_sections(matches=r".*?a.*?", flags=re.U))
  432. self.assertEqual(["\nMore text.\n", "\nAn invalid section!"],
  433. page4.get_sections(matches=r".*?a.*?", flags=re.U,
  434. include_headings=False))
  435. sections = page2.get_sections(include_headings=False)
  436. sections[0].append("Lead!\n")
  437. sections[1].append("\nFirst section!")
  438. self.assertEqual("Lead!\n==Heading==\nFirst section!", page2)
  439. page5 = parse("X\n== Foo ==\nBar\n== Baz ==\nBuzz")
  440. section = page5.get_sections(matches="Foo")[0]
  441. section.replace("\nBar\n", "\nBarf ")
  442. section.append("{{Haha}}\n")
  443. self.assertEqual("== Foo ==\nBarf {{Haha}}\n", section)
  444. self.assertEqual("X\n== Foo ==\nBarf {{Haha}}\n== Baz ==\nBuzz", page5)
  445. def test_strip_code(self):
  446. """test Wikicode.strip_code()"""
  447. # Since individual nodes have test cases for their __strip__ methods,
  448. # we're only going to do an integration test:
  449. code = parse("Foo [[bar]]\n\n{{baz|hello}}\n\n[[a|b]] &Sigma;")
  450. self.assertEqual("Foo bar\n\nb Σ",
  451. code.strip_code(normalize=True, collapse=True))
  452. self.assertEqual("Foo bar\n\n\n\nb Σ",
  453. code.strip_code(normalize=True, collapse=False))
  454. self.assertEqual("Foo bar\n\nb &Sigma;",
  455. code.strip_code(normalize=False, collapse=True))
  456. self.assertEqual("Foo bar\n\n\n\nb &Sigma;",
  457. code.strip_code(normalize=False, collapse=False))
  458. self.assertEqual("Foo bar\n\nhello\n\nb Σ",
  459. code.strip_code(normalize=True, collapse=True,
  460. keep_template_params=True))
  461. def test_get_tree(self):
  462. """test Wikicode.get_tree()"""
  463. # Since individual nodes have test cases for their __showtree___
  464. # methods, and the docstring covers all possibilities for the output of
  465. # __showtree__, we'll test it only:
  466. code = parse("Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}")
  467. expected = "Lorem ipsum \n{{\n\t foo\n\t| 1\n\t= bar\n\t| 2\n\t= " + \
  468. "{{\n\t\t\tbaz\n\t }}\n\t| spam\n\t= eggs\n}}"
  469. self.assertEqual(expected.expandtabs(4), code.get_tree())
  470. if __name__ == "__main__":
  471. unittest.main(verbosity=2)