A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

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