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.
 
 
 
 

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