A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

test_string_mixin.py 16 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #
  2. # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. from sys import getdefaultencoding
  22. from types import GeneratorType
  23. import unittest
  24. from mwparserfromhell.string_mixin import StringMixIn
  25. class _FakeString(StringMixIn):
  26. def __init__(self, data):
  27. self._data = data
  28. def __unicode__(self):
  29. return self._data
  30. class TestStringMixIn(unittest.TestCase):
  31. """Test cases for the StringMixIn class."""
  32. def test_docs(self):
  33. """make sure the various methods of StringMixIn have docstrings"""
  34. methods = [
  35. "capitalize", "casefold", "center", "count", "encode", "endswith",
  36. "expandtabs", "find", "format", "format_map", "index", "isalnum",
  37. "isalpha", "isdecimal", "isdigit", "isidentifier", "islower",
  38. "isnumeric", "isprintable", "isspace", "istitle", "isupper",
  39. "join", "ljust", "lower", "lstrip", "maketrans", "partition",
  40. "replace", "rfind", "rindex", "rjust", "rpartition", "rsplit",
  41. "rstrip", "split", "splitlines", "startswith", "strip", "swapcase",
  42. "title", "translate", "upper", "zfill"
  43. ]
  44. for meth in methods:
  45. expected = getattr("foo", meth).__doc__
  46. actual = getattr(_FakeString("foo"), meth).__doc__
  47. self.assertEqual(expected, actual)
  48. def test_types(self):
  49. """make sure StringMixIns convert to different types correctly"""
  50. fstr = _FakeString("fake string")
  51. self.assertEqual(str(fstr), "fake string")
  52. self.assertEqual(bytes(fstr), b"fake string")
  53. self.assertEqual(repr(fstr), "'fake string'")
  54. self.assertIsInstance(str(fstr), str)
  55. self.assertIsInstance(bytes(fstr), bytes)
  56. self.assertIsInstance(repr(fstr), str)
  57. def test_comparisons(self):
  58. """make sure comparison operators work"""
  59. str1 = _FakeString("this is a fake string")
  60. str2 = _FakeString("this is a fake string")
  61. str3 = _FakeString("fake string, this is")
  62. str4 = "this is a fake string"
  63. str5 = "fake string, this is"
  64. self.assertLessEqual(str1, str2)
  65. self.assertGreaterEqual(str1, str2)
  66. self.assertEqual(str1, str2)
  67. self.assertEqual(str1, str2)
  68. self.assertGreaterEqual(str1, str2)
  69. self.assertLessEqual(str1, str2)
  70. self.assertGreater(str1, str3)
  71. self.assertGreaterEqual(str1, str3)
  72. self.assertNotEqual(str1, str3)
  73. self.assertNotEqual(str1, str3)
  74. self.assertGreaterEqual(str1, str3)
  75. self.assertGreater(str1, str3)
  76. self.assertLessEqual(str1, str4)
  77. self.assertGreaterEqual(str1, str4)
  78. self.assertEqual(str1, str4)
  79. self.assertEqual(str1, str4)
  80. self.assertGreaterEqual(str1, str4)
  81. self.assertLessEqual(str1, str4)
  82. self.assertLessEqual(str5, str1)
  83. self.assertLess(str5, str1)
  84. self.assertNotEqual(str5, str1)
  85. self.assertNotEqual(str5, str1)
  86. self.assertLess(str5, str1)
  87. self.assertLessEqual(str5, str1)
  88. def test_other_magics(self):
  89. """test other magically implemented features, like len() and iter()"""
  90. str1 = _FakeString("fake string")
  91. str2 = _FakeString("")
  92. expected = ["f", "a", "k", "e", " ", "s", "t", "r", "i", "n", "g"]
  93. self.assertTrue(str1)
  94. self.assertFalse(str2)
  95. self.assertEqual(11, len(str1))
  96. self.assertEqual(0, len(str2))
  97. out = []
  98. for ch in str1:
  99. out.append(ch)
  100. self.assertEqual(expected, out)
  101. out = []
  102. for ch in str2:
  103. out.append(ch)
  104. self.assertEqual([], out)
  105. gen1 = iter(str1)
  106. gen2 = iter(str2)
  107. self.assertIsInstance(gen1, GeneratorType)
  108. self.assertIsInstance(gen2, GeneratorType)
  109. out = []
  110. for i in range(len(str1)):
  111. out.append(next(gen1))
  112. self.assertRaises(StopIteration, next, gen1)
  113. self.assertEqual(expected, out)
  114. self.assertRaises(StopIteration, next, gen2)
  115. self.assertEqual("gnirts ekaf", "".join(list(reversed(str1))))
  116. self.assertEqual([], list(reversed(str2)))
  117. self.assertEqual("f", str1[0])
  118. self.assertEqual(" ", str1[4])
  119. self.assertEqual("g", str1[10])
  120. self.assertEqual("n", str1[-2])
  121. self.assertRaises(IndexError, lambda: str1[11])
  122. self.assertRaises(IndexError, lambda: str2[0])
  123. self.assertIn("k", str1)
  124. self.assertIn("fake", str1)
  125. self.assertIn("str", str1)
  126. self.assertIn("", str1)
  127. self.assertIn("", str2)
  128. self.assertNotIn("real", str1)
  129. self.assertNotIn("s", str2)
  130. def test_other_methods(self):
  131. """test the remaining non-magic methods of StringMixIn"""
  132. str1 = _FakeString("fake string")
  133. self.assertEqual("Fake string", str1.capitalize())
  134. self.assertEqual(" fake string ", str1.center(15))
  135. self.assertEqual(" fake string ", str1.center(16))
  136. self.assertEqual("qqfake stringqq", str1.center(15, "q"))
  137. self.assertEqual(1, str1.count("e"))
  138. self.assertEqual(0, str1.count("z"))
  139. self.assertEqual(1, str1.count("r", 7))
  140. self.assertEqual(0, str1.count("r", 8))
  141. self.assertEqual(1, str1.count("r", 5, 9))
  142. self.assertEqual(0, str1.count("r", 5, 7))
  143. str3 = _FakeString("𐌲𐌿𐍄")
  144. actual = b"\xF0\x90\x8C\xB2\xF0\x90\x8C\xBF\xF0\x90\x8D\x84"
  145. self.assertEqual(b"fake string", str1.encode())
  146. self.assertEqual(actual, str3.encode("utf-8"))
  147. self.assertEqual(actual, str3.encode(encoding="utf-8"))
  148. if getdefaultencoding() == "ascii":
  149. self.assertRaises(UnicodeEncodeError, str3.encode)
  150. elif getdefaultencoding() == "utf-8":
  151. self.assertEqual(actual, str3.encode())
  152. self.assertRaises(UnicodeEncodeError, str3.encode, "ascii")
  153. self.assertRaises(UnicodeEncodeError, str3.encode, "ascii", "strict")
  154. if getdefaultencoding() == "ascii":
  155. self.assertRaises(UnicodeEncodeError, str3.encode, errors="strict")
  156. elif getdefaultencoding() == "utf-8":
  157. self.assertEqual(actual, str3.encode(errors="strict"))
  158. self.assertEqual(b"", str3.encode("ascii", "ignore"))
  159. if getdefaultencoding() == "ascii":
  160. self.assertEqual(b"", str3.encode(errors="ignore"))
  161. elif getdefaultencoding() == "utf-8":
  162. self.assertEqual(actual, str3.encode(errors="ignore"))
  163. self.assertTrue(str1.endswith("ing"))
  164. self.assertFalse(str1.endswith("ingh"))
  165. str4 = _FakeString("\tfoobar")
  166. self.assertEqual("fake string", str1)
  167. self.assertEqual(" foobar", str4.expandtabs())
  168. self.assertEqual(" foobar", str4.expandtabs(4))
  169. self.assertEqual(3, str1.find("e"))
  170. self.assertEqual(-1, str1.find("z"))
  171. self.assertEqual(7, str1.find("r", 7))
  172. self.assertEqual(-1, str1.find("r", 8))
  173. self.assertEqual(7, str1.find("r", 5, 9))
  174. self.assertEqual(-1, str1.find("r", 5, 7))
  175. str5 = _FakeString("foo{0}baz")
  176. str6 = _FakeString("foo{abc}baz")
  177. str7 = _FakeString("foo{0}{abc}buzz")
  178. str8 = _FakeString("{0}{1}")
  179. self.assertEqual("fake string", str1.format())
  180. self.assertEqual("foobarbaz", str5.format("bar"))
  181. self.assertEqual("foobarbaz", str6.format(abc="bar"))
  182. self.assertEqual("foobarbazbuzz", str7.format("bar", abc="baz"))
  183. self.assertRaises(IndexError, str8.format, "abc")
  184. self.assertEqual("fake string", str1.format_map({}))
  185. self.assertEqual("foobarbaz", str6.format_map({"abc": "bar"}))
  186. self.assertRaises(ValueError, str5.format_map, {0: "abc"})
  187. self.assertEqual(3, str1.index("e"))
  188. self.assertRaises(ValueError, str1.index, "z")
  189. self.assertEqual(7, str1.index("r", 7))
  190. self.assertRaises(ValueError, str1.index, "r", 8)
  191. self.assertEqual(7, str1.index("r", 5, 9))
  192. self.assertRaises(ValueError, str1.index, "r", 5, 7)
  193. str9 = _FakeString("foobar")
  194. str10 = _FakeString("foobar123")
  195. str11 = _FakeString("foo bar")
  196. self.assertTrue(str9.isalnum())
  197. self.assertTrue(str10.isalnum())
  198. self.assertFalse(str11.isalnum())
  199. self.assertTrue(str9.isalpha())
  200. self.assertFalse(str10.isalpha())
  201. self.assertFalse(str11.isalpha())
  202. str12 = _FakeString("123")
  203. str13 = _FakeString("\u2155")
  204. str14 = _FakeString("\u00B2")
  205. self.assertFalse(str9.isdecimal())
  206. self.assertTrue(str12.isdecimal())
  207. self.assertFalse(str13.isdecimal())
  208. self.assertFalse(str14.isdecimal())
  209. self.assertFalse(str9.isdigit())
  210. self.assertTrue(str12.isdigit())
  211. self.assertFalse(str13.isdigit())
  212. self.assertTrue(str14.isdigit())
  213. self.assertTrue(str9.isidentifier())
  214. self.assertTrue(str10.isidentifier())
  215. self.assertFalse(str11.isidentifier())
  216. self.assertFalse(str12.isidentifier())
  217. str15 = _FakeString("")
  218. str16 = _FakeString("FooBar")
  219. self.assertTrue(str9.islower())
  220. self.assertFalse(str15.islower())
  221. self.assertFalse(str16.islower())
  222. self.assertFalse(str9.isnumeric())
  223. self.assertTrue(str12.isnumeric())
  224. self.assertTrue(str13.isnumeric())
  225. self.assertTrue(str14.isnumeric())
  226. str16B = _FakeString("\x01\x02")
  227. self.assertTrue(str9.isprintable())
  228. self.assertTrue(str13.isprintable())
  229. self.assertTrue(str14.isprintable())
  230. self.assertTrue(str15.isprintable())
  231. self.assertFalse(str16B.isprintable())
  232. str17 = _FakeString(" ")
  233. str18 = _FakeString("\t \t \r\n")
  234. self.assertFalse(str1.isspace())
  235. self.assertFalse(str9.isspace())
  236. self.assertTrue(str17.isspace())
  237. self.assertTrue(str18.isspace())
  238. str19 = _FakeString("This Sentence Looks Like A Title")
  239. str20 = _FakeString("This sentence doesn't LookLikeATitle")
  240. self.assertFalse(str15.istitle())
  241. self.assertTrue(str19.istitle())
  242. self.assertFalse(str20.istitle())
  243. str21 = _FakeString("FOOBAR")
  244. self.assertFalse(str9.isupper())
  245. self.assertFalse(str15.isupper())
  246. self.assertTrue(str21.isupper())
  247. self.assertEqual("foobar", str15.join(["foo", "bar"]))
  248. self.assertEqual("foo123bar123baz", str12.join(("foo", "bar", "baz")))
  249. self.assertEqual("fake string ", str1.ljust(15))
  250. self.assertEqual("fake string ", str1.ljust(16))
  251. self.assertEqual("fake stringqqqq", str1.ljust(15, "q"))
  252. str22 = _FakeString("ß")
  253. self.assertEqual("", str15.lower())
  254. self.assertEqual("foobar", str16.lower())
  255. self.assertEqual("ß", str22.lower())
  256. self.assertEqual("", str15.casefold())
  257. self.assertEqual("foobar", str16.casefold())
  258. self.assertEqual("ss", str22.casefold())
  259. str23 = _FakeString(" fake string ")
  260. self.assertEqual("fake string", str1.lstrip())
  261. self.assertEqual("fake string ", str23.lstrip())
  262. self.assertEqual("ke string", str1.lstrip("abcdef"))
  263. self.assertEqual(("fa", "ke", " string"), str1.partition("ke"))
  264. self.assertEqual(("fake string", "", ""), str1.partition("asdf"))
  265. str24 = _FakeString("boo foo moo")
  266. self.assertEqual("real string", str1.replace("fake", "real"))
  267. self.assertEqual("bu fu moo", str24.replace("oo", "u", 2))
  268. self.assertEqual(3, str1.rfind("e"))
  269. self.assertEqual(-1, str1.rfind("z"))
  270. self.assertEqual(7, str1.rfind("r", 7))
  271. self.assertEqual(-1, str1.rfind("r", 8))
  272. self.assertEqual(7, str1.rfind("r", 5, 9))
  273. self.assertEqual(-1, str1.rfind("r", 5, 7))
  274. self.assertEqual(3, str1.rindex("e"))
  275. self.assertRaises(ValueError, str1.rindex, "z")
  276. self.assertEqual(7, str1.rindex("r", 7))
  277. self.assertRaises(ValueError, str1.rindex, "r", 8)
  278. self.assertEqual(7, str1.rindex("r", 5, 9))
  279. self.assertRaises(ValueError, str1.rindex, "r", 5, 7)
  280. self.assertEqual(" fake string", str1.rjust(15))
  281. self.assertEqual(" fake string", str1.rjust(16))
  282. self.assertEqual("qqqqfake string", str1.rjust(15, "q"))
  283. self.assertEqual(("fa", "ke", " string"), str1.rpartition("ke"))
  284. self.assertEqual(("", "", "fake string"), str1.rpartition("asdf"))
  285. str25 = _FakeString(" this is a sentence with whitespace ")
  286. actual = ["this", "is", "a", "sentence", "with", "whitespace"]
  287. self.assertEqual(actual, str25.rsplit())
  288. self.assertEqual(actual, str25.rsplit(None))
  289. actual = ["", "", "", "this", "is", "a", "", "", "sentence", "with",
  290. "", "whitespace", ""]
  291. self.assertEqual(actual, str25.rsplit(" "))
  292. actual = [" this is a", "sentence", "with", "whitespace"]
  293. self.assertEqual(actual, str25.rsplit(None, 3))
  294. actual = [" this is a sentence with", "", "whitespace", ""]
  295. self.assertEqual(actual, str25.rsplit(" ", 3))
  296. actual = [" this is a", "sentence", "with", "whitespace"]
  297. self.assertEqual(actual, str25.rsplit(maxsplit=3))
  298. self.assertEqual("fake string", str1.rstrip())
  299. self.assertEqual(" fake string", str23.rstrip())
  300. self.assertEqual("fake stri", str1.rstrip("ngr"))
  301. actual = ["this", "is", "a", "sentence", "with", "whitespace"]
  302. self.assertEqual(actual, str25.split())
  303. self.assertEqual(actual, str25.split(None))
  304. actual = ["", "", "", "this", "is", "a", "", "", "sentence", "with",
  305. "", "whitespace", ""]
  306. self.assertEqual(actual, str25.split(" "))
  307. actual = ["this", "is", "a", "sentence with whitespace "]
  308. self.assertEqual(actual, str25.split(None, 3))
  309. actual = ["", "", "", "this is a sentence with whitespace "]
  310. self.assertEqual(actual, str25.split(" ", 3))
  311. actual = ["this", "is", "a", "sentence with whitespace "]
  312. self.assertEqual(actual, str25.split(maxsplit=3))
  313. str26 = _FakeString("lines\nof\ntext\r\nare\r\npresented\nhere")
  314. self.assertEqual(["lines", "of", "text", "are", "presented", "here"],
  315. str26.splitlines())
  316. self.assertEqual(["lines\n", "of\n", "text\r\n", "are\r\n",
  317. "presented\n", "here"], str26.splitlines(True))
  318. self.assertTrue(str1.startswith("fake"))
  319. self.assertFalse(str1.startswith("faker"))
  320. self.assertEqual("fake string", str1.strip())
  321. self.assertEqual("fake string", str23.strip())
  322. self.assertEqual("ke stri", str1.strip("abcdefngr"))
  323. self.assertEqual("fOObAR", str16.swapcase())
  324. self.assertEqual("Fake String", str1.title())
  325. table1 = StringMixIn.maketrans({97: "1", 101: "2", 105: "3",
  326. 111: "4", 117: "5"})
  327. table2 = StringMixIn.maketrans("aeiou", "12345")
  328. table3 = StringMixIn.maketrans("aeiou", "12345", "rts")
  329. self.assertEqual("f1k2 str3ng", str1.translate(table1))
  330. self.assertEqual("f1k2 str3ng", str1.translate(table2))
  331. self.assertEqual("f1k2 3ng", str1.translate(table3))
  332. self.assertEqual("", str15.upper())
  333. self.assertEqual("FOOBAR", str16.upper())
  334. self.assertEqual("123", str12.zfill(3))
  335. self.assertEqual("000123", str12.zfill(6))
  336. if __name__ == "__main__":
  337. unittest.main(verbosity=2)