A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

440 linhas
18 KiB

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