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.

test_string_mixin.py 18 KiB

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