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.
 
 
 
 

439 lines
21 KiB

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