A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

438 líneas
18 KiB

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