A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

test_string_mixin.py 18 KiB

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