PageRenderTime 38ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/string_tests.py

http://github.com/IronLanguages/main
Python | 1415 lines | 1383 code | 11 blank | 21 comment | 13 complexity | ebc6d6dac9e54f2d48eb7515fc6dfb38 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """
  2. Common tests shared by test_str, test_unicode, test_userstring and test_string.
  3. """
  4. import unittest, string, sys, struct
  5. from test import test_support
  6. from UserList import UserList
  7. class Sequence:
  8. def __init__(self, seq='wxyz'): self.seq = seq
  9. def __len__(self): return len(self.seq)
  10. def __getitem__(self, i): return self.seq[i]
  11. class BadSeq1(Sequence):
  12. def __init__(self): self.seq = [7, 'hello', 123L]
  13. class BadSeq2(Sequence):
  14. def __init__(self): self.seq = ['a', 'b', 'c']
  15. def __len__(self): return 8
  16. class CommonTest(unittest.TestCase):
  17. # This testcase contains test that can be used in all
  18. # stringlike classes. Currently this is str, unicode
  19. # UserString and the string module.
  20. # The type to be tested
  21. # Change in subclasses to change the behaviour of fixtesttype()
  22. type2test = None
  23. # All tests pass their arguments to the testing methods
  24. # as str objects. fixtesttype() can be used to propagate
  25. # these arguments to the appropriate type
  26. def fixtype(self, obj):
  27. if isinstance(obj, str):
  28. return self.__class__.type2test(obj)
  29. elif isinstance(obj, list):
  30. return [self.fixtype(x) for x in obj]
  31. elif isinstance(obj, tuple):
  32. return tuple([self.fixtype(x) for x in obj])
  33. elif isinstance(obj, dict):
  34. return dict([
  35. (self.fixtype(key), self.fixtype(value))
  36. for (key, value) in obj.iteritems()
  37. ])
  38. else:
  39. return obj
  40. def test_fixtype(self):
  41. self.assertIs(type(self.fixtype("123")), self.type2test)
  42. # check that object.method(*args) returns result
  43. def checkequal(self, result, object, methodname, *args):
  44. result = self.fixtype(result)
  45. object = self.fixtype(object)
  46. args = self.fixtype(args)
  47. realresult = getattr(object, methodname)(*args)
  48. self.assertEqual(
  49. result,
  50. realresult
  51. )
  52. # if the original is returned make sure that
  53. # this doesn't happen with subclasses
  54. if object == realresult:
  55. class subtype(self.__class__.type2test):
  56. pass
  57. object = subtype(object)
  58. realresult = getattr(object, methodname)(*args)
  59. self.assertTrue(object is not realresult)
  60. # check that object.method(*args) raises exc
  61. def checkraises(self, exc, obj, methodname, *args):
  62. obj = self.fixtype(obj)
  63. args = self.fixtype(args)
  64. with self.assertRaises(exc) as cm:
  65. getattr(obj, methodname)(*args)
  66. self.assertNotEqual(cm.exception.args[0], '')
  67. # call object.method(*args) without any checks
  68. def checkcall(self, object, methodname, *args):
  69. object = self.fixtype(object)
  70. args = self.fixtype(args)
  71. getattr(object, methodname)(*args)
  72. def test_hash(self):
  73. # SF bug 1054139: += optimization was not invalidating cached hash value
  74. a = self.type2test('DNSSEC')
  75. b = self.type2test('')
  76. for c in a:
  77. b += c
  78. hash(b)
  79. self.assertEqual(hash(a), hash(b))
  80. def test_capitalize(self):
  81. self.checkequal(' hello ', ' hello ', 'capitalize')
  82. self.checkequal('Hello ', 'Hello ','capitalize')
  83. self.checkequal('Hello ', 'hello ','capitalize')
  84. self.checkequal('Aaaa', 'aaaa', 'capitalize')
  85. self.checkequal('Aaaa', 'AaAa', 'capitalize')
  86. self.checkraises(TypeError, 'hello', 'capitalize', 42)
  87. def test_count(self):
  88. self.checkequal(3, 'aaa', 'count', 'a')
  89. self.checkequal(0, 'aaa', 'count', 'b')
  90. self.checkequal(3, 'aaa', 'count', 'a')
  91. self.checkequal(0, 'aaa', 'count', 'b')
  92. self.checkequal(3, 'aaa', 'count', 'a')
  93. self.checkequal(0, 'aaa', 'count', 'b')
  94. self.checkequal(0, 'aaa', 'count', 'b')
  95. self.checkequal(2, 'aaa', 'count', 'a', 1)
  96. self.checkequal(0, 'aaa', 'count', 'a', 10)
  97. self.checkequal(1, 'aaa', 'count', 'a', -1)
  98. self.checkequal(3, 'aaa', 'count', 'a', -10)
  99. self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
  100. self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
  101. self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
  102. self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
  103. self.checkequal(3, 'aaa', 'count', '', 1)
  104. self.checkequal(1, 'aaa', 'count', '', 3)
  105. self.checkequal(0, 'aaa', 'count', '', 10)
  106. self.checkequal(2, 'aaa', 'count', '', -1)
  107. self.checkequal(4, 'aaa', 'count', '', -10)
  108. self.checkequal(1, '', 'count', '')
  109. self.checkequal(0, '', 'count', '', 1, 1)
  110. self.checkequal(0, '', 'count', '', sys.maxint, 0)
  111. self.checkequal(0, '', 'count', 'xx')
  112. self.checkequal(0, '', 'count', 'xx', 1, 1)
  113. self.checkequal(0, '', 'count', 'xx', sys.maxint, 0)
  114. self.checkraises(TypeError, 'hello', 'count')
  115. self.checkraises(TypeError, 'hello', 'count', 42)
  116. # For a variety of combinations,
  117. # verify that str.count() matches an equivalent function
  118. # replacing all occurrences and then differencing the string lengths
  119. charset = ['', 'a', 'b']
  120. digits = 7
  121. base = len(charset)
  122. teststrings = set()
  123. for i in xrange(base ** digits):
  124. entry = []
  125. for j in xrange(digits):
  126. i, m = divmod(i, base)
  127. entry.append(charset[m])
  128. teststrings.add(''.join(entry))
  129. teststrings = list(teststrings)
  130. for i in teststrings:
  131. i = self.fixtype(i)
  132. n = len(i)
  133. for j in teststrings:
  134. r1 = i.count(j)
  135. if j:
  136. r2, rem = divmod(n - len(i.replace(j, '')), len(j))
  137. else:
  138. r2, rem = len(i)+1, 0
  139. if rem or r1 != r2:
  140. self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
  141. self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
  142. def test_find(self):
  143. self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
  144. self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
  145. self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
  146. self.checkequal(0, 'abc', 'find', '', 0)
  147. self.checkequal(3, 'abc', 'find', '', 3)
  148. self.checkequal(-1, 'abc', 'find', '', 4)
  149. # to check the ability to pass None as defaults
  150. self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
  151. self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
  152. self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
  153. self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
  154. self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
  155. self.checkraises(TypeError, 'hello', 'find')
  156. self.checkraises(TypeError, 'hello', 'find', 42)
  157. self.checkequal(0, '', 'find', '')
  158. self.checkequal(-1, '', 'find', '', 1, 1)
  159. self.checkequal(-1, '', 'find', '', sys.maxint, 0)
  160. self.checkequal(-1, '', 'find', 'xx')
  161. self.checkequal(-1, '', 'find', 'xx', 1, 1)
  162. self.checkequal(-1, '', 'find', 'xx', sys.maxint, 0)
  163. # issue 7458
  164. self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0)
  165. # For a variety of combinations,
  166. # verify that str.find() matches __contains__
  167. # and that the found substring is really at that location
  168. charset = ['', 'a', 'b', 'c']
  169. digits = 5
  170. base = len(charset)
  171. teststrings = set()
  172. for i in xrange(base ** digits):
  173. entry = []
  174. for j in xrange(digits):
  175. i, m = divmod(i, base)
  176. entry.append(charset[m])
  177. teststrings.add(''.join(entry))
  178. teststrings = list(teststrings)
  179. for i in teststrings:
  180. i = self.fixtype(i)
  181. for j in teststrings:
  182. loc = i.find(j)
  183. r1 = (loc != -1)
  184. r2 = j in i
  185. self.assertEqual(r1, r2)
  186. if loc != -1:
  187. self.assertEqual(i[loc:loc+len(j)], j)
  188. def test_rfind(self):
  189. self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
  190. self.checkequal(12, 'abcdefghiabc', 'rfind', '')
  191. self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
  192. self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
  193. self.checkequal(3, 'abc', 'rfind', '', 0)
  194. self.checkequal(3, 'abc', 'rfind', '', 3)
  195. self.checkequal(-1, 'abc', 'rfind', '', 4)
  196. # to check the ability to pass None as defaults
  197. self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
  198. self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
  199. self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
  200. self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
  201. self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
  202. self.checkraises(TypeError, 'hello', 'rfind')
  203. self.checkraises(TypeError, 'hello', 'rfind', 42)
  204. # For a variety of combinations,
  205. # verify that str.rfind() matches __contains__
  206. # and that the found substring is really at that location
  207. charset = ['', 'a', 'b', 'c']
  208. digits = 5
  209. base = len(charset)
  210. teststrings = set()
  211. for i in xrange(base ** digits):
  212. entry = []
  213. for j in xrange(digits):
  214. i, m = divmod(i, base)
  215. entry.append(charset[m])
  216. teststrings.add(''.join(entry))
  217. teststrings = list(teststrings)
  218. for i in teststrings:
  219. i = self.fixtype(i)
  220. for j in teststrings:
  221. loc = i.rfind(j)
  222. r1 = (loc != -1)
  223. r2 = j in i
  224. self.assertEqual(r1, r2)
  225. if loc != -1:
  226. self.assertEqual(i[loc:loc+len(j)], self.fixtype(j))
  227. # issue 7458
  228. self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0)
  229. def test_index(self):
  230. self.checkequal(0, 'abcdefghiabc', 'index', '')
  231. self.checkequal(3, 'abcdefghiabc', 'index', 'def')
  232. self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
  233. self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
  234. self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
  235. self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
  236. self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
  237. self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
  238. # to check the ability to pass None as defaults
  239. self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
  240. self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
  241. self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
  242. self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
  243. self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
  244. self.checkraises(TypeError, 'hello', 'index')
  245. self.checkraises(TypeError, 'hello', 'index', 42)
  246. def test_rindex(self):
  247. self.checkequal(12, 'abcdefghiabc', 'rindex', '')
  248. self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
  249. self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
  250. self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
  251. self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
  252. self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
  253. self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
  254. self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
  255. self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
  256. # to check the ability to pass None as defaults
  257. self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
  258. self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
  259. self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
  260. self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
  261. self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
  262. self.checkraises(TypeError, 'hello', 'rindex')
  263. self.checkraises(TypeError, 'hello', 'rindex', 42)
  264. def test_lower(self):
  265. self.checkequal('hello', 'HeLLo', 'lower')
  266. self.checkequal('hello', 'hello', 'lower')
  267. self.checkraises(TypeError, 'hello', 'lower', 42)
  268. def test_upper(self):
  269. self.checkequal('HELLO', 'HeLLo', 'upper')
  270. self.checkequal('HELLO', 'HELLO', 'upper')
  271. self.checkraises(TypeError, 'hello', 'upper', 42)
  272. def test_expandtabs(self):
  273. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
  274. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
  275. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
  276. self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
  277. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
  278. self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
  279. self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
  280. self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
  281. self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
  282. # This test is only valid when sizeof(int) == sizeof(void*) == 4.
  283. if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
  284. self.checkraises(OverflowError,
  285. '\ta\n\tb', 'expandtabs', sys.maxint)
  286. def test_split(self):
  287. self.checkequal(['this', 'is', 'the', 'split', 'function'],
  288. 'this is the split function', 'split')
  289. # by whitespace
  290. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
  291. self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
  292. self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
  293. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
  294. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
  295. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
  296. sys.maxint-1)
  297. self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
  298. self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
  299. self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
  300. self.checkequal([], ' ', 'split')
  301. self.checkequal(['a'], ' a ', 'split')
  302. self.checkequal(['a', 'b'], ' a b ', 'split')
  303. self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
  304. self.checkequal(['a b c '], ' a b c ', 'split', None, 0)
  305. self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
  306. self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
  307. self.checkequal(['a', 'b', 'c'], ' a b c ', 'split', None, 3)
  308. self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
  309. aaa = ' a '*20
  310. self.checkequal(['a']*20, aaa, 'split')
  311. self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
  312. self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
  313. for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
  314. 'arf\fbarf', 'arf\vbarf'):
  315. self.checkequal(['arf', 'barf'], b, 'split')
  316. self.checkequal(['arf', 'barf'], b, 'split', None)
  317. self.checkequal(['arf', 'barf'], b, 'split', None, 2)
  318. # by a char
  319. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
  320. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
  321. self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
  322. self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
  323. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
  324. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
  325. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
  326. sys.maxint-2)
  327. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
  328. self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
  329. self.checkequal(['abcd'], 'abcd', 'split', '|')
  330. self.checkequal([''], '', 'split', '|')
  331. self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
  332. self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
  333. self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
  334. self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
  335. self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
  336. self.checkequal(['a']*15 +['a|a|a|a|a'],
  337. ('a|'*20)[:-1], 'split', '|', 15)
  338. # by string
  339. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
  340. self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
  341. self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
  342. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
  343. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
  344. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
  345. sys.maxint-10)
  346. self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
  347. self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
  348. self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
  349. self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
  350. self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
  351. 'split', 'test')
  352. self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
  353. self.checkequal(['', ''], 'aaa', 'split', 'aaa')
  354. self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
  355. self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
  356. self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
  357. self.checkequal([''], '', 'split', 'aaa')
  358. self.checkequal(['aa'], 'aa', 'split', 'aaa')
  359. self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
  360. self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
  361. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
  362. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
  363. self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
  364. 'split', 'BLAH', 18)
  365. # mixed use of str and unicode
  366. if self.type2test is not bytearray:
  367. result = [u'a', u'b', u'c d']
  368. self.checkequal(result, 'a b c d', 'split', u' ', 2)
  369. # argument type
  370. self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
  371. # null case
  372. self.checkraises(ValueError, 'hello', 'split', '')
  373. self.checkraises(ValueError, 'hello', 'split', '', 0)
  374. def test_rsplit(self):
  375. self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
  376. 'this is the rsplit function', 'rsplit')
  377. # by whitespace
  378. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
  379. self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
  380. self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
  381. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
  382. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
  383. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
  384. sys.maxint-20)
  385. self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
  386. self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
  387. self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
  388. self.checkequal([], ' ', 'rsplit')
  389. self.checkequal(['a'], ' a ', 'rsplit')
  390. self.checkequal(['a', 'b'], ' a b ', 'rsplit')
  391. self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
  392. self.checkequal([' a b c'], ' a b c ', 'rsplit',
  393. None, 0)
  394. self.checkequal([' a b','c'], ' a b c ', 'rsplit',
  395. None, 1)
  396. self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
  397. None, 2)
  398. self.checkequal(['a', 'b', 'c'], ' a b c ', 'rsplit',
  399. None, 3)
  400. self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
  401. aaa = ' a '*20
  402. self.checkequal(['a']*20, aaa, 'rsplit')
  403. self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
  404. self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
  405. for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
  406. 'arf\fbarf', 'arf\vbarf'):
  407. self.checkequal(['arf', 'barf'], b, 'rsplit')
  408. self.checkequal(['arf', 'barf'], b, 'rsplit', None)
  409. self.checkequal(['arf', 'barf'], b, 'rsplit', None, 2)
  410. # by a char
  411. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
  412. self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
  413. self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
  414. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
  415. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
  416. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
  417. sys.maxint-100)
  418. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
  419. self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
  420. self.checkequal(['abcd'], 'abcd', 'rsplit', '|')
  421. self.checkequal([''], '', 'rsplit', '|')
  422. self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
  423. self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
  424. self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
  425. self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
  426. self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
  427. self.checkequal(['a|a|a|a|a']+['a']*15,
  428. ('a|'*20)[:-1], 'rsplit', '|', 15)
  429. # by string
  430. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
  431. self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
  432. self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
  433. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
  434. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
  435. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
  436. sys.maxint-5)
  437. self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
  438. self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
  439. self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
  440. self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
  441. self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
  442. 'rsplit', 'test')
  443. self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
  444. self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
  445. self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
  446. self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
  447. self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
  448. self.checkequal([''], '', 'rsplit', 'aaa')
  449. self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
  450. self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
  451. self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
  452. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
  453. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
  454. self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
  455. 'rsplit', 'BLAH', 18)
  456. # mixed use of str and unicode
  457. if self.type2test is not bytearray:
  458. result = [u'a b', u'c', u'd']
  459. self.checkequal(result, 'a b c d', 'rsplit', u' ', 2)
  460. # argument type
  461. self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
  462. # null case
  463. self.checkraises(ValueError, 'hello', 'rsplit', '')
  464. self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
  465. def test_strip_whitespace(self):
  466. self.checkequal('hello', ' hello ', 'strip')
  467. self.checkequal('hello ', ' hello ', 'lstrip')
  468. self.checkequal(' hello', ' hello ', 'rstrip')
  469. self.checkequal('hello', 'hello', 'strip')
  470. b = ' \t\n\r\f\vabc \t\n\r\f\v'
  471. self.checkequal('abc', b, 'strip')
  472. self.checkequal('abc \t\n\r\f\v', b, 'lstrip')
  473. self.checkequal(' \t\n\r\f\vabc', b, 'rstrip')
  474. # strip/lstrip/rstrip with None arg
  475. self.checkequal('hello', ' hello ', 'strip', None)
  476. self.checkequal('hello ', ' hello ', 'lstrip', None)
  477. self.checkequal(' hello', ' hello ', 'rstrip', None)
  478. self.checkequal('hello', 'hello', 'strip', None)
  479. def test_strip(self):
  480. # strip/lstrip/rstrip with str arg
  481. self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
  482. self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
  483. self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
  484. self.checkequal('hello', 'hello', 'strip', 'xyz')
  485. self.checkequal('', 'mississippi', 'strip', 'mississippi')
  486. # only trims the start and end, does not strip internal characters
  487. self.checkequal('mississipp', 'mississippi', 'strip', 'i')
  488. # strip/lstrip/rstrip with unicode arg
  489. if self.type2test is not bytearray and test_support.have_unicode:
  490. self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
  491. 'strip', unicode('xyz', 'ascii'))
  492. self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
  493. 'lstrip', unicode('xyz', 'ascii'))
  494. self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
  495. 'rstrip', unicode('xyz', 'ascii'))
  496. # XXX
  497. #self.checkequal(unicode('hello', 'ascii'), 'hello',
  498. # 'strip', unicode('xyz', 'ascii'))
  499. self.checkraises(TypeError, 'hello', 'strip', 42, 42)
  500. self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
  501. self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
  502. def test_ljust(self):
  503. self.checkequal('abc ', 'abc', 'ljust', 10)
  504. self.checkequal('abc ', 'abc', 'ljust', 6)
  505. self.checkequal('abc', 'abc', 'ljust', 3)
  506. self.checkequal('abc', 'abc', 'ljust', 2)
  507. if self.type2test is bytearray:
  508. # Special case because bytearray argument is not accepted
  509. self.assertEqual(b'abc*******', bytearray(b'abc').ljust(10, '*'))
  510. else:
  511. self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
  512. self.checkraises(TypeError, 'abc', 'ljust')
  513. def test_rjust(self):
  514. self.checkequal(' abc', 'abc', 'rjust', 10)
  515. self.checkequal(' abc', 'abc', 'rjust', 6)
  516. self.checkequal('abc', 'abc', 'rjust', 3)
  517. self.checkequal('abc', 'abc', 'rjust', 2)
  518. if self.type2test is bytearray:
  519. # Special case because bytearray argument is not accepted
  520. self.assertEqual(b'*******abc', bytearray(b'abc').rjust(10, '*'))
  521. else:
  522. self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
  523. self.checkraises(TypeError, 'abc', 'rjust')
  524. def test_center(self):
  525. self.checkequal(' abc ', 'abc', 'center', 10)
  526. self.checkequal(' abc ', 'abc', 'center', 6)
  527. self.checkequal('abc', 'abc', 'center', 3)
  528. self.checkequal('abc', 'abc', 'center', 2)
  529. if self.type2test is bytearray:
  530. # Special case because bytearray argument is not accepted
  531. result = bytearray(b'abc').center(10, '*')
  532. self.assertEqual(b'***abc****', result)
  533. else:
  534. self.checkequal('***abc****', 'abc', 'center', 10, '*')
  535. self.checkraises(TypeError, 'abc', 'center')
  536. def test_swapcase(self):
  537. self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
  538. self.checkraises(TypeError, 'hello', 'swapcase', 42)
  539. def test_replace(self):
  540. EQ = self.checkequal
  541. # Operations on the empty string
  542. EQ("", "", "replace", "", "")
  543. EQ("A", "", "replace", "", "A")
  544. EQ("", "", "replace", "A", "")
  545. EQ("", "", "replace", "A", "A")
  546. EQ("", "", "replace", "", "", 100)
  547. EQ("", "", "replace", "", "", sys.maxint)
  548. # interleave (from=="", 'to' gets inserted everywhere)
  549. EQ("A", "A", "replace", "", "")
  550. EQ("*A*", "A", "replace", "", "*")
  551. EQ("*1A*1", "A", "replace", "", "*1")
  552. EQ("*-#A*-#", "A", "replace", "", "*-#")
  553. EQ("*-A*-A*-", "AA", "replace", "", "*-")
  554. EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
  555. EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
  556. EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
  557. EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
  558. EQ("*-A*-A", "AA", "replace", "", "*-", 2)
  559. EQ("*-AA", "AA", "replace", "", "*-", 1)
  560. EQ("AA", "AA", "replace", "", "*-", 0)
  561. # single character deletion (from=="A", to=="")
  562. EQ("", "A", "replace", "A", "")
  563. EQ("", "AAA", "replace", "A", "")
  564. EQ("", "AAA", "replace", "A", "", -1)
  565. EQ("", "AAA", "replace", "A", "", sys.maxint)
  566. EQ("", "AAA", "replace", "A", "", 4)
  567. EQ("", "AAA", "replace", "A", "", 3)
  568. EQ("A", "AAA", "replace", "A", "", 2)
  569. EQ("AA", "AAA", "replace", "A", "", 1)
  570. EQ("AAA", "AAA", "replace", "A", "", 0)
  571. EQ("", "AAAAAAAAAA", "replace", "A", "")
  572. EQ("BCD", "ABACADA", "replace", "A", "")
  573. EQ("BCD", "ABACADA", "replace", "A", "", -1)
  574. EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
  575. EQ("BCD", "ABACADA", "replace", "A", "", 5)
  576. EQ("BCD", "ABACADA", "replace", "A", "", 4)
  577. EQ("BCDA", "ABACADA", "replace", "A", "", 3)
  578. EQ("BCADA", "ABACADA", "replace", "A", "", 2)
  579. EQ("BACADA", "ABACADA", "replace", "A", "", 1)
  580. EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
  581. EQ("BCD", "ABCAD", "replace", "A", "")
  582. EQ("BCD", "ABCADAA", "replace", "A", "")
  583. EQ("BCD", "BCD", "replace", "A", "")
  584. EQ("*************", "*************", "replace", "A", "")
  585. EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
  586. # substring deletion (from=="the", to=="")
  587. EQ("", "the", "replace", "the", "")
  588. EQ("ater", "theater", "replace", "the", "")
  589. EQ("", "thethe", "replace", "the", "")
  590. EQ("", "thethethethe", "replace", "the", "")
  591. EQ("aaaa", "theatheatheathea", "replace", "the", "")
  592. EQ("that", "that", "replace", "the", "")
  593. EQ("thaet", "thaet", "replace", "the", "")
  594. EQ("here and re", "here and there", "replace", "the", "")
  595. EQ("here and re and re", "here and there and there",
  596. "replace", "the", "", sys.maxint)
  597. EQ("here and re and re", "here and there and there",
  598. "replace", "the", "", -1)
  599. EQ("here and re and re", "here and there and there",
  600. "replace", "the", "", 3)
  601. EQ("here and re and re", "here and there and there",
  602. "replace", "the", "", 2)
  603. EQ("here and re and there", "here and there and there",
  604. "replace", "the", "", 1)
  605. EQ("here and there and there", "here and there and there",
  606. "replace", "the", "", 0)
  607. EQ("here and re and re", "here and there and there", "replace", "the", "")
  608. EQ("abc", "abc", "replace", "the", "")
  609. EQ("abcdefg", "abcdefg", "replace", "the", "")
  610. # substring deletion (from=="bob", to=="")
  611. EQ("bob", "bbobob", "replace", "bob", "")
  612. EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
  613. EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
  614. EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
  615. # single character replace in place (len(from)==len(to)==1)
  616. EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
  617. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
  618. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
  619. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
  620. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
  621. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
  622. EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
  623. EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
  624. EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
  625. EQ("who goes there?", "Who goes there?", "replace", "W", "w")
  626. EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
  627. EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
  628. EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
  629. EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
  630. # substring replace in place (len(from)==len(to) > 1)
  631. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
  632. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
  633. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
  634. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
  635. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
  636. EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
  637. EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
  638. EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
  639. EQ("cobob", "bobob", "replace", "bob", "cob")
  640. EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
  641. EQ("bobob", "bobob", "replace", "bot", "bot")
  642. # replace single character (len(from)==1, len(to)>1)
  643. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
  644. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
  645. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
  646. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
  647. EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
  648. EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
  649. EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
  650. EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
  651. # replace substring (len(from)>1, len(to)!=len(from))
  652. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  653. "replace", "spam", "ham")
  654. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  655. "replace", "spam", "ham", sys.maxint)
  656. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  657. "replace", "spam", "ham", -1)
  658. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  659. "replace", "spam", "ham", 4)
  660. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  661. "replace", "spam", "ham", 3)
  662. EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
  663. "replace", "spam", "ham", 2)
  664. EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
  665. "replace", "spam", "ham", 1)
  666. EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
  667. "replace", "spam", "ham", 0)
  668. EQ("bobob", "bobobob", "replace", "bobob", "bob")
  669. EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
  670. EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
  671. with test_support.check_py3k_warnings():
  672. ba = buffer('a')
  673. bb = buffer('b')
  674. EQ("bbc", "abc", "replace", ba, bb)
  675. EQ("aac", "abc", "replace", bb, ba)
  676. #
  677. self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
  678. self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
  679. self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
  680. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
  681. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
  682. self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
  683. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
  684. self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
  685. self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
  686. self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
  687. self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
  688. self.checkequal('abc', 'abc', 'replace', '', '-', 0)
  689. self.checkequal('', '', 'replace', '', '')
  690. self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
  691. self.checkequal('abc', 'abc', 'replace', 'xy', '--')
  692. # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
  693. # MemoryError due to empty result (platform malloc issue when requesting
  694. # 0 bytes).
  695. self.checkequal('', '123', 'replace', '123', '')
  696. self.checkequal('', '123123', 'replace', '123', '')
  697. self.checkequal('x', '123x123', 'replace', '123', '')
  698. self.checkraises(TypeError, 'hello', 'replace')
  699. self.checkraises(TypeError, 'hello', 'replace', 42)
  700. self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
  701. self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
  702. @unittest.skipIf(sys.maxint > (1 << 32) or struct.calcsize('P') != 4,
  703. 'only applies to 32-bit platforms')
  704. def test_replace_overflow(self):
  705. # Check for overflow checking on 32 bit machines
  706. A2_16 = "A" * (2**16)
  707. self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
  708. self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
  709. self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
  710. def test_zfill(self):
  711. self.checkequal('123', '123', 'zfill', 2)
  712. self.checkequal('123', '123', 'zfill', 3)
  713. self.checkequal('0123', '123', 'zfill', 4)
  714. self.checkequal('+123', '+123', 'zfill', 3)
  715. self.checkequal('+123', '+123', 'zfill', 4)
  716. self.checkequal('+0123', '+123', 'zfill', 5)
  717. self.checkequal('-123', '-123', 'zfill', 3)
  718. self.checkequal('-123', '-123', 'zfill', 4)
  719. self.checkequal('-0123', '-123', 'zfill', 5)
  720. self.checkequal('000', '', 'zfill', 3)
  721. self.checkequal('34', '34', 'zfill', 1)
  722. self.checkequal('0034', '34', 'zfill', 4)
  723. self.checkraises(TypeError, '123', 'zfill')
  724. class NonStringModuleTest:
  725. # additional test cases for all string classes from bytearray to
  726. # UserString, but not valid for the "string" module
  727. def test_islower(self):
  728. self.checkequal(False, '', 'islower')
  729. self.checkequal(True, 'a', 'islower')
  730. self.checkequal(False, 'A', 'islower')
  731. self.checkequal(False, '\n', 'islower')
  732. self.checkequal(True, 'abc', 'islower')
  733. self.checkequal(False, 'aBc', 'islower')
  734. self.checkequal(True, 'abc\n', 'islower')
  735. self.checkraises(TypeError, 'abc', 'islower', 42)
  736. def test_isupper(self):
  737. self.checkequal(False, '', 'isupper')
  738. self.checkequal(False, 'a', 'isupper')
  739. self.checkequal(True, 'A', 'isupper')
  740. self.checkequal(False, '\n', 'isupper')
  741. self.checkequal(True, 'ABC', 'isupper')
  742. self.checkequal(False, 'AbC', 'isupper')
  743. self.checkequal(True, 'ABC\n', 'isupper')
  744. self.checkraises(TypeError, 'abc', 'isupper', 42)
  745. def test_istitle(self):
  746. self.checkequal(False, '', 'istitle')
  747. self.checkequal(False, 'a', 'istitle')
  748. self.checkequal(True, 'A', 'istitle')
  749. self.checkequal(False, '\n', 'istitle')
  750. self.checkequal(True, 'A Titlecased Line', 'istitle')
  751. self.checkequal(True, 'A\nTitlecased Line', 'istitle')
  752. self.checkequal(True, 'A Titlecased, Line', 'istitle')
  753. self.checkequal(False, 'Not a capitalized String', 'istitle')
  754. self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
  755. self.checkequal(False, 'Not--a Titlecase String', 'istitle')
  756. self.checkequal(False, 'NOT', 'istitle')
  757. self.checkraises(TypeError, 'abc', 'istitle', 42)
  758. def test_isspace(self):
  759. self.checkequal(False, '', 'isspace')
  760. self.checkequal(False, 'a', 'isspace')
  761. self.checkequal(True, ' ', 'isspace')
  762. self.checkequal(True, '\t', 'isspace')
  763. self.checkequal(True, '\r', 'isspace')
  764. self.checkequal(True, '\n', 'isspace')
  765. self.checkequal(True, ' \t\r\n', 'isspace')
  766. self.checkequal(False, ' \t\r\na', 'isspace')
  767. self.checkraises(TypeError, 'abc', 'isspace', 42)
  768. def test_isalpha(self):
  769. self.checkequal(False, '', 'isalpha')
  770. self.checkequal(True, 'a', 'isalpha')
  771. self.checkequal(True, 'A', 'isalpha')
  772. self.checkequal(False, '\n', 'isalpha')
  773. self.checkequal(True, 'abc', 'isalpha')
  774. self.checkequal(False, 'aBc123', 'isalpha')
  775. self.checkequal(False, 'abc\n', 'isalpha')
  776. self.checkraises(TypeError, 'abc', 'isalpha', 42)
  777. def test_isalnum(self):
  778. self.checkequal(False, '', 'isalnum')
  779. self.checkequal(True, 'a', 'isalnum')
  780. self.checkequal(True, 'A', 'isalnum')
  781. self.checkequal(False, '\n', 'isalnum')
  782. self.checkequal(True, '123abc456', 'isalnum')
  783. self.checkequal(True, 'a1b3c', 'isalnum')
  784. self.checkequal(False, 'aBc000 ', 'isalnum')
  785. self.checkequal(False, 'abc\n', 'isalnum')
  786. self.checkraises(TypeError, 'abc', 'isalnum', 42)
  787. def test_isdigit(self):
  788. self.checkequal(False, '', 'isdigit')
  789. self.checkequal(False, 'a', 'isdigit')
  790. self.checkequal(True, '0', 'isdigit')
  791. self.checkequal(True, '0123456789', 'isdigit')
  792. self.checkequal(False, '0123456789a', 'isdigit')
  793. self.checkraises(TypeError, 'abc', 'isdigit', 42)
  794. def test_title(self):
  795. self.checkequal(' Hello ', ' hello ', 'title')
  796. self.checkequal('Hello ', 'hello ', 'title')
  797. self.checkequal('Hello ', 'Hello ', 'title')
  798. self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
  799. self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
  800. self.checkequal('Getint', "getInt", 'title')
  801. self.checkraises(TypeError, 'hello', 'title', 42)
  802. def test_splitlines(self):
  803. self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
  804. self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
  805. self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
  806. self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
  807. self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
  808. self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
  809. self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
  810. self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
  811. class MixinStrUnicodeUserStringTest(NonStringModuleTest):
  812. # additional tests that only work for
  813. # stringlike objects, i.e. str, unicode, UserString
  814. # (but not the string module)
  815. def test_startswith(self):
  816. self.checkequal(True, 'hello', 'startswith', 'he')
  817. self.checkequal(True, 'hello', 'startswith', 'hello')
  818. self.checkequal(False, 'hello', 'startswith', 'hello world')
  819. self.checkequal(True, 'hello', 'startswith', '')
  820. self.checkequal(False, 'hello', 'startswith', 'ello')
  821. self.checkequal(True, 'hello', 'startswith', 'ello', 1)
  822. self.checkequal(True, 'hello', 'startswith', 'o', 4)
  823. self.checkequal(False, 'hello', 'startswith', 'o', 5)
  824. self.checkequal(True, 'hello', 'startswith', '', 5)
  825. self.checkequal(False, 'hello', 'startswith', 'lo', 6)
  826. self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
  827. self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
  828. self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
  829. # test negative indices
  830. self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
  831. self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
  832. self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
  833. self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
  834. self.checkequal(False, 'hello', 'startswith', 'ello', -5)
  835. self.checkequal(True, 'hello', 'startswith', 'ello', -4)
  836. self.checkequal(False, 'hello', 'startswith', 'o', -2)
  837. self.checkequal(True, 'hello', 'startswith', 'o', -1)
  838. self.checkequal(True, 'hello', 'startswith', '', -3, -3)
  839. self.checkequal(False, 'hello', 'startswith', 'lo', -9)
  840. self.checkraises(TypeError, 'hello', 'startswith')
  841. self.checkraises(TypeError, 'hello', 'startswith', 42)
  842. # test tuple arguments
  843. self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
  844. self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
  845. self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
  846. self.checkequal(False, 'hello', 'startswith', ())
  847. self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
  848. 'rld', 'lowo'), 3)
  849. self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
  850. 'rld'), 3)
  851. self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
  852. self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
  853. self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
  854. self.checkraises(TypeError, 'hello', 'startswith', (42,))
  855. def test_endswith(self):
  856. self.checkequal(True, 'hello', 'endswith', 'lo')
  857. self.checkequal(False, 'hello', 'endswith', 'he')
  858. self.checkequal(True, 'hello', 'endswith', '')
  859. self.checkequal(False, 'hello', 'endswith', 'hello world')
  860. self.checkequal(False, 'helloworld', 'endswith', 'worl')
  861. self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
  862. self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
  863. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
  864. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
  865. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
  866. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
  867. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
  868. self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
  869. self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
  870. # test negative indices
  871. self.checkequal(True, 'hello', 'endswith', 'lo', -2)
  872. self.checkequal(False, 'hello', 'endswith', 'he', -2)
  873. self.checkequal(True, 'hello', 'endswith', '', -3, -3)
  874. self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
  875. self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
  876. self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
  877. self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
  878. self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
  879. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
  880. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
  881. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
  882. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
  883. self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
  884. self.checkraises(TypeError, 'hello', 'endswith')
  885. self.checkraises(TypeError, 'hello', 'endswith', 42)
  886. # test tuple arguments
  887. self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
  888. self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
  889. self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
  890. self.checkequal(False, 'hello', 'endswith', ())
  891. self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
  892. 'rld', 'lowo'), 3)
  893. self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
  894. 'rld'), 3, -1)
  895. self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
  896. self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
  897. self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
  898. self.checkraises(TypeError, 'hello', 'endswith', (42,))
  899. def test___contains__(self):
  900. self.checkequal(True, '', '__contains__', '')
  901. self.checkequal(True, 'abc', '__contains__', '')
  902. self.checkequal(False, 'abc', '__contains__', '\0')
  903. self.checkequal(True, '\0abc', '__contains__', '\0')
  904. self.checkequal(True, 'abc\0', '__contains__', '\0')
  905. self.checkequal(True, '\0abc', '__contains__', 'a')
  906. self.checkequal(True, 'asdf', '__contains__', 'asdf')
  907. self.checkequal(False, 'asd', '__contains__', 'asdf')
  908. self.checkequal(False, '', '__contains__', 'asdf')
  909. def test_subscript(self):
  910. self.checkequal(u'a', 'abc', '__getitem__', 0)
  911. self.checkequal(u'c', 'abc', '__getitem__', -1)
  912. self.checkequal(u'a', 'abc', '__getitem__', 0L)
  913. self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
  914. self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
  915. self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
  916. self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
  917. self.checkraises(TypeError, 'abc', '__getitem__', 'def')
  918. def test_slice(self):
  919. self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
  920. self.checkequal('abc', 'abc', '__getslice__', 0, 3)
  921. self.checkequal('ab', 'abc', '__getslice__', 0, 2)
  922. self.checkequal('bc', 'abc', '__getslice__', 1, 3)
  923. self.checkequal('b', 'abc', '__getslice__', 1, 2)
  924. self.checkequal('', 'abc', '__getslice__', 2, 2)
  925. self.checkequal('', 'abc', '__getslice__', 1000, 1000)
  926. self.checkequal('', 'abc', '__getslice__', 2000, 1000)
  927. self.checkequal('', 'abc', '__getslice__', 2, 1)
  928. self.checkraises(TypeError, 'abc', '__getslice__', 'def')
  929. def test_extended_getslice(self):
  930. # Test extended slicing by comparing with list slicing.
  931. s = string.ascii_letters + string.digits
  932. indices = (0, None, 1, 3, 41, -1, -2, -37)
  933. for start in indices:
  934. for stop in indices:
  935. # Skip step 0 (invalid)
  936. for step in indices[1:]:
  937. L = list(s)[start:stop:step]
  938. self.checkequal(u"".join(L), s, '__getitem__',
  939. slice(start, stop, step))
  940. def test_mul(self):
  941. self.checkequal('', 'abc', '__mul__', -1)
  942. self.checkequal('', 'abc', '__mul__', 0)
  943. self.checkequal('abc', 'abc', '__mul__', 1)
  944. self.checkequal('abcabcabc', 'abc', '__mul__', 3)
  945. self.checkraises(TypeError, 'abc', '__mul__')
  946. self.checkraises(TypeError, 'abc', '__mul__', '')
  947. # XXX: on a 64-bit system, this doesn't raise an overflow error,
  948. # but either raises a MemoryError, or succeeds (if you have 54TiB)
  949. #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
  950. def test_join(self):
  951. # join now works with any sequence type
  952. # moved here, because the argument order is
  953. # different in string.join (see the test in
  954. # test.test_string.StringTest.test_join)
  955. self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
  956. self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
  957. self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
  958. self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
  959. self.checkequal('w x y z', ' ', 'join', Sequence())
  960. self.checkequal('abc', 'a', 'join', ('abc',))
  961. self.checkequal('z', 'a', 'join', UserList(['z']))
  962. if test_support.have_unicode:
  963. self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
  964. self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
  965. self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
  966. self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
  967. self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
  968. for i in [5, 25, 125]:
  969. self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
  970. ['a' * i] * i)
  971. self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
  972. ('a' * i,) * i)
  973. self.checkraises(TypeError, ' ', 'join', BadSeq1())
  974. self.checkequal('a b c', ' ', 'join', BadSeq2())
  975. self.checkraises(TypeError, ' ', 'join')
  976. self.checkraises(TypeError, ' ', 'join', None)
  977. self.checkraises(TypeError, ' ', 'join', 7)
  978. self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
  979. try:
  980. def f():
  981. yield 4 + ""
  982. self.fixtype(' ').join(f())
  983. except TypeError, e:
  984. if '+' not in str(e):
  985. self.fail('join() ate exception message')
  986. else:
  987. self.fail('exception not raised')
  988. def test_formatting(self):
  989. self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
  990. self.checkequal('+10+', '+%d+', '__mod__', 10)
  991. self.checkequal('a', "%c", '__mod__', "a")
  992. self.checkequal('a', "%c", '__mod__', "a")
  993. self.checkequal('"', "%c", '__mod__', 34)
  994. self.checkequal('$', "%c", '__mod__', 36)
  995. self.checkequal('10', "%d", '__mod__', 10)
  996. self.checkequal('\x7f', "%c", '__mod__', 0x7f)
  997. for ordinal in (-100, 0x200000):
  998. # unicode raises ValueError, str raises OverflowError
  999. self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
  1000. longvalue = sys.maxint + 10L
  1001. slongvalue = str(longvalue)
  1002. if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
  1003. self.checkequal(' 42', '%3ld', '__mod__', 42)
  1004. self.checkequal('42', '%d', '__mod__', 42L)
  1005. self.checkequal('42', '%d', '__mod__', 42.0)
  1006. self.checkequal(slongvalue, '%d', '__mod__', longvalue)
  1007. self.checkcall('%d', '__mod__', float(longvalue))
  1008. self.checkequal('0042.00', '%07.2f', '__mod__', 42)
  1009. self.checkequal('0042.00', '%07.2F', '__mod__', 42)
  1010. self.checkraises(TypeError, 'abc', '__mod__')
  1011. self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
  1012. self.checkraises(TypeError, '%s%s', '__mod__', (42,))
  1013. self.checkraises(TypeError, '%c', '__mod__', (None,))
  1014. self.checkraises(ValueError, '%(foo', '__mod__', {})
  1015. self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
  1016. self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
  1017. self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided
  1018. # argument names with properly nested brackets are supported
  1019. self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
  1020. # 100 is a magic number in PyUnicode_Format, this forces a resize
  1021. self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
  1022. self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
  1023. self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
  1024. self.checkraises(ValueError, '%10', '__mod__', (42,))
  1025. class X(object): pass
  1026. self.checkraises(TypeError, 'abc', '__mod__', X())
  1027. class X(Exception):
  1028. def __getitem__(self, k):
  1029. return k
  1030. self.checkequal('melon apple', '%(melon)s %(apple)s', '__mod__', X())
  1031. @test_support.cpython_only
  1032. def test_formatting_c_limits(self):
  1033. from _testcapi import PY_SSIZE_T_MAX, INT_MAX, UINT_MAX
  1034. SIZE_MAX = (1 << (PY_SSIZE_T_MAX.bit_length() + 1)) - 1
  1035. width = int(PY_SSIZE_T_MAX + 1)
  1036. if width <= sys.maxint:
  1037. self.checkraises(OverflowError, '%*s', '__mod__', (width, ''))
  1038. prec = int(INT_MAX + 1)
  1039. if prec <= sys.maxint:
  1040. self.checkraises(OverflowError, '%.*f', '__mod__', (prec, 1. / 7))
  1041. # Issue 15989
  1042. width = int(SIZE_MAX + 1)
  1043. if width <= sys.maxint:
  1044. self.checkraises(OverflowError, '%*s', '__mod__', (width, ''))
  1045. prec = int(UINT_MAX + 1)
  1046. if prec <= sys.maxint:
  1047. self.checkraises(OverflowError, '%.*f', '__mod__', (prec, 1. / 7))
  1048. def test_floatformatting(self):
  1049. # float formatting
  1050. for prec in xrange(100):
  1051. format = '%%.%if' % prec
  1052. value = 0.01
  1053. for x in xrange(60):
  1054. value = value * 3.14159265359 / 3.0 * 10.0
  1055. self.checkcall(format, "__mod__", value)
  1056. def test_inplace_rewrites(self):
  1057. # Check that strings don't copy and modify cached single-character strings
  1058. self.checkequal('a', 'A', 'lower')
  1059. self.checkequal(True, 'A', 'isupper')
  1060. self.checkequal('A', 'a', 'upper')
  1061. self.checkequal(True, 'a', 'islower')
  1062. self.checkequal('a', 'A', 'replace', 'A', 'a')
  1063. self.checkequal(True, 'A', 'isupper')
  1064. self.checkequal('A', 'a', 'capitalize')
  1065. self.checkequal(True, 'a', 'islower')
  1066. self.checkequal('A', 'a', 'swapcase')
  1067. self.checkequal(True, 'a', 'islower')
  1068. self.checkequal('A', 'a', 'title')
  1069. self.checkequal(True, 'a', 'islower')
  1070. def test_partition(self):
  1071. self.checkequal(('this is the par', 'ti', 'tion method'),
  1072. 'this is the partition method', 'partition', 'ti')
  1073. # from raymond's original specification
  1074. S = 'http://www.python.org'
  1075. self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
  1076. self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
  1077. self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
  1078. self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
  1079. self.checkraises(ValueError, S, 'partition', '')
  1080. self.checkraises(TypeError, S, 'partition', None)
  1081. # mixed use of str and unicode
  1082. self.assertEqual('a/b/c'.partition(u'/'), ('a', '/', 'b/c'))
  1083. def test_rpartition(self):
  1084. self.checkequal(('this is the rparti', 'ti', 'on method'),
  1085. 'this is the rpartition method', 'rpartition', 'ti')
  1086. # from raymond's original specification
  1087. S = 'http://www.python.org'
  1088. self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
  1089. self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
  1090. self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
  1091. self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
  1092. self.checkraises(ValueError, S, 'rpartition', '')
  1093. self.checkraises(TypeError, S, 'rpartition', None)
  1094. # mixed use of str and unicode
  1095. self.assertEqual('a/b/c'.rpartition(u'/'), ('a/b', '/', 'c'))
  1096. def test_none_arguments(self):
  1097. # issue 11828
  1098. s = 'hello'
  1099. self.checkequal(2, s, 'find', 'l', None)
  1100. self.checkequal(3, s, 'find', 'l', -2, None)
  1101. self.checkequal(2, s, 'find', 'l', None, -2)
  1102. self.checkequal(0, s, 'find', 'h', None, None)
  1103. self.checkequal(3, s, 'rfind', 'l', None)
  1104. self.checkequal(3, s, 'rfind', 'l', -2, None)
  1105. self.checkequal(2, s, 'rfind', 'l', None, -2)
  1106. self.checkequal(0, s, 'rfind', 'h', None, None)
  1107. self.checkequal(2, s, 'index', 'l', None)
  1108. self.checkequal(3, s, 'index', 'l', -2, None)
  1109. self.checkequal(2, s, 'index', 'l', None, -2)
  1110. self.checkequal(0, s, 'index', 'h', None, None)
  1111. self.checkequal(3, s, 'rindex', 'l', None)
  1112. self.checkequal(3, s, 'rindex', 'l', -2, None)
  1113. self.checkequal(2, s, 'rindex', 'l', None, -2)
  1114. self.checkequal(0, s, 'rindex', 'h', None, None)
  1115. self.checkequal(2, s, 'count', 'l', None)
  1116. self.checkequal(1, s, 'count', 'l', -2, None)
  1117. self.checkequal(1, s, 'count', 'l', None, -2)
  1118. self.checkequal(0, s, 'count', 'x', None, None)
  1119. self.checkequal(True, s, 'endswith', 'o', None)
  1120. self.checkequal(True, s, 'endswith', 'lo', -2, None)
  1121. self.checkequal(True, s, 'endswith', 'l', None, -2)
  1122. self.checkequal(False, s, 'endswith', 'x', None, None)
  1123. self.checkequal(True, s, 'startswith', 'h', None)
  1124. self.checkequal(True, s, 'startswith', 'l', -2, None)
  1125. self.checkequal(True, s, 'startswith', 'h', None, -2)
  1126. self.checkequal(False, s, 'startswith', 'x', None, None)
  1127. def test_find_etc_raise_correct_error_messages(self):
  1128. # issue 11828
  1129. s = 'hello'
  1130. x = 'x'
  1131. self.assertRaisesRegexp(TypeError, r'\bfind\b', s.find,
  1132. x, None, None, None)
  1133. self.assertRaisesRegexp(TypeError, r'\brfind\b', s.rfind,
  1134. x, None, None, None)
  1135. self.assertRaisesRegexp(TypeError, r'\bindex\b', s.index,
  1136. x, None, None, None)
  1137. self.assertRaisesRegexp(TypeError, r'\brindex\b', s.rindex,
  1138. x, None, None, None)
  1139. self.assertRaisesRegexp(TypeError, r'^count\(', s.count,
  1140. x, None, None, None)
  1141. self.assertRaisesRegexp(TypeError, r'^startswith\(', s.startswith,
  1142. x, None, None, None)
  1143. self.assertRaisesRegexp(TypeError, r'^endswith\(', s.endswith,
  1144. x, None, None, None)
  1145. class MixinStrStringUserStringTest:
  1146. # Additional tests for 8bit strings, i.e. str, UserString and
  1147. # the string module
  1148. def test_maketrans(self):
  1149. self.assertEqual(
  1150. ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
  1151. string.maketrans('abc', 'xyz')
  1152. )
  1153. self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
  1154. def test_translate(self):
  1155. table = string.maketrans('abc', 'xyz')
  1156. self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
  1157. table = string.maketrans('a', 'A')
  1158. self.checkequal('Abc', 'abc', 'translate', table)
  1159. self.checkequal('xyz', 'xyz', 'translate', table)
  1160. self.checkequal('yz', 'xyz', 'translate', table, 'x')
  1161. self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
  1162. self.checkequal('zyzzx', 'zyzzx', 'translate', None, '')
  1163. self.checkequal('zyzzx', 'zyzzx', 'translate', None)
  1164. self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
  1165. self.checkraises(ValueError, 'xyz', 'translate', 'too short')
  1166. class MixinStrUserStringTest:
  1167. # Additional tests that only work with
  1168. # 8bit compatible object, i.e. str and UserString
  1169. @unittest.skipUnless(test_support.have_unicode, 'no unicode support')
  1170. def test_encoding_decoding(self):
  1171. codecs = [('rot13', 'uryyb jbeyq'),
  1172. ('base64', 'aGVsbG8gd29ybGQ=\n'),
  1173. ('hex', '68656c6c6f20776f726c64'),
  1174. ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
  1175. for encoding, data in codecs:
  1176. with test_support.check_py3k_warnings():
  1177. self.checkequal(data, 'hello world', 'encode', encoding)
  1178. with test_support.check_py3k_warnings():
  1179. self.checkequal('hello world', data, 'decode', encoding)
  1180. # zlib is optional, so we make the test optional too...
  1181. try:
  1182. import zlib
  1183. except ImportError:
  1184. pass
  1185. else:
  1186. data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
  1187. with test_support.check_py3k_warnings():
  1188. self.checkequal(data, 'hello world', 'encode', 'zlib')
  1189. with test_support.check_py3k_warnings():
  1190. self.checkequal('hello world', data, 'decode', 'zlib')
  1191. self.checkraises(TypeError, 'xyz', 'decode', 42)
  1192. self.checkraises(TypeError, 'xyz', 'encode', 42)
  1193. class MixinStrUnicodeTest:
  1194. # Additional tests that only work with str and unicode.
  1195. def test_bug1001011(self):
  1196. # Make sure join returns a NEW object for single item sequences
  1197. # involving a subclass.
  1198. # Make sure that it is of the appropriate type.
  1199. # Check the optimisation still occurs for standard objects.
  1200. t = self.type2test
  1201. class subclass(t):
  1202. pass
  1203. s1 = subclass("abcd")
  1204. s2 = t().join([s1])
  1205. self.assertTrue(s1 is not s2)
  1206. self.assertTrue(type(s2) is t)
  1207. s1 = t("abcd")
  1208. s2 = t().join([s1])
  1209. self.assertTrue(s1 is s2)
  1210. # Should also test mixed-type join.
  1211. if t is unicode:
  1212. s1 = subclass("abcd")
  1213. s2 = "".join([s1])
  1214. self.assertTrue(s1 is not s2)
  1215. self.assertTrue(type(s2) is t)
  1216. s1 = t("abcd")
  1217. s2 = "".join([s1])
  1218. self.assertTrue(s1 is s2)
  1219. elif t is str:
  1220. s1 = subclass("abcd")
  1221. s2 = u"".join([s1])
  1222. self.assertTrue(s1 is not s2)
  1223. self.assertTrue(type(s2) is unicode) # promotes!
  1224. s1 = t("abcd")
  1225. s2 = u"".join([s1])
  1226. self.assertTrue(s1 is not s2)
  1227. self.assertTrue(type(s2) is unicode) # promotes!
  1228. else:
  1229. self.fail("unexpected type for MixinStrUnicodeTest %r" % t)