A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

test_tag.py 16 KiB

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