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.

test_tag.py 14 KiB

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