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.
 
 
 
 

428 lines
20 KiB

  1. #
  2. # Copyright (C) 2012-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. import pytest
  22. from mwparserfromhell.nodes import (Argument, Comment, ExternalLink, Heading,
  23. HTMLEntity, Tag, Template, Text, Wikilink)
  24. from mwparserfromhell.nodes.extras import Attribute, Parameter
  25. from mwparserfromhell.parser import tokens, ParserError
  26. from mwparserfromhell.parser.builder import Builder
  27. from ._test_tree_equality import TreeEqualityTestCase, wrap, wraptext
  28. class TestBuilder(TreeEqualityTestCase):
  29. """Tests for the builder, which turns tokens into Wikicode objects."""
  30. @pytest.fixture()
  31. def builder(self):
  32. return Builder()
  33. @pytest.mark.parametrize("test,valid", [
  34. ([tokens.Text(text="foobar")], wraptext("foobar")),
  35. ([tokens.Text(text="fóóbar")], wraptext("fóóbar")),
  36. ([tokens.Text(text="spam"), tokens.Text(text="eggs")],
  37. wraptext("spam", "eggs")),
  38. ])
  39. def test_text(self, builder, test, valid):
  40. """tests for building Text nodes"""
  41. self.assertWikicodeEqual(valid, builder.build(test))
  42. @pytest.mark.parametrize("test,valid", [
  43. ([tokens.TemplateOpen(), tokens.Text(text="foobar"),
  44. tokens.TemplateClose()],
  45. wrap([Template(wraptext("foobar"))])),
  46. ([tokens.TemplateOpen(), tokens.Text(text="spam"),
  47. tokens.Text(text="eggs"), tokens.TemplateClose()],
  48. wrap([Template(wraptext("spam", "eggs"))])),
  49. ([tokens.TemplateOpen(), tokens.Text(text="foo"),
  50. tokens.TemplateParamSeparator(), tokens.Text(text="bar"),
  51. tokens.TemplateClose()],
  52. wrap([Template(wraptext("foo"), params=[
  53. Parameter(wraptext("1"), wraptext("bar"), showkey=False)])])),
  54. ([tokens.TemplateOpen(), tokens.Text(text="foo"),
  55. tokens.TemplateParamSeparator(), tokens.Text(text="bar"),
  56. tokens.TemplateParamEquals(), tokens.Text(text="baz"),
  57. tokens.TemplateClose()],
  58. wrap([Template(wraptext("foo"), params=[
  59. Parameter(wraptext("bar"), wraptext("baz"))])])),
  60. ([tokens.TemplateOpen(), tokens.TemplateParamSeparator(),
  61. tokens.TemplateParamSeparator(), tokens.TemplateParamEquals(),
  62. tokens.TemplateParamSeparator(), tokens.TemplateClose()],
  63. wrap([Template(wrap([]), params=[
  64. Parameter(wraptext("1"), wrap([]), showkey=False),
  65. Parameter(wrap([]), wrap([]), showkey=True),
  66. Parameter(wraptext("2"), wrap([]), showkey=False)])])),
  67. ([tokens.TemplateOpen(), tokens.Text(text="foo"),
  68. tokens.TemplateParamSeparator(), tokens.Text(text="bar"),
  69. tokens.TemplateParamEquals(), tokens.Text(text="baz"),
  70. tokens.TemplateParamSeparator(), tokens.Text(text="biz"),
  71. tokens.TemplateParamSeparator(), tokens.Text(text="buzz"),
  72. tokens.TemplateParamSeparator(), tokens.Text(text="3"),
  73. tokens.TemplateParamEquals(), tokens.Text(text="buff"),
  74. tokens.TemplateParamSeparator(), tokens.Text(text="baff"),
  75. tokens.TemplateClose()],
  76. wrap([Template(wraptext("foo"), params=[
  77. Parameter(wraptext("bar"), wraptext("baz")),
  78. Parameter(wraptext("1"), wraptext("biz"), showkey=False),
  79. Parameter(wraptext("2"), wraptext("buzz"), showkey=False),
  80. Parameter(wraptext("3"), wraptext("buff")),
  81. Parameter(wraptext("3"), wraptext("baff"),
  82. showkey=False)])])),
  83. ])
  84. def test_template(self, builder, test, valid):
  85. """tests for building Template nodes"""
  86. self.assertWikicodeEqual(valid, builder.build(test))
  87. @pytest.mark.parametrize("test,valid", [
  88. ([tokens.ArgumentOpen(), tokens.Text(text="foobar"),
  89. tokens.ArgumentClose()],
  90. wrap([Argument(wraptext("foobar"))])),
  91. ([tokens.ArgumentOpen(), tokens.Text(text="spam"),
  92. tokens.Text(text="eggs"), tokens.ArgumentClose()],
  93. wrap([Argument(wraptext("spam", "eggs"))])),
  94. ([tokens.ArgumentOpen(), tokens.Text(text="foo"),
  95. tokens.ArgumentSeparator(), tokens.Text(text="bar"),
  96. tokens.ArgumentClose()],
  97. wrap([Argument(wraptext("foo"), wraptext("bar"))])),
  98. ([tokens.ArgumentOpen(), tokens.Text(text="foo"),
  99. tokens.Text(text="bar"), tokens.ArgumentSeparator(),
  100. tokens.Text(text="baz"), tokens.Text(text="biz"),
  101. tokens.ArgumentClose()],
  102. wrap([Argument(wraptext("foo", "bar"), wraptext("baz", "biz"))])),
  103. ])
  104. def test_argument(self, builder, test, valid):
  105. """tests for building Argument nodes"""
  106. self.assertWikicodeEqual(valid, builder.build(test))
  107. @pytest.mark.parametrize("test,valid", [
  108. ([tokens.WikilinkOpen(), tokens.Text(text="foobar"),
  109. tokens.WikilinkClose()],
  110. wrap([Wikilink(wraptext("foobar"))])),
  111. ([tokens.WikilinkOpen(), tokens.Text(text="spam"),
  112. tokens.Text(text="eggs"), tokens.WikilinkClose()],
  113. wrap([Wikilink(wraptext("spam", "eggs"))])),
  114. ([tokens.WikilinkOpen(), tokens.Text(text="foo"),
  115. tokens.WikilinkSeparator(), tokens.Text(text="bar"),
  116. tokens.WikilinkClose()],
  117. wrap([Wikilink(wraptext("foo"), wraptext("bar"))])),
  118. ([tokens.WikilinkOpen(), tokens.Text(text="foo"),
  119. tokens.Text(text="bar"), tokens.WikilinkSeparator(),
  120. tokens.Text(text="baz"), tokens.Text(text="biz"),
  121. tokens.WikilinkClose()],
  122. wrap([Wikilink(wraptext("foo", "bar"), wraptext("baz", "biz"))])),
  123. ])
  124. def test_wikilink(self, builder, test, valid):
  125. """tests for building Wikilink nodes"""
  126. self.assertWikicodeEqual(valid, builder.build(test))
  127. @pytest.mark.parametrize("test,valid", [
  128. ([tokens.ExternalLinkOpen(brackets=False),
  129. tokens.Text(text="http://example.com/"),
  130. tokens.ExternalLinkClose()],
  131. wrap([ExternalLink(wraptext("http://example.com/"),
  132. brackets=False)])),
  133. ([tokens.ExternalLinkOpen(brackets=True),
  134. tokens.Text(text="http://example.com/"),
  135. tokens.ExternalLinkClose()],
  136. wrap([ExternalLink(wraptext("http://example.com/"))])),
  137. ([tokens.ExternalLinkOpen(brackets=True),
  138. tokens.Text(text="http://example.com/"),
  139. tokens.ExternalLinkSeparator(), tokens.ExternalLinkClose()],
  140. wrap([ExternalLink(wraptext("http://example.com/"), wrap([]))])),
  141. ([tokens.ExternalLinkOpen(brackets=True),
  142. tokens.Text(text="http://example.com/"),
  143. tokens.ExternalLinkSeparator(), tokens.Text(text="Example"),
  144. tokens.ExternalLinkClose()],
  145. wrap([ExternalLink(wraptext("http://example.com/"),
  146. wraptext("Example"))])),
  147. ([tokens.ExternalLinkOpen(brackets=False),
  148. tokens.Text(text="http://example"), tokens.Text(text=".com/foo"),
  149. tokens.ExternalLinkClose()],
  150. wrap([ExternalLink(wraptext("http://example", ".com/foo"),
  151. brackets=False)])),
  152. ([tokens.ExternalLinkOpen(brackets=True),
  153. tokens.Text(text="http://example"), tokens.Text(text=".com/foo"),
  154. tokens.ExternalLinkSeparator(), tokens.Text(text="Example"),
  155. tokens.Text(text=" Web Page"), tokens.ExternalLinkClose()],
  156. wrap([ExternalLink(wraptext("http://example", ".com/foo"),
  157. wraptext("Example", " Web Page"))])),
  158. ])
  159. def test_external_link(self, builder, test, valid):
  160. """tests for building ExternalLink nodes"""
  161. self.assertWikicodeEqual(valid, builder.build(test))
  162. @pytest.mark.parametrize("test,valid", [
  163. ([tokens.HTMLEntityStart(), tokens.Text(text="nbsp"),
  164. tokens.HTMLEntityEnd()],
  165. wrap([HTMLEntity("nbsp", named=True, hexadecimal=False)])),
  166. ([tokens.HTMLEntityStart(), tokens.HTMLEntityNumeric(),
  167. tokens.Text(text="107"), tokens.HTMLEntityEnd()],
  168. wrap([HTMLEntity("107", named=False, hexadecimal=False)])),
  169. ([tokens.HTMLEntityStart(), tokens.HTMLEntityNumeric(),
  170. tokens.HTMLEntityHex(char="X"), tokens.Text(text="6B"),
  171. tokens.HTMLEntityEnd()],
  172. wrap([HTMLEntity("6B", named=False, hexadecimal=True,
  173. hex_char="X")])),
  174. ])
  175. def test_html_entity(self, builder, test, valid):
  176. """tests for building HTMLEntity nodes"""
  177. self.assertWikicodeEqual(valid, builder.build(test))
  178. @pytest.mark.parametrize("test,valid", [
  179. ([tokens.HeadingStart(level=2), tokens.Text(text="foobar"),
  180. tokens.HeadingEnd()],
  181. wrap([Heading(wraptext("foobar"), 2)])),
  182. ([tokens.HeadingStart(level=4), tokens.Text(text="spam"),
  183. tokens.Text(text="eggs"), tokens.HeadingEnd()],
  184. wrap([Heading(wraptext("spam", "eggs"), 4)])),
  185. ])
  186. def test_heading(self, builder, test, valid):
  187. """tests for building Heading nodes"""
  188. self.assertWikicodeEqual(valid, builder.build(test))
  189. @pytest.mark.parametrize("test,valid", [
  190. ([tokens.CommentStart(), tokens.Text(text="foobar"),
  191. tokens.CommentEnd()],
  192. wrap([Comment("foobar")])),
  193. ([tokens.CommentStart(), tokens.Text(text="spam"),
  194. tokens.Text(text="eggs"), tokens.CommentEnd()],
  195. wrap([Comment("spameggs")])),
  196. ])
  197. def test_comment(self, builder, test, valid):
  198. """tests for building Comment nodes"""
  199. self.assertWikicodeEqual(valid, builder.build(test))
  200. @pytest.mark.parametrize("test,valid", [
  201. # <ref></ref>
  202. ([tokens.TagOpenOpen(), tokens.Text(text="ref"),
  203. tokens.TagCloseOpen(padding=""), tokens.TagOpenClose(),
  204. tokens.Text(text="ref"), tokens.TagCloseClose()],
  205. wrap([Tag(wraptext("ref"), wrap([]),
  206. closing_tag=wraptext("ref"))])),
  207. # <ref name></ref>
  208. ([tokens.TagOpenOpen(), tokens.Text(text="ref"),
  209. tokens.TagAttrStart(pad_first=" ", pad_before_eq="",
  210. pad_after_eq=""),
  211. tokens.Text(text="name"), tokens.TagCloseOpen(padding=""),
  212. tokens.TagOpenClose(), tokens.Text(text="ref"),
  213. tokens.TagCloseClose()],
  214. wrap([Tag(wraptext("ref"), wrap([]),
  215. attrs=[Attribute(wraptext("name"))])])),
  216. # <ref name="abc" />
  217. ([tokens.TagOpenOpen(), tokens.Text(text="ref"),
  218. tokens.TagAttrStart(pad_first=" ", pad_before_eq="",
  219. pad_after_eq=""),
  220. tokens.Text(text="name"), tokens.TagAttrEquals(),
  221. tokens.TagAttrQuote(char='"'), tokens.Text(text="abc"),
  222. tokens.TagCloseSelfclose(padding=" ")],
  223. wrap([Tag(wraptext("ref"),
  224. attrs=[Attribute(wraptext("name"), wraptext("abc"))],
  225. self_closing=True, padding=" ")])),
  226. # <br/>
  227. ([tokens.TagOpenOpen(), tokens.Text(text="br"),
  228. tokens.TagCloseSelfclose(padding="")],
  229. wrap([Tag(wraptext("br"), self_closing=True)])),
  230. # <li>
  231. ([tokens.TagOpenOpen(), tokens.Text(text="li"),
  232. tokens.TagCloseSelfclose(padding="", implicit=True)],
  233. wrap([Tag(wraptext("li"), self_closing=True, implicit=True)])),
  234. # </br>
  235. ([tokens.TagOpenOpen(invalid=True), tokens.Text(text="br"),
  236. tokens.TagCloseSelfclose(padding="", implicit=True)],
  237. wrap([Tag(wraptext("br"), self_closing=True, invalid=True,
  238. implicit=True)])),
  239. # </br/>
  240. ([tokens.TagOpenOpen(invalid=True), tokens.Text(text="br"),
  241. tokens.TagCloseSelfclose(padding="")],
  242. wrap([Tag(wraptext("br"), self_closing=True, invalid=True)])),
  243. # <ref name={{abc}} foo="bar {{baz}}" abc={{de}}f ghi=j{{k}}{{l}}
  244. # mno = '{{p}} [[q]] {{r}}'>[[Source]]</ref>
  245. ([tokens.TagOpenOpen(), tokens.Text(text="ref"),
  246. tokens.TagAttrStart(pad_first=" ", pad_before_eq="",
  247. pad_after_eq=""),
  248. tokens.Text(text="name"), tokens.TagAttrEquals(),
  249. tokens.TemplateOpen(), tokens.Text(text="abc"),
  250. tokens.TemplateClose(),
  251. tokens.TagAttrStart(pad_first=" ", pad_before_eq="",
  252. pad_after_eq=""),
  253. tokens.Text(text="foo"), tokens.TagAttrEquals(),
  254. tokens.TagAttrQuote(char='"'), tokens.Text(text="bar "),
  255. tokens.TemplateOpen(), tokens.Text(text="baz"),
  256. tokens.TemplateClose(),
  257. tokens.TagAttrStart(pad_first=" ", pad_before_eq="",
  258. pad_after_eq=""),
  259. tokens.Text(text="abc"), tokens.TagAttrEquals(),
  260. tokens.TemplateOpen(), tokens.Text(text="de"),
  261. tokens.TemplateClose(), tokens.Text(text="f"),
  262. tokens.TagAttrStart(pad_first=" ", pad_before_eq="",
  263. pad_after_eq=""),
  264. tokens.Text(text="ghi"), tokens.TagAttrEquals(),
  265. tokens.Text(text="j"), tokens.TemplateOpen(),
  266. tokens.Text(text="k"), tokens.TemplateClose(),
  267. tokens.TemplateOpen(), tokens.Text(text="l"),
  268. tokens.TemplateClose(),
  269. tokens.TagAttrStart(pad_first=" \n ", pad_before_eq=" ",
  270. pad_after_eq=" "),
  271. tokens.Text(text="mno"), tokens.TagAttrEquals(),
  272. tokens.TagAttrQuote(char="'"), tokens.TemplateOpen(),
  273. tokens.Text(text="p"), tokens.TemplateClose(),
  274. tokens.Text(text=" "), tokens.WikilinkOpen(),
  275. tokens.Text(text="q"), tokens.WikilinkClose(),
  276. tokens.Text(text=" "), tokens.TemplateOpen(),
  277. tokens.Text(text="r"), tokens.TemplateClose(),
  278. tokens.TagCloseOpen(padding=""), tokens.WikilinkOpen(),
  279. tokens.Text(text="Source"), tokens.WikilinkClose(),
  280. tokens.TagOpenClose(), tokens.Text(text="ref"),
  281. tokens.TagCloseClose()],
  282. wrap([Tag(wraptext("ref"), wrap([Wikilink(wraptext("Source"))]), [
  283. Attribute(wraptext("name"),
  284. wrap([Template(wraptext("abc"))]), None),
  285. Attribute(wraptext("foo"), wrap([Text("bar "),
  286. Template(wraptext("baz"))]), pad_first=" "),
  287. Attribute(wraptext("abc"), wrap([Template(wraptext("de")),
  288. Text("f")]), None),
  289. Attribute(wraptext("ghi"), wrap([Text("j"),
  290. Template(wraptext("k")),
  291. Template(wraptext("l"))]), None),
  292. Attribute(wraptext("mno"), wrap([Template(wraptext("p")),
  293. Text(" "), Wikilink(wraptext("q")), Text(" "),
  294. Template(wraptext("r"))]), "'", " \n ", " ",
  295. " ")])])),
  296. # "''italic text''"
  297. ([tokens.TagOpenOpen(wiki_markup="''"), tokens.Text(text="i"),
  298. tokens.TagCloseOpen(), tokens.Text(text="italic text"),
  299. tokens.TagOpenClose(), tokens.Text(text="i"),
  300. tokens.TagCloseClose()],
  301. wrap([Tag(wraptext("i"), wraptext("italic text"),
  302. wiki_markup="''")])),
  303. # * bullet
  304. ([tokens.TagOpenOpen(wiki_markup="*"), tokens.Text(text="li"),
  305. tokens.TagCloseSelfclose(), tokens.Text(text=" bullet")],
  306. wrap([Tag(wraptext("li"), wiki_markup="*", self_closing=True),
  307. Text(" bullet")])),
  308. ])
  309. def test_tag(self, builder, test, valid):
  310. """tests for building Tag nodes"""
  311. self.assertWikicodeEqual(valid, builder.build(test))
  312. def test_integration(self, builder):
  313. """a test for building a combination of templates together"""
  314. # {{{{{{{{foo}}bar|baz=biz}}buzz}}usr|{{bin}}}}
  315. test = [tokens.TemplateOpen(), tokens.TemplateOpen(),
  316. tokens.TemplateOpen(), tokens.TemplateOpen(),
  317. tokens.Text(text="foo"), tokens.TemplateClose(),
  318. tokens.Text(text="bar"), tokens.TemplateParamSeparator(),
  319. tokens.Text(text="baz"), tokens.TemplateParamEquals(),
  320. tokens.Text(text="biz"), tokens.TemplateClose(),
  321. tokens.Text(text="buzz"), tokens.TemplateClose(),
  322. tokens.Text(text="usr"), tokens.TemplateParamSeparator(),
  323. tokens.TemplateOpen(), tokens.Text(text="bin"),
  324. tokens.TemplateClose(), tokens.TemplateClose()]
  325. valid = wrap(
  326. [Template(wrap([Template(wrap([Template(wrap([Template(wraptext(
  327. "foo")), Text("bar")]), params=[Parameter(wraptext("baz"),
  328. wraptext("biz"))]), Text("buzz")])), Text("usr")]), params=[
  329. Parameter(wraptext("1"), wrap([Template(wraptext("bin"))]),
  330. showkey=False)])])
  331. self.assertWikicodeEqual(valid, builder.build(test))
  332. def test_integration2(self, builder):
  333. """an even more audacious test for building a horrible wikicode mess"""
  334. # {{a|b|{{c|[[d]]{{{e}}}}}}}[[f|{{{g}}}<!--h-->]]{{i|j=&nbsp;}}
  335. test = [tokens.TemplateOpen(), tokens.Text(text="a"),
  336. tokens.TemplateParamSeparator(), tokens.Text(text="b"),
  337. tokens.TemplateParamSeparator(), tokens.TemplateOpen(),
  338. tokens.Text(text="c"), tokens.TemplateParamSeparator(),
  339. tokens.WikilinkOpen(), tokens.Text(text="d"),
  340. tokens.WikilinkClose(), tokens.ArgumentOpen(),
  341. tokens.Text(text="e"), tokens.ArgumentClose(),
  342. tokens.TemplateClose(), tokens.TemplateClose(),
  343. tokens.WikilinkOpen(), tokens.Text(text="f"),
  344. tokens.WikilinkSeparator(), tokens.ArgumentOpen(),
  345. tokens.Text(text="g"), tokens.ArgumentClose(),
  346. tokens.CommentStart(), tokens.Text(text="h"),
  347. tokens.CommentEnd(), tokens.WikilinkClose(),
  348. tokens.TemplateOpen(), tokens.Text(text="i"),
  349. tokens.TemplateParamSeparator(), tokens.Text(text="j"),
  350. tokens.TemplateParamEquals(), tokens.HTMLEntityStart(),
  351. tokens.Text(text="nbsp"), tokens.HTMLEntityEnd(),
  352. tokens.TemplateClose()]
  353. valid = wrap(
  354. [Template(wraptext("a"), params=[Parameter(wraptext("1"), wraptext(
  355. "b"), showkey=False), Parameter(wraptext("2"), wrap([Template(
  356. wraptext("c"), params=[Parameter(wraptext("1"), wrap([Wikilink(
  357. wraptext("d")), Argument(wraptext("e"))]), showkey=False)])]),
  358. showkey=False)]), Wikilink(wraptext("f"), wrap([Argument(wraptext(
  359. "g")), Comment("h")])), Template(wraptext("i"), params=[
  360. Parameter(wraptext("j"), wrap([HTMLEntity("nbsp",
  361. named=True)]))])])
  362. self.assertWikicodeEqual(valid, builder.build(test))
  363. @pytest.mark.parametrize("tokens", [
  364. [tokens.TemplateOpen(), tokens.TemplateParamSeparator()],
  365. [tokens.TemplateOpen()], [tokens.ArgumentOpen()],
  366. [tokens.WikilinkOpen()], [tokens.ExternalLinkOpen()],
  367. [tokens.HeadingStart()], [tokens.CommentStart()],
  368. [tokens.TagOpenOpen(), tokens.TagAttrStart()],
  369. [tokens.TagOpenOpen()]
  370. ])
  371. def test_parser_errors(self, builder, tokens):
  372. """test whether ParserError gets thrown for bad input"""
  373. with pytest.raises(ParserError):
  374. builder.build(tokens)
  375. def test_parser_errors_templateclose(self, builder):
  376. with pytest.raises(
  377. ParserError,
  378. match=r"_handle_token\(\) got unexpected TemplateClose"
  379. ):
  380. builder.build([tokens.TemplateClose()])