A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

617 lines
22 KiB

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