A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

404 line
16 KiB

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