A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

639 líneas
22 KiB

  1. # Copyright (C) 2012-2025 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. """
  21. Tests for the Wikicode class, which manages a list of nodes.
  22. """
  23. from __future__ import annotations
  24. import pickle
  25. import re
  26. from functools import partial
  27. from types import GeneratorType
  28. import pytest
  29. from mwparserfromhell import parse
  30. from mwparserfromhell.nodes import Argument, Heading, Template, Text
  31. from mwparserfromhell.smart_list import SmartList
  32. from mwparserfromhell.wikicode import Wikicode
  33. from .conftest import wrap, wraptext
  34. def test_str():
  35. """test Wikicode.__str__()"""
  36. code1 = parse("foobar")
  37. code2 = parse("Have a {{template}} and a [[page|link]]")
  38. assert "foobar" == str(code1)
  39. assert "Have a {{template}} and a [[page|link]]" == str(code2)
  40. def test_nodes():
  41. """test getter/setter for the nodes attribute"""
  42. code = parse("Have a {{template}}")
  43. assert ["Have a ", "{{template}}"] == code.nodes
  44. L1 = SmartList([Text("foobar"), Template(wraptext("abc"))])
  45. L2 = [Text("barfoo"), Template(wraptext("cba"))]
  46. L3 = "abc{{def}}"
  47. code.nodes = L1
  48. assert L1 is code.nodes
  49. code.nodes = L2
  50. assert L2 is code.nodes
  51. code.nodes = L3
  52. assert ["abc", "{{def}}"] == code.nodes
  53. with pytest.raises(ValueError):
  54. code.__setattr__("nodes", object)
  55. @pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1))
  56. def test_pickling(protocol: int):
  57. """test Wikicode objects can be pickled"""
  58. code = parse("Have a {{template}} and a [[page|link]]")
  59. enc = pickle.dumps(code, protocol=protocol)
  60. assert pickle.loads(enc) == code
  61. def test_get():
  62. """test Wikicode.get()"""
  63. code = parse("Have a {{template}} and a [[page|link]]")
  64. assert code.nodes[0] is code.get(0)
  65. assert code.nodes[2] is code.get(2)
  66. with pytest.raises(IndexError):
  67. code.get(4)
  68. def test_set():
  69. """test Wikicode.set()"""
  70. code = parse("Have a {{template}} and a [[page|link]]")
  71. code.set(1, "{{{argument}}}")
  72. assert "Have a {{{argument}}} and a [[page|link]]" == code
  73. assert isinstance(code.get(1), Argument)
  74. code.set(2, None)
  75. assert "Have a {{{argument}}}[[page|link]]" == code
  76. code.set(-3, "This is an ")
  77. assert "This is an {{{argument}}}[[page|link]]" == code
  78. with pytest.raises(ValueError):
  79. code.set(1, "foo {{bar}}")
  80. with pytest.raises(IndexError):
  81. code.set(3, "{{baz}}")
  82. with pytest.raises(IndexError):
  83. code.set(-4, "{{baz}}")
  84. def test_contains():
  85. """test Wikicode.contains()"""
  86. code = parse("Here is {{aaa|{{bbb|xyz{{ccc}}}}}} and a [[page|link]]")
  87. tmpl1, tmpl2, tmpl3 = code.filter_templates()
  88. tmpl4 = parse("{{ccc}}").filter_templates()[0]
  89. assert code.contains(tmpl1) is True
  90. assert code.contains(tmpl3) is True
  91. assert code.contains(tmpl4) is False
  92. assert code.contains(str(tmpl4)) is True
  93. assert code.contains(tmpl2.params[0].value) is True
  94. def test_index():
  95. """test Wikicode.index()"""
  96. code = parse("Have a {{template}} and a [[page|link]]")
  97. assert 0 == code.index("Have a ")
  98. assert 3 == code.index("[[page|link]]")
  99. assert 1 == code.index(code.get(1))
  100. with pytest.raises(ValueError):
  101. code.index("foo")
  102. code = parse("{{foo}}{{bar|{{baz}}}}")
  103. assert 1 == code.index("{{bar|{{baz}}}}")
  104. assert 1 == code.index("{{baz}}", recursive=True)
  105. assert 1 == code.index(code.get(1).get(1).value, recursive=True)
  106. with pytest.raises(ValueError):
  107. code.index("{{baz}}", recursive=False)
  108. with pytest.raises(ValueError):
  109. code.index(code.get(1).get(1).value, recursive=False)
  110. def test_get_ancestors_parent():
  111. """test Wikicode.get_ancestors() and Wikicode.get_parent()"""
  112. code = parse("{{a|{{b|{{d|{{e}}{{f}}}}{{g}}}}}}{{c}}")
  113. tmpl = code.filter_templates(matches=lambda n: n.name == "f")[0]
  114. parent1 = code.filter_templates(matches=lambda n: n.name == "d")[0]
  115. parent2 = code.filter_templates(matches=lambda n: n.name == "b")[0]
  116. parent3 = code.filter_templates(matches=lambda n: n.name == "a")[0]
  117. fake = parse("{{f}}").get(0)
  118. assert [parent3, parent2, parent1] == code.get_ancestors(tmpl)
  119. assert parent1 is code.get_parent(tmpl)
  120. assert [] == code.get_ancestors(parent3)
  121. assert None is code.get_parent(parent3)
  122. with pytest.raises(ValueError):
  123. code.get_ancestors(fake)
  124. with pytest.raises(ValueError):
  125. code.get_parent(fake)
  126. def test_insert():
  127. """test Wikicode.insert()"""
  128. code = parse("Have a {{template}} and a [[page|link]]")
  129. code.insert(1, "{{{argument}}}")
  130. assert "Have a {{{argument}}}{{template}} and a [[page|link]]" == code
  131. assert isinstance(code.get(1), Argument)
  132. code.insert(2, None)
  133. assert "Have a {{{argument}}}{{template}} and a [[page|link]]" == code
  134. code.insert(-3, Text("foo"))
  135. assert "Have a {{{argument}}}foo{{template}} and a [[page|link]]" == code
  136. code2 = parse("{{foo}}{{bar}}{{baz}}")
  137. code2.insert(1, "abc{{def}}ghi[[jk]]")
  138. assert "{{foo}}abc{{def}}ghi[[jk]]{{bar}}{{baz}}" == code2
  139. assert [
  140. "{{foo}}",
  141. "abc",
  142. "{{def}}",
  143. "ghi",
  144. "[[jk]]",
  145. "{{bar}}",
  146. "{{baz}}",
  147. ] == code2.nodes
  148. code3 = parse("{{foo}}bar")
  149. code3.insert(1000, "[[baz]]")
  150. code3.insert(-1000, "derp")
  151. assert "derp{{foo}}bar[[baz]]" == code3
  152. def _test_search(meth, expected):
  153. """Base test for insert_before(), insert_after(), and replace()."""
  154. code = parse("{{a}}{{b}}{{c}}{{d}}{{e}}")
  155. func = partial(meth, code)
  156. func("{{b}}", "x", recursive=True)
  157. func("{{d}}", "[[y]]", recursive=False)
  158. func(code.get(2), "z")
  159. assert expected[0] == code
  160. with pytest.raises(ValueError):
  161. func("{{r}}", "n", recursive=True)
  162. with pytest.raises(ValueError):
  163. func("{{r}}", "n", recursive=False)
  164. fake = parse("{{a}}").get(0)
  165. with pytest.raises(ValueError):
  166. func(fake, "n", recursive=True)
  167. with pytest.raises(ValueError):
  168. func(fake, "n", recursive=False)
  169. code2 = parse("{{a}}{{a}}{{a}}{{b}}{{b}}{{b}}")
  170. func = partial(meth, code2)
  171. func(code2.get(1), "c", recursive=False)
  172. func("{{a}}", "d", recursive=False)
  173. func(code2.get(-1), "e", recursive=True)
  174. func("{{b}}", "f", recursive=True)
  175. assert expected[1] == code2
  176. code3 = parse("{{a|{{b}}|{{c|d={{f}}}}}}")
  177. func = partial(meth, code3)
  178. obj = code3.get(0).params[0].value.get(0)
  179. with pytest.raises(ValueError):
  180. func(obj, "x", recursive=False)
  181. func(obj, "x", recursive=True)
  182. with pytest.raises(ValueError):
  183. func("{{f}}", "y", recursive=False)
  184. func("{{f}}", "y", recursive=True)
  185. assert expected[2] == code3
  186. code4 = parse("{{a}}{{b}}{{c}}{{d}}{{e}}{{f}}{{g}}{{h}}{{i}}{{j}}")
  187. func = partial(meth, code4)
  188. fake = parse("{{b}}{{c}}")
  189. with pytest.raises(ValueError):
  190. func(fake, "q", recursive=False)
  191. with pytest.raises(ValueError):
  192. func(fake, "q", recursive=True)
  193. func("{{b}}{{c}}", "w", recursive=False)
  194. func("{{d}}{{e}}", "x", recursive=True)
  195. func(Wikicode(code4.nodes[-2:]), "y", recursive=False)
  196. func(Wikicode(code4.nodes[-2:]), "z", recursive=True)
  197. assert expected[3] == code4
  198. with pytest.raises(ValueError):
  199. func("{{c}}{{d}}", "q", recursive=False)
  200. with pytest.raises(ValueError):
  201. func("{{c}}{{d}}", "q", recursive=True)
  202. code5 = parse("{{a|{{b}}{{c}}|{{f|{{g}}={{h}}{{i}}}}}}")
  203. func = partial(meth, code5)
  204. with pytest.raises(ValueError):
  205. func("{{b}}{{c}}", "x", recursive=False)
  206. func("{{b}}{{c}}", "x", recursive=True)
  207. obj = code5.get(0).params[1].value.get(0).params[0].value
  208. with pytest.raises(ValueError):
  209. func(obj, "y", recursive=False)
  210. func(obj, "y", recursive=True)
  211. assert expected[4] == code5
  212. code6 = parse("here is {{some text and a {{template}}}}")
  213. func = partial(meth, code6)
  214. with pytest.raises(ValueError):
  215. func("text and", "ab", recursive=False)
  216. func("text and", "ab", recursive=True)
  217. with pytest.raises(ValueError):
  218. func("is {{some", "cd", recursive=False)
  219. func("is {{some", "cd", recursive=True)
  220. assert expected[5] == code6
  221. code7 = parse("{{foo}}{{bar}}{{baz}}{{foo}}{{baz}}")
  222. func = partial(meth, code7)
  223. obj = wrap([code7.get(0), code7.get(2)])
  224. with pytest.raises(ValueError):
  225. func(obj, "{{lol}}")
  226. func("{{foo}}{{baz}}", "{{lol}}")
  227. assert expected[6] == code7
  228. code8 = parse("== header ==")
  229. func = partial(meth, code8)
  230. sec1, sec2 = code8.get_sections(include_headings=False)
  231. func(sec1, "lead\n")
  232. func(sec2, "\nbody")
  233. assert expected[7] == code8
  234. code9 = parse("{{foo}}")
  235. meth(code9.get_sections()[0], code9.get_sections()[0], "{{bar}}")
  236. meth(code9.get_sections()[0], code9, "{{baz}}")
  237. meth(code9, code9, "{{qux}}")
  238. meth(code9, code9.get_sections()[0], "{{quz}}")
  239. assert expected[8] == code9
  240. def test_insert_before():
  241. """test Wikicode.insert_before()"""
  242. def meth(code, *args, **kw):
  243. return code.insert_before(*args, **kw)
  244. expected = [
  245. "{{a}}xz{{b}}{{c}}[[y]]{{d}}{{e}}",
  246. "d{{a}}cd{{a}}d{{a}}f{{b}}f{{b}}ef{{b}}",
  247. "{{a|x{{b}}|{{c|d=y{{f}}}}}}",
  248. "{{a}}w{{b}}{{c}}x{{d}}{{e}}{{f}}{{g}}{{h}}yz{{i}}{{j}}",
  249. "{{a|x{{b}}{{c}}|{{f|{{g}}=y{{h}}{{i}}}}}}",
  250. "here cdis {{some abtext and a {{template}}}}",
  251. "{{foo}}{{bar}}{{baz}}{{lol}}{{foo}}{{baz}}",
  252. "lead\n== header ==\nbody",
  253. "{{quz}}{{qux}}{{baz}}{{bar}}{{foo}}",
  254. ]
  255. _test_search(meth, expected)
  256. def test_insert_after():
  257. """test Wikicode.insert_after()"""
  258. def meth(code, *args, **kw):
  259. return code.insert_after(*args, **kw)
  260. expected = [
  261. "{{a}}{{b}}xz{{c}}{{d}}[[y]]{{e}}",
  262. "{{a}}d{{a}}dc{{a}}d{{b}}f{{b}}f{{b}}fe",
  263. "{{a|{{b}}x|{{c|d={{f}}y}}}}",
  264. "{{a}}{{b}}{{c}}w{{d}}{{e}}x{{f}}{{g}}{{h}}{{i}}{{j}}yz",
  265. "{{a|{{b}}{{c}}x|{{f|{{g}}={{h}}{{i}}y}}}}",
  266. "here is {{somecd text andab a {{template}}}}",
  267. "{{foo}}{{bar}}{{baz}}{{foo}}{{baz}}{{lol}}",
  268. "lead\n== header ==\nbody",
  269. "{{foo}}{{bar}}{{baz}}{{qux}}{{quz}}",
  270. ]
  271. _test_search(meth, expected)
  272. def test_replace():
  273. """test Wikicode.replace()"""
  274. def meth(code, *args, **kw):
  275. return code.replace(*args, **kw)
  276. expected = [
  277. "{{a}}xz[[y]]{{e}}",
  278. "dcdffe",
  279. "{{a|x|{{c|d=y}}}}",
  280. "{{a}}wx{{f}}{{g}}z",
  281. "{{a|x|{{f|{{g}}=y}}}}",
  282. "here cd ab a {{template}}}}",
  283. "{{foo}}{{bar}}{{baz}}{{lol}}",
  284. "lead\n== header ==\nbody",
  285. "{{quz}}",
  286. ]
  287. _test_search(meth, expected)
  288. def test_append():
  289. """test Wikicode.append()"""
  290. code = parse("Have a {{template}}")
  291. code.append("{{{argument}}}")
  292. assert "Have a {{template}}{{{argument}}}" == code
  293. assert isinstance(code.get(2), Argument)
  294. code.append(None)
  295. assert "Have a {{template}}{{{argument}}}" == code
  296. code.append(Text(" foo"))
  297. assert "Have a {{template}}{{{argument}}} foo" == code
  298. with pytest.raises(ValueError):
  299. code.append(slice(0, 1))
  300. def test_remove():
  301. """test Wikicode.remove()"""
  302. def meth(code, obj, value, **kw):
  303. return code.remove(obj, **kw)
  304. expected = [
  305. "{{a}}{{c}}",
  306. "",
  307. "{{a||{{c|d=}}}}",
  308. "{{a}}{{f}}",
  309. "{{a||{{f|{{g}}=}}}}",
  310. "here a {{template}}}}",
  311. "{{foo}}{{bar}}{{baz}}",
  312. "== header ==",
  313. "",
  314. ]
  315. _test_search(meth, expected)
  316. def test_matches():
  317. """test Wikicode.matches()"""
  318. code1 = parse("Cleanup")
  319. code2 = parse("\nstub<!-- TODO: make more specific -->")
  320. code3 = parse("Hello world!")
  321. code4 = parse("World,_hello?")
  322. code5 = parse("")
  323. assert code1.matches("Cleanup") is True
  324. assert code1.matches("cleanup") is True
  325. assert code1.matches(" cleanup\n") is True
  326. assert code1.matches("CLEANup") is False
  327. assert code1.matches("Blah") is False
  328. assert code2.matches("stub") is True
  329. assert code2.matches("Stub<!-- no, it's fine! -->") is True
  330. assert code2.matches("StuB") is False
  331. assert code1.matches(("cleanup", "stub")) is True
  332. assert code2.matches(("cleanup", "stub")) is True
  333. assert code2.matches(("StuB", "sTUb", "foobar")) is False
  334. assert code2.matches(["StuB", "sTUb", "foobar"]) is False
  335. assert code2.matches(("StuB", "sTUb", "foo", "bar", "Stub")) is True
  336. assert code2.matches(["StuB", "sTUb", "foo", "bar", "Stub"]) is True
  337. assert code3.matches("hello world!") is True
  338. assert code3.matches("hello_world!") is True
  339. assert code3.matches("hello__world!") is False
  340. assert code4.matches("World,_hello?") is True
  341. assert code4.matches("World, hello?") is True
  342. assert code4.matches("World, hello?") is False
  343. assert code5.matches("") is True
  344. assert code5.matches("<!-- nothing -->") is True
  345. assert code5.matches(("a", "b", "")) is True
  346. def test_filter_family():
  347. """test the Wikicode.i?filter() family of functions"""
  348. def genlist(gen):
  349. assert isinstance(gen, GeneratorType)
  350. return list(gen)
  351. def ifilter(code):
  352. return lambda *a, **k: genlist(code.ifilter(*a, **k))
  353. code = parse("a{{b}}c[[d]]{{{e}}}{{f}}[[g]]")
  354. for func in (code.filter, ifilter(code)):
  355. assert [
  356. "a",
  357. "{{b}}",
  358. "b",
  359. "c",
  360. "[[d]]",
  361. "d",
  362. "{{{e}}}",
  363. "e",
  364. "{{f}}",
  365. "f",
  366. "[[g]]",
  367. "g",
  368. ] == func()
  369. assert ["{{{e}}}"] == func(forcetype=Argument)
  370. assert code.get(4) is func(forcetype=Argument)[0]
  371. assert list("abcdefg") == func(forcetype=Text)
  372. assert [] == func(forcetype=Heading)
  373. with pytest.raises(TypeError):
  374. func(forcetype=True)
  375. funcs = [
  376. lambda name, **kw: getattr(code, "filter_" + name)(**kw),
  377. lambda name, **kw: genlist(getattr(code, "ifilter_" + name)(**kw)),
  378. ]
  379. for get_filter in funcs:
  380. assert ["{{{e}}}"] == get_filter("arguments")
  381. assert code.get(4) is get_filter("arguments")[0]
  382. assert [] == get_filter("comments")
  383. assert [] == get_filter("external_links")
  384. assert [] == get_filter("headings")
  385. assert [] == get_filter("html_entities")
  386. assert [] == get_filter("tags")
  387. assert ["{{b}}", "{{f}}"] == get_filter("templates")
  388. assert list("abcdefg") == get_filter("text")
  389. assert ["[[d]]", "[[g]]"] == get_filter("wikilinks")
  390. code2 = parse("{{a|{{b}}|{{c|d={{f}}{{h}}}}}}")
  391. for func in (code2.filter, ifilter(code2)):
  392. assert ["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"] == func(
  393. recursive=False, forcetype=Template
  394. )
  395. assert [
  396. "{{a|{{b}}|{{c|d={{f}}{{h}}}}}}",
  397. "{{b}}",
  398. "{{c|d={{f}}{{h}}}}",
  399. "{{f}}",
  400. "{{h}}",
  401. ] == func(recursive=True, forcetype=Template)
  402. code3 = parse("{{foobar}}{{FOO}}{{baz}}{{bz}}{{barfoo}}")
  403. for func in (code3.filter, ifilter(code3)):
  404. assert ["{{foobar}}", "{{barfoo}}"] == func(
  405. False, matches=lambda node: "foo" in node
  406. )
  407. assert ["{{foobar}}", "{{FOO}}", "{{barfoo}}"] == func(False, matches=r"foo")
  408. assert ["{{foobar}}", "{{FOO}}"] == func(matches=r"^{{foo.*?}}")
  409. assert ["{{foobar}}"] == func(matches=r"^{{foo.*?}}", flags=re.UNICODE)
  410. assert ["{{baz}}", "{{bz}}"] == func(matches=r"^{{b.*?z")
  411. assert ["{{baz}}"] == func(matches=r"^{{b.+?z}}")
  412. exp_rec = [
  413. "{{a|{{b}}|{{c|d={{f}}{{h}}}}}}",
  414. "{{b}}",
  415. "{{c|d={{f}}{{h}}}}",
  416. "{{f}}",
  417. "{{h}}",
  418. ]
  419. exp_unrec = ["{{a|{{b}}|{{c|d={{f}}{{h}}}}}}"]
  420. assert exp_rec == code2.filter_templates()
  421. assert exp_unrec == code2.filter_templates(recursive=False)
  422. assert exp_rec == code2.filter_templates(recursive=True)
  423. assert exp_rec == code2.filter_templates(True)
  424. assert exp_unrec == code2.filter_templates(False)
  425. assert ["{{foobar}}"] == code3.filter_templates(
  426. matches=lambda node: node.name.matches("Foobar")
  427. )
  428. assert ["{{baz}}", "{{bz}}"] == code3.filter_templates(matches=r"^{{b.*?z")
  429. assert [] == code3.filter_tags(matches=r"^{{b.*?z")
  430. assert [] == code3.filter_tags(matches=r"^{{b.*?z", flags=0)
  431. with pytest.raises(TypeError):
  432. code.filter_templates(a=42)
  433. with pytest.raises(TypeError):
  434. code.filter_templates(forcetype=Template)
  435. with pytest.raises(TypeError):
  436. code.filter_templates(1, 0, 0, Template)
  437. code4 = parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
  438. actual1 = code4.filter_templates(recursive=code4.RECURSE_OTHERS)
  439. actual2 = code4.filter_templates(code4.RECURSE_OTHERS)
  440. assert ["{{foo}}", "{{foo|{{bar}}}}"] == actual1
  441. assert ["{{foo}}", "{{foo|{{bar}}}}"] == actual2
  442. def test_get_sections():
  443. """test Wikicode.get_sections()"""
  444. page1 = parse("")
  445. page2 = parse("==Heading==")
  446. page3 = parse("===Heading===\nFoo bar baz\n====Gnidaeh====\n")
  447. p4_lead = "This is a lead.\n"
  448. p4_IA = "=== Section I.A ===\nSection I.A [[body]].\n"
  449. p4_IB1 = "==== Section I.B.1 ====\nSection I.B.1 body.\n\n&bull;Some content.\n\n"
  450. p4_IB = "=== Section I.B ===\n" + p4_IB1
  451. p4_I = "== Section I ==\nSection I body. {{and a|template}}\n" + p4_IA + p4_IB
  452. p4_II = "== Section II ==\nSection II body.\n\n"
  453. p4_IIIA1a = "===== Section III.A.1.a =====\nMore text.\n"
  454. p4_IIIA2ai1 = "======= Section III.A.2.a.i.1 =======\nAn invalid section!"
  455. p4_IIIA2 = "==== Section III.A.2 ====\nEven more text.\n" + p4_IIIA2ai1
  456. p4_IIIA = "=== Section III.A ===\nText.\n" + p4_IIIA1a + p4_IIIA2
  457. p4_III = "== Section III ==\n" + p4_IIIA
  458. page4 = parse(p4_lead + p4_I + p4_II + p4_III)
  459. assert [""] == page1.get_sections()
  460. assert ["", "==Heading=="] == page2.get_sections()
  461. assert [
  462. "",
  463. "===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  464. "====Gnidaeh====\n",
  465. ] == page3.get_sections()
  466. assert [
  467. p4_lead,
  468. p4_I,
  469. p4_IA,
  470. p4_IB,
  471. p4_IB1,
  472. p4_II,
  473. p4_III,
  474. p4_IIIA,
  475. p4_IIIA1a,
  476. p4_IIIA2,
  477. p4_IIIA2ai1,
  478. ] == page4.get_sections()
  479. assert ["====Gnidaeh====\n"] == page3.get_sections(levels=[4])
  480. assert ["===Heading===\nFoo bar baz\n====Gnidaeh====\n"] == page3.get_sections(
  481. levels=(2, 3)
  482. )
  483. assert ["===Heading===\nFoo bar baz\n"] == page3.get_sections(
  484. levels=(2, 3), flat=True
  485. )
  486. assert [] == page3.get_sections(levels=[0])
  487. assert ["", "====Gnidaeh====\n"] == page3.get_sections(
  488. levels=[4], include_lead=True
  489. )
  490. assert [
  491. "===Heading===\nFoo bar baz\n====Gnidaeh====\n",
  492. "====Gnidaeh====\n",
  493. ] == page3.get_sections(include_lead=False)
  494. assert ["===Heading===\nFoo bar baz\n", "====Gnidaeh====\n"] == page3.get_sections(
  495. flat=True, include_lead=False
  496. )
  497. assert [p4_IB1, p4_IIIA2] == page4.get_sections(levels=[4])
  498. assert [p4_IA, p4_IB, p4_IIIA] == page4.get_sections(levels=[3])
  499. assert [
  500. p4_IA,
  501. "=== Section I.B ===\n",
  502. "=== Section III.A ===\nText.\n",
  503. ] == page4.get_sections(levels=[3], flat=True)
  504. assert ["", ""] == page2.get_sections(include_headings=False)
  505. assert [
  506. "\nSection I.B.1 body.\n\n&bull;Some content.\n\n",
  507. "\nEven more text.\n" + p4_IIIA2ai1,
  508. ] == page4.get_sections(levels=[4], include_headings=False)
  509. assert [] == page4.get_sections(matches=r"body")
  510. assert [p4_I, p4_IA, p4_IB, p4_IB1] == page4.get_sections(
  511. matches=r"Section\sI[.\s].*?"
  512. )
  513. assert [p4_IA, p4_IIIA, p4_IIIA1a, p4_IIIA2, p4_IIIA2ai1] == page4.get_sections(
  514. matches=r".*?a.*?"
  515. )
  516. assert [p4_IIIA1a, p4_IIIA2ai1] == page4.get_sections(
  517. matches=r".*?a.*?", flags=re.U
  518. )
  519. assert ["\nMore text.\n", "\nAn invalid section!"] == page4.get_sections(
  520. matches=r".*?a.*?", flags=re.U, include_headings=False
  521. )
  522. sections = page2.get_sections(include_headings=False)
  523. sections[0].append("Lead!\n")
  524. sections[1].append("\nFirst section!")
  525. assert "Lead!\n==Heading==\nFirst section!" == page2
  526. page5 = parse("X\n== Foo ==\nBar\n== Baz ==\nBuzz")
  527. section = page5.get_sections(matches="Foo")[0]
  528. section.replace("\nBar\n", "\nBarf ")
  529. section.append("{{Haha}}\n")
  530. assert "== Foo ==\nBarf {{Haha}}\n" == section
  531. assert "X\n== Foo ==\nBarf {{Haha}}\n== Baz ==\nBuzz" == page5
  532. def test_strip_code():
  533. """test Wikicode.strip_code()"""
  534. # Since individual nodes have test cases for their __strip__ methods,
  535. # we're only going to do an integration test:
  536. code = parse("Foo [[bar]]\n\n{{baz|hello}}\n\n[[a|b]] &Sigma;")
  537. assert "Foo bar\n\nb Σ" == code.strip_code(normalize=True, collapse=True)
  538. assert "Foo bar\n\n\n\nb Σ" == code.strip_code(normalize=True, collapse=False)
  539. assert "Foo bar\n\nb &Sigma;" == code.strip_code(normalize=False, collapse=True)
  540. assert "Foo bar\n\n\n\nb &Sigma;" == code.strip_code(
  541. normalize=False, collapse=False
  542. )
  543. assert "Foo bar\n\nhello\n\nb Σ" == code.strip_code(
  544. normalize=True, collapse=True, keep_template_params=True
  545. )
  546. def test_get_tree():
  547. """test Wikicode.get_tree()"""
  548. # Since individual nodes have test cases for their __showtree___
  549. # methods, and the docstring covers all possibilities for the output of
  550. # __showtree__, we'll test it only:
  551. code = parse("Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}")
  552. expected = (
  553. "Lorem ipsum \n{{\n\t foo\n\t| 1\n\t= bar\n\t| 2\n\t= "
  554. + "{{\n\t\t\tbaz\n\t }}\n\t| spam\n\t= eggs\n}}"
  555. )
  556. assert expected.expandtabs(4) == code.get_tree()