A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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