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.

11 年之前
11 年之前
11 年之前
11 年之前
11 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #
  2. # Copyright (C) 2012-2016 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 unittest
  22. from mwparserfromhell.nodes import Tag, Template, Text
  23. from mwparserfromhell.nodes.extras import Attribute
  24. from ._test_tree_equality import TreeEqualityTestCase, wrap, wraptext
  25. agen = lambda name, value: Attribute(wraptext(name), wraptext(value))
  26. agennv = lambda name: Attribute(wraptext(name))
  27. agennq = lambda name, value: Attribute(wraptext(name), wraptext(value), None)
  28. agenp = lambda name, v, a, b, c: Attribute(wraptext(name), v, '"', a, b, c)
  29. agenpnv = lambda name, a, b, c: Attribute(wraptext(name), None, '"', a, b, c)
  30. class TestTag(TreeEqualityTestCase):
  31. """Test cases for the Tag node."""
  32. def test_unicode(self):
  33. """test Tag.__unicode__()"""
  34. node1 = Tag(wraptext("ref"))
  35. node2 = Tag(wraptext("span"), wraptext("foo"),
  36. [agen("style", "color: red;")])
  37. node3 = Tag(wraptext("ref"),
  38. attrs=[agennq("name", "foo"),
  39. agenpnv("some_attr", " ", "", "")],
  40. self_closing=True)
  41. node4 = Tag(wraptext("br"), self_closing=True, padding=" ")
  42. node5 = Tag(wraptext("br"), self_closing=True, implicit=True)
  43. node6 = Tag(wraptext("br"), self_closing=True, invalid=True,
  44. implicit=True)
  45. node7 = Tag(wraptext("br"), self_closing=True, invalid=True,
  46. padding=" ")
  47. node8 = Tag(wraptext("hr"), wiki_markup="----", self_closing=True)
  48. node9 = Tag(wraptext("i"), wraptext("italics!"), wiki_markup="''")
  49. self.assertEqual("<ref></ref>", str(node1))
  50. self.assertEqual('<span style="color: red;">foo</span>', str(node2))
  51. self.assertEqual("<ref name=foo some_attr/>", str(node3))
  52. self.assertEqual("<br />", str(node4))
  53. self.assertEqual("<br>", str(node5))
  54. self.assertEqual("</br>", str(node6))
  55. self.assertEqual("</br />", str(node7))
  56. self.assertEqual("----", str(node8))
  57. self.assertEqual("''italics!''", str(node9))
  58. def test_children(self):
  59. """test Tag.__children__()"""
  60. # <ref>foobar</ref>
  61. node1 = Tag(wraptext("ref"), wraptext("foobar"))
  62. # '''bold text'''
  63. node2 = Tag(wraptext("b"), wraptext("bold text"), wiki_markup="'''")
  64. # <img id="foo" class="bar" selected />
  65. node3 = Tag(wraptext("img"),
  66. attrs=[agen("id", "foo"), agen("class", "bar"),
  67. agennv("selected")],
  68. self_closing=True, padding=" ")
  69. gen1 = node1.__children__()
  70. gen2 = node2.__children__()
  71. gen3 = node3.__children__()
  72. self.assertEqual(node1.tag, next(gen1))
  73. self.assertEqual(node3.tag, next(gen3))
  74. self.assertEqual(node3.attributes[0].name, next(gen3))
  75. self.assertEqual(node3.attributes[0].value, next(gen3))
  76. self.assertEqual(node3.attributes[1].name, next(gen3))
  77. self.assertEqual(node3.attributes[1].value, next(gen3))
  78. self.assertEqual(node3.attributes[2].name, next(gen3))
  79. self.assertEqual(node1.contents, next(gen1))
  80. self.assertEqual(node2.contents, next(gen2))
  81. self.assertEqual(node1.closing_tag, next(gen1))
  82. self.assertRaises(StopIteration, next, gen1)
  83. self.assertRaises(StopIteration, next, gen2)
  84. self.assertRaises(StopIteration, next, gen3)
  85. def test_strip(self):
  86. """test Tag.__strip__()"""
  87. node1 = Tag(wraptext("i"), wraptext("foobar"))
  88. node2 = Tag(wraptext("math"), wraptext("foobar"))
  89. node3 = Tag(wraptext("br"), self_closing=True)
  90. self.assertEqual("foobar", node1.__strip__())
  91. self.assertEqual(None, node2.__strip__())
  92. self.assertEqual(None, node3.__strip__())
  93. def test_showtree(self):
  94. """test Tag.__showtree__()"""
  95. output = []
  96. getter, marker = object(), object()
  97. get = lambda code: output.append((getter, code))
  98. mark = lambda: output.append(marker)
  99. node1 = Tag(wraptext("ref"), wraptext("text"),
  100. [agen("name", "foo"), agennv("selected")])
  101. node2 = Tag(wraptext("br"), self_closing=True, padding=" ")
  102. node3 = Tag(wraptext("br"), self_closing=True, invalid=True,
  103. implicit=True, padding=" ")
  104. node1.__showtree__(output.append, get, mark)
  105. node2.__showtree__(output.append, get, mark)
  106. node3.__showtree__(output.append, get, mark)
  107. valid = [
  108. "<", (getter, node1.tag), (getter, node1.attributes[0].name),
  109. " = ", marker, (getter, node1.attributes[0].value),
  110. (getter, node1.attributes[1].name), ">", (getter, node1.contents),
  111. "</", (getter, node1.closing_tag), ">", "<", (getter, node2.tag),
  112. "/>", "</", (getter, node3.tag), ">"]
  113. self.assertEqual(valid, output)
  114. def test_tag(self):
  115. """test getter/setter for the tag attribute"""
  116. tag = wraptext("ref")
  117. node = Tag(tag, wraptext("text"))
  118. self.assertIs(tag, node.tag)
  119. self.assertIs(tag, node.closing_tag)
  120. node.tag = "span"
  121. self.assertWikicodeEqual(wraptext("span"), node.tag)
  122. self.assertWikicodeEqual(wraptext("span"), node.closing_tag)
  123. self.assertEqual("<span>text</span>", node)
  124. def test_contents(self):
  125. """test getter/setter for the contents attribute"""
  126. contents = wraptext("text")
  127. node = Tag(wraptext("ref"), contents)
  128. self.assertIs(contents, node.contents)
  129. node.contents = "text and a {{template}}"
  130. parsed = wrap([Text("text and a "), Template(wraptext("template"))])
  131. self.assertWikicodeEqual(parsed, node.contents)
  132. self.assertEqual("<ref>text and a {{template}}</ref>", node)
  133. def test_attributes(self):
  134. """test getter for the attributes attribute"""
  135. attrs = [agen("name", "bar")]
  136. node1 = Tag(wraptext("ref"), wraptext("foo"))
  137. node2 = Tag(wraptext("ref"), wraptext("foo"), attrs)
  138. self.assertEqual([], node1.attributes)
  139. self.assertIs(attrs, node2.attributes)
  140. def test_wiki_markup(self):
  141. """test getter/setter for the wiki_markup attribute"""
  142. node = Tag(wraptext("i"), wraptext("italic text"))
  143. self.assertIs(None, node.wiki_markup)
  144. node.wiki_markup = "''"
  145. self.assertEqual("''", node.wiki_markup)
  146. self.assertEqual("''italic text''", node)
  147. node.wiki_markup = False
  148. self.assertFalse(node.wiki_markup)
  149. self.assertEqual("<i>italic text</i>", node)
  150. def test_self_closing(self):
  151. """test getter/setter for the self_closing attribute"""
  152. node = Tag(wraptext("ref"), wraptext("foobar"))
  153. self.assertFalse(node.self_closing)
  154. node.self_closing = True
  155. self.assertTrue(node.self_closing)
  156. self.assertEqual("<ref/>", node)
  157. node.self_closing = 0
  158. self.assertFalse(node.self_closing)
  159. self.assertEqual("<ref>foobar</ref>", node)
  160. def test_invalid(self):
  161. """test getter/setter for the invalid attribute"""
  162. node = Tag(wraptext("br"), self_closing=True, implicit=True)
  163. self.assertFalse(node.invalid)
  164. node.invalid = True
  165. self.assertTrue(node.invalid)
  166. self.assertEqual("</br>", node)
  167. node.invalid = 0
  168. self.assertFalse(node.invalid)
  169. self.assertEqual("<br>", node)
  170. def test_implicit(self):
  171. """test getter/setter for the implicit attribute"""
  172. node = Tag(wraptext("br"), self_closing=True)
  173. self.assertFalse(node.implicit)
  174. node.implicit = True
  175. self.assertTrue(node.implicit)
  176. self.assertEqual("<br>", node)
  177. node.implicit = 0
  178. self.assertFalse(node.implicit)
  179. self.assertEqual("<br/>", node)
  180. def test_padding(self):
  181. """test getter/setter for the padding attribute"""
  182. node = Tag(wraptext("ref"), wraptext("foobar"))
  183. self.assertEqual("", node.padding)
  184. node.padding = " "
  185. self.assertEqual(" ", node.padding)
  186. self.assertEqual("<ref >foobar</ref>", node)
  187. node.padding = None
  188. self.assertEqual("", node.padding)
  189. self.assertEqual("<ref>foobar</ref>", node)
  190. self.assertRaises(ValueError, setattr, node, "padding", True)
  191. def test_closing_tag(self):
  192. """test getter/setter for the closing_tag attribute"""
  193. tag = wraptext("ref")
  194. node = Tag(tag, wraptext("foobar"))
  195. self.assertIs(tag, node.closing_tag)
  196. node.closing_tag = "ref {{ignore me}}"
  197. parsed = wrap([Text("ref "), Template(wraptext("ignore me"))])
  198. self.assertWikicodeEqual(parsed, node.closing_tag)
  199. self.assertEqual("<ref>foobar</ref {{ignore me}}>", node)
  200. def test_wiki_style_separator(self):
  201. """test getter/setter for wiki_style_separator attribute"""
  202. node = Tag(wraptext("table"), wraptext("\n"))
  203. self.assertIs(None, node.wiki_style_separator)
  204. node.wiki_style_separator = "|"
  205. self.assertEqual("|", node.wiki_style_separator)
  206. node.wiki_markup = "{"
  207. self.assertEqual("{|\n{", node)
  208. node2 = Tag(wraptext("table"), wraptext("\n"), wiki_style_separator="|")
  209. self.assertEqual("|", node.wiki_style_separator)
  210. def test_closing_wiki_markup(self):
  211. """test getter/setter for closing_wiki_markup attribute"""
  212. node = Tag(wraptext("table"), wraptext("\n"))
  213. self.assertIs(None, node.closing_wiki_markup)
  214. node.wiki_markup = "{|"
  215. self.assertEqual("{|", node.closing_wiki_markup)
  216. node.closing_wiki_markup = "|}"
  217. self.assertEqual("|}", node.closing_wiki_markup)
  218. self.assertEqual("{|\n|}", node)
  219. node.wiki_markup = "!!"
  220. self.assertEqual("|}", node.closing_wiki_markup)
  221. self.assertEqual("!!\n|}", node)
  222. node.wiki_markup = False
  223. self.assertFalse(node.closing_wiki_markup)
  224. self.assertEqual("<table>\n</table>", node)
  225. node2 = Tag(wraptext("table"), wraptext("\n"),
  226. attrs=[agen("id", "foo")], wiki_markup="{|",
  227. closing_wiki_markup="|}")
  228. self.assertEqual("|}", node2.closing_wiki_markup)
  229. self.assertEqual('{| id="foo"\n|}', node2)
  230. def test_has(self):
  231. """test Tag.has()"""
  232. node = Tag(wraptext("ref"), wraptext("cite"), [agen("name", "foo")])
  233. self.assertTrue(node.has("name"))
  234. self.assertTrue(node.has(" name "))
  235. self.assertTrue(node.has(wraptext("name")))
  236. self.assertFalse(node.has("Name"))
  237. self.assertFalse(node.has("foo"))
  238. attrs = [agen("id", "foo"), agenp("class", "bar", " ", "\n", "\n"),
  239. agen("foo", "bar"), agenpnv("foo", " ", " \n ", " \t")]
  240. node2 = Tag(wraptext("div"), attrs=attrs, self_closing=True)
  241. self.assertTrue(node2.has("id"))
  242. self.assertTrue(node2.has("class"))
  243. self.assertTrue(node2.has(attrs[1].pad_first + str(attrs[1].name) +
  244. attrs[1].pad_before_eq))
  245. self.assertTrue(node2.has(attrs[3]))
  246. self.assertTrue(node2.has(str(attrs[3])))
  247. self.assertFalse(node2.has("idclass"))
  248. self.assertFalse(node2.has("id class"))
  249. self.assertFalse(node2.has("id=foo"))
  250. def test_get(self):
  251. """test Tag.get()"""
  252. attrs = [agen("name", "foo")]
  253. node = Tag(wraptext("ref"), wraptext("cite"), attrs)
  254. self.assertIs(attrs[0], node.get("name"))
  255. self.assertIs(attrs[0], node.get(" name "))
  256. self.assertIs(attrs[0], node.get(wraptext("name")))
  257. self.assertRaises(ValueError, node.get, "Name")
  258. self.assertRaises(ValueError, node.get, "foo")
  259. attrs = [agen("id", "foo"), agenp("class", "bar", " ", "\n", "\n"),
  260. agen("foo", "bar"), agenpnv("foo", " ", " \n ", " \t")]
  261. node2 = Tag(wraptext("div"), attrs=attrs, self_closing=True)
  262. self.assertIs(attrs[0], node2.get("id"))
  263. self.assertIs(attrs[1], node2.get("class"))
  264. self.assertIs(attrs[1], node2.get(
  265. attrs[1].pad_first + str(attrs[1].name) + attrs[1].pad_before_eq))
  266. self.assertIs(attrs[3], node2.get(attrs[3]))
  267. self.assertIs(attrs[3], node2.get(str(attrs[3])))
  268. self.assertIs(attrs[3], node2.get(" foo"))
  269. self.assertRaises(ValueError, node2.get, "idclass")
  270. self.assertRaises(ValueError, node2.get, "id class")
  271. self.assertRaises(ValueError, node2.get, "id=foo")
  272. def test_add(self):
  273. """test Tag.add()"""
  274. node = Tag(wraptext("ref"), wraptext("cite"))
  275. node.add("name", "value")
  276. node.add("name", "value", quotes=None)
  277. node.add("name", "value", quotes="'")
  278. node.add("name")
  279. node.add(1, False)
  280. node.add("style", "{{foobar}}")
  281. node.add("name", "value", '"', "\n", " ", " ")
  282. attr1 = ' name="value"'
  283. attr2 = " name=value"
  284. attr3 = " name='value'"
  285. attr4 = " name"
  286. attr5 = ' 1="False"'
  287. attr6 = ' style="{{foobar}}"'
  288. attr7 = '\nname = "value"'
  289. self.assertEqual(attr1, node.attributes[0])
  290. self.assertEqual(attr2, node.attributes[1])
  291. self.assertEqual(attr3, node.attributes[2])
  292. self.assertEqual(attr4, node.attributes[3])
  293. self.assertEqual(attr5, node.attributes[4])
  294. self.assertEqual(attr6, node.attributes[5])
  295. self.assertEqual(attr7, node.attributes[6])
  296. self.assertEqual(attr7, node.get("name"))
  297. self.assertWikicodeEqual(wrap([Template(wraptext("foobar"))]),
  298. node.attributes[5].value)
  299. self.assertEqual("".join(("<ref", attr1, attr2, attr3, attr4, attr5,
  300. attr6, attr7, ">cite</ref>")), node)
  301. self.assertRaises(ValueError, node.add, "name", "foo", quotes="bar")
  302. self.assertRaises(ValueError, node.add, "name", "a bc d", quotes=None)
  303. def test_remove(self):
  304. """test Tag.remove()"""
  305. attrs = [agen("id", "foo"), agenp("class", "bar", " ", "\n", "\n"),
  306. agen("foo", "bar"), agenpnv("foo", " ", " \n ", " \t")]
  307. node = Tag(wraptext("div"), attrs=attrs, self_closing=True)
  308. node.remove("class")
  309. self.assertEqual('<div id="foo" foo="bar" foo \n />', node)
  310. node.remove("foo")
  311. self.assertEqual('<div id="foo"/>', node)
  312. self.assertRaises(ValueError, node.remove, "foo")
  313. node.remove("id")
  314. self.assertEqual('<div/>', node)
  315. if __name__ == "__main__":
  316. unittest.main(verbosity=2)