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.
 
 
 
 

422 regels
17 KiB

  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. from types import GeneratorType
  24. import unittest
  25. from mwparserfromhell.compat import bytes, py3k, range, str
  26. from mwparserfromhell.string_mixin import StringMixIn
  27. class _FakeString(StringMixIn):
  28. def __init__(self, data):
  29. self._data = data
  30. def __unicode__(self):
  31. return self._data
  32. class TestStringMixIn(unittest.TestCase):
  33. """Test cases for the StringMixIn class."""
  34. def test_docs(self):
  35. """make sure the various methods of StringMixIn have docstrings"""
  36. methods = [
  37. "capitalize", "center", "count", "encode", "endswith",
  38. "expandtabs", "find", "format", "index", "isalnum", "isalpha",
  39. "isdecimal", "isdigit", "islower", "isnumeric", "isspace",
  40. "istitle", "isupper", "join", "ljust", "lower", "lstrip",
  41. "partition", "replace", "rfind", "rindex", "rjust", "rpartition",
  42. "rsplit", "rstrip", "split", "splitlines", "startswith", "strip",
  43. "swapcase", "title", "translate", "upper", "zfill"]
  44. if py3k:
  45. methods.extend(["casefold", "format_map", "isidentifier",
  46. "isprintable", "maketrans"])
  47. else:
  48. methods.append("decode")
  49. for meth in methods:
  50. expected = getattr(str, meth).__doc__
  51. actual = getattr(StringMixIn, meth).__doc__
  52. self.assertEquals(expected, actual)
  53. def test_types(self):
  54. """make sure StringMixIns convert to different types correctly"""
  55. fstr = _FakeString("fake string")
  56. self.assertEquals(str(fstr), "fake string")
  57. self.assertEquals(bytes(fstr), b"fake string")
  58. if py3k:
  59. self.assertEquals(repr(fstr), "'fake string'")
  60. else:
  61. self.assertEquals(repr(fstr), b"u'fake string'")
  62. self.assertIsInstance(str(fstr), str)
  63. self.assertIsInstance(bytes(fstr), bytes)
  64. if py3k:
  65. self.assertIsInstance(repr(fstr), str)
  66. else:
  67. self.assertIsInstance(repr(fstr), bytes)
  68. def test_comparisons(self):
  69. """make sure comparison operators work"""
  70. str1 = _FakeString("this is a fake string")
  71. str2 = _FakeString("this is a fake string")
  72. str3 = _FakeString("fake string, this is")
  73. str4 = "this is a fake string"
  74. str5 = "fake string, this is"
  75. self.assertFalse(str1 > str2)
  76. self.assertTrue(str1 >= str2)
  77. self.assertTrue(str1 == str2)
  78. self.assertFalse(str1 != str2)
  79. self.assertFalse(str1 < str2)
  80. self.assertTrue(str1 <= str2)
  81. self.assertTrue(str1 > str3)
  82. self.assertTrue(str1 >= str3)
  83. self.assertFalse(str1 == str3)
  84. self.assertTrue(str1 != str3)
  85. self.assertFalse(str1 < str3)
  86. self.assertFalse(str1 <= str3)
  87. self.assertFalse(str1 > str4)
  88. self.assertTrue(str1 >= str4)
  89. self.assertTrue(str1 == str4)
  90. self.assertFalse(str1 != str4)
  91. self.assertFalse(str1 < str4)
  92. self.assertTrue(str1 <= str4)
  93. self.assertTrue(str1 > str5)
  94. self.assertTrue(str1 >= str5)
  95. self.assertFalse(str1 == str5)
  96. self.assertTrue(str1 != str5)
  97. self.assertFalse(str1 < str5)
  98. self.assertFalse(str1 <= str5)
  99. def test_other_magics(self):
  100. """test other magically implemented features, like len() and iter()"""
  101. str1 = _FakeString("fake string")
  102. str2 = _FakeString("")
  103. expected = ["f", "a", "k", "e", " ", "s", "t", "r", "i", "n", "g"]
  104. self.assertTrue(str1)
  105. self.assertFalse(str2)
  106. self.assertEquals(11, len(str1))
  107. self.assertEquals(0, len(str2))
  108. out = []
  109. for ch in str1:
  110. out.append(ch)
  111. self.assertEquals(expected, out)
  112. out = []
  113. for ch in str2:
  114. out.append(ch)
  115. self.assertEquals([], out)
  116. gen1 = iter(str1)
  117. gen2 = iter(str2)
  118. self.assertIsInstance(gen1, GeneratorType)
  119. self.assertIsInstance(gen2, GeneratorType)
  120. out = []
  121. for i in range(len(str1)):
  122. out.append(gen1.next())
  123. self.assertRaises(StopIteration, gen1.next)
  124. self.assertEquals(expected, out)
  125. self.assertRaises(StopIteration, gen2.next)
  126. self.assertEquals("gnirts ekaf", "".join(list(reversed(str1))))
  127. self.assertEquals([], list(reversed(str2)))
  128. self.assertEquals("f", str1[0])
  129. self.assertEquals(" ", str1[4])
  130. self.assertEquals("g", str1[10])
  131. self.assertEquals("n", str1[-2])
  132. self.assertRaises(IndexError, lambda: str1[11])
  133. self.assertRaises(IndexError, lambda: str2[0])
  134. self.assertTrue("k" in str1)
  135. self.assertTrue("fake" in str1)
  136. self.assertTrue("str" in str1)
  137. self.assertTrue("" in str1)
  138. self.assertTrue("" in str2)
  139. self.assertFalse("real" in str1)
  140. self.assertFalse("s" in str2)
  141. def test_other_methods(self):
  142. """test the remaining non-magic methods of StringMixIn"""
  143. str1 = _FakeString("fake string")
  144. self.assertEquals("Fake string", str1.capitalize())
  145. self.assertEquals(" fake string ", str1.center(15))
  146. self.assertEquals(" fake string ", str1.center(16))
  147. self.assertEquals("qqfake stringqq", str1.center(15, "q"))
  148. self.assertEquals(1, str1.count("e"))
  149. self.assertEquals(0, str1.count("z"))
  150. self.assertEquals(1, str1.count("r", 7))
  151. self.assertEquals(0, str1.count("r", 8))
  152. self.assertEquals(1, str1.count("r", 5, 9))
  153. self.assertEquals(0, str1.count("r", 5, 7))
  154. if not py3k:
  155. str2 = _FakeString("fo")
  156. self.assertEquals(str1, str1.decode())
  157. actual = _FakeString("\\U00010332\\U0001033f\\U00010344")
  158. self.assertEquals("𐌲𐌿𐍄", actual.decode("unicode_escape"))
  159. self.assertRaises(UnicodeError, str2.decode, "punycode")
  160. self.assertEquals("", str2.decode("punycode", "ignore"))
  161. str3 = _FakeString("𐌲𐌿𐍄")
  162. self.assertEquals(b"fake string", str1.encode())
  163. self.assertEquals(b"\xF0\x90\x8C\xB2\xF0\x90\x8C\xBF\xF0\x90\x8D\x84",
  164. str3.encode("utf8"))
  165. self.assertEquals(b"\xF0\x90\x8C\xB2\xF0\x90\x8C\xBF\xF0\x90\x8D\x84",
  166. str3.encode(encoding="utf8"))
  167. self.assertRaises(UnicodeEncodeError, str3.encode)
  168. self.assertRaises(UnicodeEncodeError, str3.encode, "ascii")
  169. self.assertRaises(UnicodeEncodeError, str3.encode, "ascii", "strict")
  170. self.assertRaises(UnicodeEncodeError, str3.encode, errors="strict")
  171. self.assertEquals("", str3.encode("ascii", "ignore"))
  172. self.assertEquals("", str3.encode(errors="ignore"))
  173. self.assertTrue(str1.endswith("ing"))
  174. self.assertFalse(str1.endswith("ingh"))
  175. str4 = _FakeString("\tfoobar")
  176. self.assertEquals("fake string", str1)
  177. self.assertEquals(" foobar", str4.expandtabs())
  178. self.assertEquals(" foobar", str4.expandtabs(4))
  179. self.assertEquals(3, str1.find("e"))
  180. self.assertEquals(-1, str1.find("z"))
  181. self.assertEquals(7, str1.find("r", 7))
  182. self.assertEquals(-1, str1.find("r", 8))
  183. self.assertEquals(7, str1.find("r", 5, 9))
  184. self.assertEquals(-1, str1.find("r", 5, 7))
  185. str5 = _FakeString("foo{0}baz")
  186. str6 = _FakeString("foo{abc}baz")
  187. str7 = _FakeString("foo{0}{abc}buzz")
  188. str8 = _FakeString("{0}{1}")
  189. self.assertEquals("fake string", str1.format())
  190. self.assertEquals("foobarbaz", str5.format("bar"))
  191. self.assertEquals("foobarbaz", str6.format(abc="bar"))
  192. self.assertEquals("foobarbazbuzz", str7.format("bar", abc="baz"))
  193. self.assertRaises(IndexError, str8.format, "abc")
  194. if py3k:
  195. self.assertEquals("fake string", str1.format_map({}))
  196. self.assertEquals("foobarbaz", str6.format_map({"abc": "bar"}))
  197. self.assertRaises(ValueError, str5.format_map, {0: "abc"})
  198. self.assertEquals(3, str1.index("e"))
  199. self.assertRaises(ValueError, str1.index, "z")
  200. self.assertEquals(7, str1.index("r", 7))
  201. self.assertRaises(ValueError, str1.index, "r", 8)
  202. self.assertEquals(7, str1.index("r", 5, 9))
  203. self.assertRaises(ValueError, str1.index, "r", 5, 7)
  204. str9 = _FakeString("foobar")
  205. str10 = _FakeString("foobar123")
  206. str11 = _FakeString("foo bar")
  207. self.assertTrue(str9.isalnum())
  208. self.assertTrue(str10.isalnum())
  209. self.assertFalse(str11.isalnum())
  210. self.assertTrue(str9.isalpha())
  211. self.assertFalse(str10.isalpha())
  212. self.assertFalse(str11.isalpha())
  213. str12 = _FakeString("123")
  214. str13 = _FakeString("\u2155")
  215. str14 = _FakeString("\u00B2")
  216. self.assertFalse(str9.isdecimal())
  217. self.assertTrue(str12.isdecimal())
  218. self.assertFalse(str13.isdecimal())
  219. self.assertFalse(str14.isdecimal())
  220. self.assertFalse(str9.isdigit())
  221. self.assertTrue(str12.isdigit())
  222. self.assertFalse(str13.isdigit())
  223. self.assertTrue(str14.isdigit())
  224. if py3k:
  225. self.assertTrue(str9.isidentifier())
  226. self.assertTrue(str10.isidentifier())
  227. self.assertFalse(str11.isidentifier())
  228. self.assertFalse(str12.isidentifier())
  229. str15 = _FakeString("")
  230. str16 = _FakeString("FooBar")
  231. self.assertTrue(str9.islower())
  232. self.assertFalse(str15.islower())
  233. self.assertFalse(str16.islower())
  234. self.assertFalse(str9.isnumeric())
  235. self.assertTrue(str12.isnumeric())
  236. self.assertTrue(str13.isnumeric())
  237. self.assertTrue(str14.isnumeric())
  238. if py3k:
  239. str16B = _FakeString("\x01\x02")
  240. self.assertTrue(str9.isprintable())
  241. self.assertTrue(str13.isprintable())
  242. self.assertTrue(str14.isprintable())
  243. self.assertTrue(str15.isprintable())
  244. self.assertFalse(str16B.isprintable())
  245. str17 = _FakeString(" ")
  246. str18 = _FakeString("\t \t \r\n")
  247. self.assertFalse(str1.isspace())
  248. self.assertFalse(str9.isspace())
  249. self.assertTrue(str17.isspace())
  250. self.assertTrue(str18.isspace())
  251. str19 = _FakeString("This Sentence Looks Like A Title")
  252. str20 = _FakeString("This sentence doesn't LookLikeATitle")
  253. self.assertFalse(str15.istitle())
  254. self.assertTrue(str19.istitle())
  255. self.assertFalse(str20.istitle())
  256. str21 = _FakeString("FOOBAR")
  257. self.assertFalse(str9.isupper())
  258. self.assertFalse(str15.isupper())
  259. self.assertTrue(str21.isupper())
  260. self.assertEquals("foobar", str15.join(["foo", "bar"]))
  261. self.assertEquals("foo123bar123baz", str12.join(("foo", "bar", "baz")))
  262. self.assertEquals("fake string ", str1.ljust(15))
  263. self.assertEquals("fake string ", str1.ljust(16))
  264. self.assertEquals("fake stringqqqq", str1.ljust(15, "q"))
  265. str22 = _FakeString("ß")
  266. self.assertEquals("", str15.lower())
  267. self.assertEquals("foobar", str16.lower())
  268. self.assertEquals("ß", str22.lower())
  269. if py3k:
  270. self.assertEquals("", str15.casefold())
  271. self.assertEquals("foobar", str16.casefold())
  272. self.assertEquals("ss", str22.casefold())
  273. str23 = _FakeString(" fake string ")
  274. self.assertEquals("fake string", str1.lstrip())
  275. self.assertEquals("fake string ", str23.lstrip())
  276. self.assertEquals("ke string", str1.lstrip("abcdef"))
  277. self.assertEquals(("fa", "ke", " string"), str1.partition("ke"))
  278. self.assertEquals(("fake string", "", ""), str1.partition("asdf"))
  279. str24 = _FakeString("boo foo moo")
  280. self.assertEquals("real string", str1.replace("fake", "real"))
  281. self.assertEquals("bu fu moo", str24.replace("oo", "u", 2))
  282. self.assertEquals(3, str1.rfind("e"))
  283. self.assertEquals(-1, str1.rfind("z"))
  284. self.assertEquals(7, str1.rfind("r", 7))
  285. self.assertEquals(-1, str1.rfind("r", 8))
  286. self.assertEquals(7, str1.rfind("r", 5, 9))
  287. self.assertEquals(-1, str1.rfind("r", 5, 7))
  288. self.assertEquals(3, str1.rindex("e"))
  289. self.assertRaises(ValueError, str1.rindex, "z")
  290. self.assertEquals(7, str1.rindex("r", 7))
  291. self.assertRaises(ValueError, str1.rindex, "r", 8)
  292. self.assertEquals(7, str1.rindex("r", 5, 9))
  293. self.assertRaises(ValueError, str1.rindex, "r", 5, 7)
  294. self.assertEquals(" fake string", str1.rjust(15))
  295. self.assertEquals(" fake string", str1.rjust(16))
  296. self.assertEquals("qqqqfake string", str1.rjust(15, "q"))
  297. self.assertEquals(("fa", "ke", " string"), str1.rpartition("ke"))
  298. self.assertEquals(("", "", "fake string"), str1.rpartition("asdf"))
  299. str25 = _FakeString(" this is a sentence with whitespace ")
  300. actual = ["this", "is", "a", "sentence", "with", "whitespace"]
  301. self.assertEquals(actual, str25.rsplit())
  302. self.assertEquals(actual, str25.rsplit(None))
  303. actual = ["", "", "", "this", "is", "a", "", "", "sentence", "with",
  304. "", "whitespace", ""]
  305. self.assertEquals(actual, str25.rsplit(" "))
  306. actual = [" this is a", "sentence", "with", "whitespace"]
  307. self.assertEquals(actual, str25.rsplit(None, 3))
  308. actual = [" this is a sentence with", "", "whitespace", ""]
  309. self.assertEquals(actual, str25.rsplit(" ", 3))
  310. if py3k:
  311. self.assertEquals(actual, str25.rsplit(maxsplit=3))
  312. self.assertEquals("fake string", str1.rstrip())
  313. self.assertEquals(" fake string", str23.rstrip())
  314. self.assertEquals("fake stri", str1.rstrip("ngr"))
  315. actual = ["this", "is", "a", "sentence", "with", "whitespace"]
  316. self.assertEquals(actual, str25.split())
  317. self.assertEquals(actual, str25.split(None))
  318. actual = ["", "", "", "this", "is", "a", "", "", "sentence", "with",
  319. "", "whitespace", ""]
  320. self.assertEquals(actual, str25.split(" "))
  321. actual = ["this", "is", "a", "sentence with whitespace "]
  322. self.assertEquals(actual, str25.split(None, 3))
  323. actual = ["", "", "", "this is a sentence with whitespace "]
  324. self.assertEquals(actual, str25.split(" ", 3))
  325. if py3k:
  326. self.assertEquals(actual, str25.split(maxsplit=3))
  327. str26 = _FakeString("lines\nof\ntext\r\nare\r\npresented\nhere")
  328. self.assertEquals(["lines", "of", "text", "are", "presented", "here"],
  329. str26.splitlines())
  330. self.assertEquals(["lines\n", "of\n", "text\r\n", "are\r\n",
  331. "presented\n", "here"], str26.splitlines(True))
  332. self.assertTrue(str1.startswith("fake"))
  333. self.assertFalse(str1.startswith("faker"))
  334. self.assertEquals("fake string", str1.strip())
  335. self.assertEquals("fake string", str23.strip())
  336. self.assertEquals("ke stri", str1.strip("abcdefngr"))
  337. self.assertEquals("fOObAR", str16.swapcase())
  338. self.assertEquals("Fake String", str1.title())
  339. if py3k:
  340. table1 = str.maketrans({97: "1", 101: "2", 105: "3", 111: "4",
  341. 117: "5"})
  342. table2 = str.maketrans("aeiou", "12345")
  343. table3 = str.maketrans("aeiou", "12345", "rts")
  344. self.assertEquals("f1k2 str3ng", str1.translate(table1))
  345. self.assertEquals("f1k2 str3ng", str1.translate(table2))
  346. self.assertEquals("f1k2 3ng", str1.translate(table3))
  347. else:
  348. table = {97: "1", 101: "2", 105: "3", 111: "4", 117: "5"}
  349. self.assertEquals("f1k2 str3ng", str1.translate(table))
  350. self.assertEquals("", str15.upper())
  351. self.assertEquals("FOOBAR", str16.upper())
  352. self.assertEquals("123", str12.zfill(3))
  353. self.assertEquals("000123", str12.zfill(6))
  354. if __name__ == "__main__":
  355. unittest.main(verbosity=2)