A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

270 rader
10 KiB

  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 types import GeneratorType
  24. import unittest
  25. from mwparserfromhell.compat import bytes, py3k, range, str
  26. from mwparserfromhell.string_mixin import StringMixIn
  27. class _FakeString(StringMixIn):
  28. def __init__(self, data):
  29. self._data = data
  30. def __unicode__(self):
  31. return self._data
  32. class TestStringMixIn(unittest.TestCase):
  33. """Test cases for the StringMixIn class."""
  34. def test_docs(self):
  35. """make sure the various functions of StringMixIn have docstrings"""
  36. methods = [
  37. "capitalize", "center", "count", "encode", "endswith",
  38. "expandtabs", "find", "format", "index", "isalnum", "isalpha",
  39. "isdigit", "islower", "isnumeric", "isspace", "istitle", "isupper",
  40. "join", "ljust", "lstrip", "partition", "replace", "rfind",
  41. "rindex", "rjust", "rpartition", "rsplit", "rstrip", "split",
  42. "splitlines", "startswith", "strip", "swapcase", "title",
  43. "translate", "upper", "zfill"]
  44. if py3k:
  45. methods.append("isdecimal")
  46. else:
  47. methods.append("decode")
  48. for meth in methods:
  49. expected = getattr(str, meth).__doc__
  50. actual = getattr(StringMixIn, meth).__doc__
  51. self.assertEquals(expected, actual)
  52. def test_types(self):
  53. """make sure StringMixIns convert to different types correctly"""
  54. fstr = _FakeString("fake string")
  55. self.assertEquals(str(fstr), "fake string")
  56. self.assertEquals(bytes(fstr), b"fake string")
  57. if py3k:
  58. self.assertEquals(repr(fstr), "'fake string'")
  59. else:
  60. self.assertEquals(repr(fstr), b"u'fake string'")
  61. self.assertIsInstance(str(fstr), str)
  62. self.assertIsInstance(bytes(fstr), bytes)
  63. if py3k:
  64. self.assertIsInstance(repr(fstr), str)
  65. else:
  66. self.assertIsInstance(repr(fstr), bytes)
  67. def test_comparisons(self):
  68. """make sure comparison operators work"""
  69. str1 = _FakeString("this is a fake string")
  70. str2 = _FakeString("this is a fake string")
  71. str3 = _FakeString("fake string, this is")
  72. str4 = "this is a fake string"
  73. str5 = "fake string, this is"
  74. self.assertFalse(str1 > str2)
  75. self.assertTrue(str1 >= str2)
  76. self.assertTrue(str1 == str2)
  77. self.assertFalse(str1 != str2)
  78. self.assertFalse(str1 < str2)
  79. self.assertTrue(str1 <= str2)
  80. self.assertTrue(str1 > str3)
  81. self.assertTrue(str1 >= str3)
  82. self.assertFalse(str1 == str3)
  83. self.assertTrue(str1 != str3)
  84. self.assertFalse(str1 < str3)
  85. self.assertFalse(str1 <= str3)
  86. self.assertFalse(str1 > str4)
  87. self.assertTrue(str1 >= str4)
  88. self.assertTrue(str1 == str4)
  89. self.assertFalse(str1 != str4)
  90. self.assertFalse(str1 < str4)
  91. self.assertTrue(str1 <= str4)
  92. self.assertTrue(str1 > str5)
  93. self.assertTrue(str1 >= str5)
  94. self.assertFalse(str1 == str5)
  95. self.assertTrue(str1 != str5)
  96. self.assertFalse(str1 < str5)
  97. self.assertFalse(str1 <= str5)
  98. def test_other_magics(self):
  99. """test other magically implemented features, like len() and iter()"""
  100. str1 = _FakeString("fake string")
  101. str2 = _FakeString("")
  102. expected = ["f", "a", "k", "e", " ", "s", "t", "r", "i", "n", "g"]
  103. self.assertTrue(str1)
  104. self.assertFalse(str2)
  105. self.assertEquals(11, len(str1))
  106. self.assertEquals(0, len(str2))
  107. out = []
  108. for ch in str1:
  109. out.append(ch)
  110. self.assertEquals(expected, out)
  111. out = []
  112. for ch in str2:
  113. out.append(ch)
  114. self.assertEquals([], out)
  115. gen1 = iter(str1)
  116. gen2 = iter(str2)
  117. self.assertIsInstance(gen1, GeneratorType)
  118. self.assertIsInstance(gen2, GeneratorType)
  119. out = []
  120. for i in range(len(str1)):
  121. out.append(gen1.next())
  122. self.assertRaises(StopIteration, gen1.next)
  123. self.assertEquals(expected, out)
  124. self.assertRaises(StopIteration, gen2.next)
  125. self.assertEquals("f", str1[0])
  126. self.assertEquals(" ", str1[4])
  127. self.assertEquals("g", str1[10])
  128. self.assertEquals("n", str1[-2])
  129. self.assertRaises(IndexError, lambda: str1[11])
  130. self.assertRaises(IndexError, lambda: str2[0])
  131. self.assertTrue("k" in str1)
  132. self.assertTrue("fake" in str1)
  133. self.assertTrue("str" in str1)
  134. self.assertTrue("" in str1)
  135. self.assertTrue("" in str2)
  136. self.assertFalse("real" in str1)
  137. self.assertFalse("s" in str2)
  138. def test_other_methods(self):
  139. """test the remaining non-magic methods of StringMixIn"""
  140. str1 = _FakeString("fake string")
  141. self.assertEquals("Fake string", str1.capitalize())
  142. self.assertEquals(" fake string ", str1.center(15))
  143. self.assertEquals(" fake string ", str1.center(16))
  144. self.assertEquals("qqfake stringqq", str1.center(15, "q"))
  145. self.assertEquals(1, str1.count("e"))
  146. self.assertEquals(0, str1.count("z"))
  147. self.assertEquals(1, str1.count("r", 7))
  148. self.assertEquals(0, str1.count("r", 8))
  149. self.assertEquals(1, str1.count("r", 5, 9))
  150. self.assertEquals(0, str1.count("r", 5, 7))
  151. if not py3k:
  152. str2 = _FakeString("fo")
  153. self.assertEquals(str1, str1.decode())
  154. actual = _FakeString("\\U00010332\\U0001033f\\U00010344")
  155. self.assertEquals("𐌲𐌿𐍄", actual.decode("unicode_escape"))
  156. self.assertRaises(UnicodeError, str2.decode, "punycode")
  157. self.assertEquals("", str2.decode("punycode", "ignore"))
  158. str3 = _FakeString("𐌲𐌿𐍄")
  159. self.assertEquals(b"fake string", str1.encode())
  160. self.assertEquals(b"\xF0\x90\x8C\xB2\xF0\x90\x8C\xBF\xF0\x90\x8D\x84",
  161. str3.encode("utf8"))
  162. self.assertRaises(UnicodeEncodeError, str3.encode)
  163. self.assertRaises(UnicodeEncodeError, str3.encode, "ascii")
  164. self.assertRaises(UnicodeEncodeError, str3.encode, "ascii", "strict")
  165. self.assertEquals("", str3.encode("ascii", "ignore"))
  166. self.assertTrue(str1.endswith("ing"))
  167. self.assertFalse(str1.endswith("ingh"))
  168. str4 = _FakeString("\tfoobar")
  169. self.assertEquals("fake string", str1)
  170. self.assertEquals(" foobar", str4.expandtabs())
  171. self.assertEquals(" foobar", str4.expandtabs(4))
  172. self.assertEquals(3, str1.find("e"))
  173. self.assertEquals(-1, str1.find("z"))
  174. self.assertEquals(7, str1.find("r", 7))
  175. self.assertEquals(-1, str1.find("r", 8))
  176. self.assertEquals(7, str1.find("r", 5, 9))
  177. self.assertEquals(-1, str1.find("r", 5, 7))
  178. str5 = _FakeString("foo{0}baz")
  179. str6 = _FakeString("foo{abc}baz")
  180. str7 = _FakeString("foo{0}{abc}buzz")
  181. str8 = _FakeString("{0}{1}")
  182. self.assertEquals("fake string", str1.format())
  183. self.assertEquals("foobarbaz", str5.format("bar"))
  184. self.assertEquals("foobarbaz", str6.format(abc="bar"))
  185. self.assertEquals("foobarbazbuzz", str7.format("bar", abc="baz"))
  186. self.assertRaises(IndexError, str8.format, "abc")
  187. self.assertEquals(3, str1.index("e"))
  188. self.assertRaises(ValueError, str1.index, "z")
  189. self.assertEquals(7, str1.index("r", 7))
  190. self.assertRaises(ValueError, str1.index, "r", 8)
  191. self.assertEquals(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. if py3k:
  206. self.assertFalse(str9.isdecimal())
  207. self.assertTrue(str12.isdecimal())
  208. self.assertFalse(str13.isdecimal())
  209. self.assertFalse(str14.isdecimal())
  210. self.assertFalse(str9.isdigit())
  211. self.assertTrue(str12.isdigit())
  212. self.assertFalse(str13.isdigit())
  213. self.assertTrue(str14.isdigit())
  214. str15 = _FakeString("")
  215. str16 = _FakeString("FooBar")
  216. self.assertTrue(str9.islower())
  217. self.assertFalse(str15.islower())
  218. self.assertFalse(str16.islower())
  219. self.assertFalse(str9.isnumeric())
  220. self.assertTrue(str12.isnumeric())
  221. self.assertTrue(str13.isnumeric())
  222. self.assertTrue(str14.isnumeric())
  223. methods = [
  224. "isspace",
  225. "istitle", "isupper", "join", "ljust", "lstrip", "partition",
  226. "replace", "rfind", "rindex", "rjust", "rpartition", "rsplit",
  227. "rstrip", "split", "splitlines", "startswith", "strip", "swapcase",
  228. "title", "translate", "upper", "zfill"]
  229. if __name__ == "__main__":
  230. unittest.main(verbosity=2)