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.

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