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

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