PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

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

http://github.com/IronLanguages/main
Python | 1333 lines | 1298 code | 12 blank | 23 comment | 12 complexity | cc689df153fb58716fb22ec2e9727dbe 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. # check that object.method(*args) returns result
  41. def checkequal(self, result, object, methodname, *args):
  42. result = self.fixtype(result)
  43. object = self.fixtype(object)
  44. args = self.fixtype(args)
  45. realresult = getattr(object, methodname)(*args)
  46. self.assertEqual(
  47. result,
  48. realresult
  49. )
  50. # if the original is returned make sure that
  51. # this doesn't happen with subclasses
  52. if object == realresult:
  53. class subtype(self.__class__.type2test):
  54. pass
  55. object = subtype(object)
  56. realresult = getattr(object, methodname)(*args)
  57. self.assertTrue(object is not realresult)
  58. # check that object.method(*args) raises exc
  59. def checkraises(self, exc, object, methodname, *args):
  60. object = self.fixtype(object)
  61. args = self.fixtype(args)
  62. self.assertRaises(
  63. exc,
  64. getattr(object, methodname),
  65. *args
  66. )
  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, 1)
  305. self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
  306. self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
  307. aaa = ' a '*20
  308. self.checkequal(['a']*20, aaa, 'split')
  309. self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
  310. self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
  311. # by a char
  312. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
  313. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
  314. self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
  315. self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
  316. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
  317. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
  318. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
  319. sys.maxint-2)
  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', '|', 2)
  322. self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
  323. self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
  324. self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
  325. self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
  326. self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
  327. self.checkequal(['a']*15 +['a|a|a|a|a'],
  328. ('a|'*20)[:-1], 'split', '|', 15)
  329. # by string
  330. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
  331. self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
  332. self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
  333. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
  334. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
  335. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
  336. sys.maxint-10)
  337. self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
  338. self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
  339. self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
  340. self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
  341. self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
  342. 'split', 'test')
  343. self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
  344. self.checkequal(['', ''], 'aaa', 'split', 'aaa')
  345. self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
  346. self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
  347. self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
  348. self.checkequal([''], '', 'split', 'aaa')
  349. self.checkequal(['aa'], 'aa', 'split', 'aaa')
  350. self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
  351. self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
  352. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
  353. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
  354. self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
  355. 'split', 'BLAH', 18)
  356. # mixed use of str and unicode
  357. self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
  358. # argument type
  359. self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
  360. # null case
  361. self.checkraises(ValueError, 'hello', 'split', '')
  362. self.checkraises(ValueError, 'hello', 'split', '', 0)
  363. def test_rsplit(self):
  364. self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
  365. 'this is the rsplit function', 'rsplit')
  366. # by whitespace
  367. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
  368. self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
  369. self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
  370. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
  371. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
  372. self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
  373. sys.maxint-20)
  374. self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
  375. self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
  376. self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
  377. self.checkequal([], ' ', 'rsplit')
  378. self.checkequal(['a'], ' a ', 'rsplit')
  379. self.checkequal(['a', 'b'], ' a b ', 'rsplit')
  380. self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
  381. self.checkequal([' a b','c'], ' a b c ', 'rsplit',
  382. None, 1)
  383. self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
  384. None, 2)
  385. self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
  386. aaa = ' a '*20
  387. self.checkequal(['a']*20, aaa, 'rsplit')
  388. self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
  389. self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
  390. # by a char
  391. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
  392. self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
  393. self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
  394. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
  395. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
  396. self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
  397. sys.maxint-100)
  398. self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
  399. self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
  400. self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
  401. self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
  402. self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
  403. self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
  404. self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
  405. self.checkequal(['a|a|a|a|a']+['a']*15,
  406. ('a|'*20)[:-1], 'rsplit', '|', 15)
  407. # by string
  408. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
  409. self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
  410. self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
  411. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
  412. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
  413. self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
  414. sys.maxint-5)
  415. self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
  416. self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
  417. self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
  418. self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
  419. self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
  420. 'rsplit', 'test')
  421. self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
  422. self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
  423. self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
  424. self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
  425. self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
  426. self.checkequal([''], '', 'rsplit', 'aaa')
  427. self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
  428. self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
  429. self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
  430. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
  431. self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
  432. self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
  433. 'rsplit', 'BLAH', 18)
  434. # mixed use of str and unicode
  435. self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
  436. # argument type
  437. self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
  438. # null case
  439. self.checkraises(ValueError, 'hello', 'rsplit', '')
  440. self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
  441. def test_strip(self):
  442. self.checkequal('hello', ' hello ', 'strip')
  443. self.checkequal('hello ', ' hello ', 'lstrip')
  444. self.checkequal(' hello', ' hello ', 'rstrip')
  445. self.checkequal('hello', 'hello', 'strip')
  446. # strip/lstrip/rstrip with None arg
  447. self.checkequal('hello', ' hello ', 'strip', None)
  448. self.checkequal('hello ', ' hello ', 'lstrip', None)
  449. self.checkequal(' hello', ' hello ', 'rstrip', None)
  450. self.checkequal('hello', 'hello', 'strip', None)
  451. # strip/lstrip/rstrip with str arg
  452. self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
  453. self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
  454. self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
  455. self.checkequal('hello', 'hello', 'strip', 'xyz')
  456. # strip/lstrip/rstrip with unicode arg
  457. if test_support.have_unicode:
  458. self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
  459. 'strip', unicode('xyz', 'ascii'))
  460. self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
  461. 'lstrip', unicode('xyz', 'ascii'))
  462. self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
  463. 'rstrip', unicode('xyz', 'ascii'))
  464. # XXX
  465. #self.checkequal(unicode('hello', 'ascii'), 'hello',
  466. # 'strip', unicode('xyz', 'ascii'))
  467. self.checkraises(TypeError, 'hello', 'strip', 42, 42)
  468. self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
  469. self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
  470. def test_ljust(self):
  471. self.checkequal('abc ', 'abc', 'ljust', 10)
  472. self.checkequal('abc ', 'abc', 'ljust', 6)
  473. self.checkequal('abc', 'abc', 'ljust', 3)
  474. self.checkequal('abc', 'abc', 'ljust', 2)
  475. self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
  476. self.checkraises(TypeError, 'abc', 'ljust')
  477. def test_rjust(self):
  478. self.checkequal(' abc', 'abc', 'rjust', 10)
  479. self.checkequal(' abc', 'abc', 'rjust', 6)
  480. self.checkequal('abc', 'abc', 'rjust', 3)
  481. self.checkequal('abc', 'abc', 'rjust', 2)
  482. self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
  483. self.checkraises(TypeError, 'abc', 'rjust')
  484. def test_center(self):
  485. self.checkequal(' abc ', 'abc', 'center', 10)
  486. self.checkequal(' abc ', 'abc', 'center', 6)
  487. self.checkequal('abc', 'abc', 'center', 3)
  488. self.checkequal('abc', 'abc', 'center', 2)
  489. self.checkequal('***abc****', 'abc', 'center', 10, '*')
  490. self.checkraises(TypeError, 'abc', 'center')
  491. def test_swapcase(self):
  492. self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
  493. self.checkraises(TypeError, 'hello', 'swapcase', 42)
  494. def test_replace(self):
  495. EQ = self.checkequal
  496. # Operations on the empty string
  497. EQ("", "", "replace", "", "")
  498. EQ("A", "", "replace", "", "A")
  499. EQ("", "", "replace", "A", "")
  500. EQ("", "", "replace", "A", "A")
  501. EQ("", "", "replace", "", "", 100)
  502. EQ("", "", "replace", "", "", sys.maxint)
  503. # interleave (from=="", 'to' gets inserted everywhere)
  504. EQ("A", "A", "replace", "", "")
  505. EQ("*A*", "A", "replace", "", "*")
  506. EQ("*1A*1", "A", "replace", "", "*1")
  507. EQ("*-#A*-#", "A", "replace", "", "*-#")
  508. EQ("*-A*-A*-", "AA", "replace", "", "*-")
  509. EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
  510. EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
  511. EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
  512. EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
  513. EQ("*-A*-A", "AA", "replace", "", "*-", 2)
  514. EQ("*-AA", "AA", "replace", "", "*-", 1)
  515. EQ("AA", "AA", "replace", "", "*-", 0)
  516. # single character deletion (from=="A", to=="")
  517. EQ("", "A", "replace", "A", "")
  518. EQ("", "AAA", "replace", "A", "")
  519. EQ("", "AAA", "replace", "A", "", -1)
  520. EQ("", "AAA", "replace", "A", "", sys.maxint)
  521. EQ("", "AAA", "replace", "A", "", 4)
  522. EQ("", "AAA", "replace", "A", "", 3)
  523. EQ("A", "AAA", "replace", "A", "", 2)
  524. EQ("AA", "AAA", "replace", "A", "", 1)
  525. EQ("AAA", "AAA", "replace", "A", "", 0)
  526. EQ("", "AAAAAAAAAA", "replace", "A", "")
  527. EQ("BCD", "ABACADA", "replace", "A", "")
  528. EQ("BCD", "ABACADA", "replace", "A", "", -1)
  529. EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
  530. EQ("BCD", "ABACADA", "replace", "A", "", 5)
  531. EQ("BCD", "ABACADA", "replace", "A", "", 4)
  532. EQ("BCDA", "ABACADA", "replace", "A", "", 3)
  533. EQ("BCADA", "ABACADA", "replace", "A", "", 2)
  534. EQ("BACADA", "ABACADA", "replace", "A", "", 1)
  535. EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
  536. EQ("BCD", "ABCAD", "replace", "A", "")
  537. EQ("BCD", "ABCADAA", "replace", "A", "")
  538. EQ("BCD", "BCD", "replace", "A", "")
  539. EQ("*************", "*************", "replace", "A", "")
  540. EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
  541. # substring deletion (from=="the", to=="")
  542. EQ("", "the", "replace", "the", "")
  543. EQ("ater", "theater", "replace", "the", "")
  544. EQ("", "thethe", "replace", "the", "")
  545. EQ("", "thethethethe", "replace", "the", "")
  546. EQ("aaaa", "theatheatheathea", "replace", "the", "")
  547. EQ("that", "that", "replace", "the", "")
  548. EQ("thaet", "thaet", "replace", "the", "")
  549. EQ("here and re", "here and there", "replace", "the", "")
  550. EQ("here and re and re", "here and there and there",
  551. "replace", "the", "", sys.maxint)
  552. EQ("here and re and re", "here and there and there",
  553. "replace", "the", "", -1)
  554. EQ("here and re and re", "here and there and there",
  555. "replace", "the", "", 3)
  556. EQ("here and re and re", "here and there and there",
  557. "replace", "the", "", 2)
  558. EQ("here and re and there", "here and there and there",
  559. "replace", "the", "", 1)
  560. EQ("here and there and there", "here and there and there",
  561. "replace", "the", "", 0)
  562. EQ("here and re and re", "here and there and there", "replace", "the", "")
  563. EQ("abc", "abc", "replace", "the", "")
  564. EQ("abcdefg", "abcdefg", "replace", "the", "")
  565. # substring deletion (from=="bob", to=="")
  566. EQ("bob", "bbobob", "replace", "bob", "")
  567. EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
  568. EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
  569. EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
  570. # single character replace in place (len(from)==len(to)==1)
  571. EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
  572. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
  573. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
  574. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
  575. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
  576. EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
  577. EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
  578. EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
  579. EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
  580. EQ("who goes there?", "Who goes there?", "replace", "W", "w")
  581. EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
  582. EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
  583. EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
  584. EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
  585. # substring replace in place (len(from)==len(to) > 1)
  586. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
  587. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
  588. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
  589. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
  590. EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
  591. EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
  592. EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
  593. EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
  594. EQ("cobob", "bobob", "replace", "bob", "cob")
  595. EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
  596. EQ("bobob", "bobob", "replace", "bot", "bot")
  597. # replace single character (len(from)==1, len(to)>1)
  598. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
  599. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
  600. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
  601. EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
  602. EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
  603. EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
  604. EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
  605. EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
  606. # replace substring (len(from)>1, len(to)!=len(from))
  607. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  608. "replace", "spam", "ham")
  609. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  610. "replace", "spam", "ham", sys.maxint)
  611. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  612. "replace", "spam", "ham", -1)
  613. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  614. "replace", "spam", "ham", 4)
  615. EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
  616. "replace", "spam", "ham", 3)
  617. EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
  618. "replace", "spam", "ham", 2)
  619. EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
  620. "replace", "spam", "ham", 1)
  621. EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
  622. "replace", "spam", "ham", 0)
  623. EQ("bobob", "bobobob", "replace", "bobob", "bob")
  624. EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
  625. EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
  626. with test_support.check_py3k_warnings():
  627. ba = buffer('a')
  628. bb = buffer('b')
  629. EQ("bbc", "abc", "replace", ba, bb)
  630. EQ("aac", "abc", "replace", bb, ba)
  631. #
  632. self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
  633. self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
  634. self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
  635. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
  636. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
  637. self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
  638. self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
  639. self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
  640. self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
  641. self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
  642. self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
  643. self.checkequal('abc', 'abc', 'replace', '', '-', 0)
  644. self.checkequal('', '', 'replace', '', '')
  645. self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
  646. self.checkequal('abc', 'abc', 'replace', 'xy', '--')
  647. # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
  648. # MemoryError due to empty result (platform malloc issue when requesting
  649. # 0 bytes).
  650. self.checkequal('', '123', 'replace', '123', '')
  651. self.checkequal('', '123123', 'replace', '123', '')
  652. self.checkequal('x', '123x123', 'replace', '123', '')
  653. self.checkraises(TypeError, 'hello', 'replace')
  654. self.checkraises(TypeError, 'hello', 'replace', 42)
  655. self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
  656. self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
  657. def test_replace_overflow(self):
  658. # Check for overflow checking on 32 bit machines
  659. if sys.maxint != 2147483647 or struct.calcsize("P") > 4:
  660. return
  661. A2_16 = "A" * (2**16)
  662. self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
  663. self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
  664. self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
  665. def test_zfill(self):
  666. self.checkequal('123', '123', 'zfill', 2)
  667. self.checkequal('123', '123', 'zfill', 3)
  668. self.checkequal('0123', '123', 'zfill', 4)
  669. self.checkequal('+123', '+123', 'zfill', 3)
  670. self.checkequal('+123', '+123', 'zfill', 4)
  671. self.checkequal('+0123', '+123', 'zfill', 5)
  672. self.checkequal('-123', '-123', 'zfill', 3)
  673. self.checkequal('-123', '-123', 'zfill', 4)
  674. self.checkequal('-0123', '-123', 'zfill', 5)
  675. self.checkequal('000', '', 'zfill', 3)
  676. self.checkequal('34', '34', 'zfill', 1)
  677. self.checkequal('0034', '34', 'zfill', 4)
  678. self.checkraises(TypeError, '123', 'zfill')
  679. # XXX alias for py3k forward compatibility
  680. BaseTest = CommonTest
  681. class MixinStrUnicodeUserStringTest:
  682. # additional tests that only work for
  683. # stringlike objects, i.e. str, unicode, UserString
  684. # (but not the string module)
  685. def test_islower(self):
  686. self.checkequal(False, '', 'islower')
  687. self.checkequal(True, 'a', 'islower')
  688. self.checkequal(False, 'A', 'islower')
  689. self.checkequal(False, '\n', 'islower')
  690. self.checkequal(True, 'abc', 'islower')
  691. self.checkequal(False, 'aBc', 'islower')
  692. self.checkequal(True, 'abc\n', 'islower')
  693. self.checkraises(TypeError, 'abc', 'islower', 42)
  694. def test_isupper(self):
  695. self.checkequal(False, '', 'isupper')
  696. self.checkequal(False, 'a', 'isupper')
  697. self.checkequal(True, 'A', 'isupper')
  698. self.checkequal(False, '\n', 'isupper')
  699. self.checkequal(True, 'ABC', 'isupper')
  700. self.checkequal(False, 'AbC', 'isupper')
  701. self.checkequal(True, 'ABC\n', 'isupper')
  702. self.checkraises(TypeError, 'abc', 'isupper', 42)
  703. def test_istitle(self):
  704. self.checkequal(False, '', 'istitle')
  705. self.checkequal(False, 'a', 'istitle')
  706. self.checkequal(True, 'A', 'istitle')
  707. self.checkequal(False, '\n', 'istitle')
  708. self.checkequal(True, 'A Titlecased Line', 'istitle')
  709. self.checkequal(True, 'A\nTitlecased Line', 'istitle')
  710. self.checkequal(True, 'A Titlecased, Line', 'istitle')
  711. self.checkequal(False, 'Not a capitalized String', 'istitle')
  712. self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
  713. self.checkequal(False, 'Not--a Titlecase String', 'istitle')
  714. self.checkequal(False, 'NOT', 'istitle')
  715. self.checkraises(TypeError, 'abc', 'istitle', 42)
  716. def test_isspace(self):
  717. self.checkequal(False, '', 'isspace')
  718. self.checkequal(False, 'a', 'isspace')
  719. self.checkequal(True, ' ', 'isspace')
  720. self.checkequal(True, '\t', 'isspace')
  721. self.checkequal(True, '\r', 'isspace')
  722. self.checkequal(True, '\n', 'isspace')
  723. self.checkequal(True, ' \t\r\n', 'isspace')
  724. self.checkequal(False, ' \t\r\na', 'isspace')
  725. self.checkraises(TypeError, 'abc', 'isspace', 42)
  726. def test_isalpha(self):
  727. self.checkequal(False, '', 'isalpha')
  728. self.checkequal(True, 'a', 'isalpha')
  729. self.checkequal(True, 'A', 'isalpha')
  730. self.checkequal(False, '\n', 'isalpha')
  731. self.checkequal(True, 'abc', 'isalpha')
  732. self.checkequal(False, 'aBc123', 'isalpha')
  733. self.checkequal(False, 'abc\n', 'isalpha')
  734. self.checkraises(TypeError, 'abc', 'isalpha', 42)
  735. def test_isalnum(self):
  736. self.checkequal(False, '', 'isalnum')
  737. self.checkequal(True, 'a', 'isalnum')
  738. self.checkequal(True, 'A', 'isalnum')
  739. self.checkequal(False, '\n', 'isalnum')
  740. self.checkequal(True, '123abc456', 'isalnum')
  741. self.checkequal(True, 'a1b3c', 'isalnum')
  742. self.checkequal(False, 'aBc000 ', 'isalnum')
  743. self.checkequal(False, 'abc\n', 'isalnum')
  744. self.checkraises(TypeError, 'abc', 'isalnum', 42)
  745. def test_isdigit(self):
  746. self.checkequal(False, '', 'isdigit')
  747. self.checkequal(False, 'a', 'isdigit')
  748. self.checkequal(True, '0', 'isdigit')
  749. self.checkequal(True, '0123456789', 'isdigit')
  750. self.checkequal(False, '0123456789a', 'isdigit')
  751. self.checkraises(TypeError, 'abc', 'isdigit', 42)
  752. def test_title(self):
  753. self.checkequal(' Hello ', ' hello ', 'title')
  754. self.checkequal('Hello ', 'hello ', 'title')
  755. self.checkequal('Hello ', 'Hello ', 'title')
  756. self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
  757. self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
  758. self.checkequal('Getint', "getInt", 'title')
  759. self.checkraises(TypeError, 'hello', 'title', 42)
  760. def test_splitlines(self):
  761. self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
  762. self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
  763. self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
  764. self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
  765. self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
  766. self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
  767. self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
  768. self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
  769. def test_startswith(self):
  770. self.checkequal(True, 'hello', 'startswith', 'he')
  771. self.checkequal(True, 'hello', 'startswith', 'hello')
  772. self.checkequal(False, 'hello', 'startswith', 'hello world')
  773. self.checkequal(True, 'hello', 'startswith', '')
  774. self.checkequal(False, 'hello', 'startswith', 'ello')
  775. self.checkequal(True, 'hello', 'startswith', 'ello', 1)
  776. self.checkequal(True, 'hello', 'startswith', 'o', 4)
  777. self.checkequal(False, 'hello', 'startswith', 'o', 5)
  778. self.checkequal(True, 'hello', 'startswith', '', 5)
  779. self.checkequal(False, 'hello', 'startswith', 'lo', 6)
  780. self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
  781. self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
  782. self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
  783. # test negative indices
  784. self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
  785. self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
  786. self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
  787. self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
  788. self.checkequal(False, 'hello', 'startswith', 'ello', -5)
  789. self.checkequal(True, 'hello', 'startswith', 'ello', -4)
  790. self.checkequal(False, 'hello', 'startswith', 'o', -2)
  791. self.checkequal(True, 'hello', 'startswith', 'o', -1)
  792. self.checkequal(True, 'hello', 'startswith', '', -3, -3)
  793. self.checkequal(False, 'hello', 'startswith', 'lo', -9)
  794. self.checkraises(TypeError, 'hello', 'startswith')
  795. self.checkraises(TypeError, 'hello', 'startswith', 42)
  796. # test tuple arguments
  797. self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
  798. self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
  799. self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
  800. self.checkequal(False, 'hello', 'startswith', ())
  801. self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
  802. 'rld', 'lowo'), 3)
  803. self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
  804. 'rld'), 3)
  805. self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
  806. self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
  807. self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
  808. self.checkraises(TypeError, 'hello', 'startswith', (42,))
  809. def test_endswith(self):
  810. self.checkequal(True, 'hello', 'endswith', 'lo')
  811. self.checkequal(False, 'hello', 'endswith', 'he')
  812. self.checkequal(True, 'hello', 'endswith', '')
  813. self.checkequal(False, 'hello', 'endswith', 'hello world')
  814. self.checkequal(False, 'helloworld', 'endswith', 'worl')
  815. self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
  816. self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
  817. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
  818. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
  819. self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
  820. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
  821. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
  822. self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
  823. self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
  824. # test negative indices
  825. self.checkequal(True, 'hello', 'endswith', 'lo', -2)
  826. self.checkequal(False, 'hello', 'endswith', 'he', -2)
  827. self.checkequal(True, 'hello', 'endswith', '', -3, -3)
  828. self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
  829. self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
  830. self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
  831. self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
  832. self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
  833. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
  834. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
  835. self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
  836. self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
  837. self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
  838. self.checkraises(TypeError, 'hello', 'endswith')
  839. self.checkraises(TypeError, 'hello', 'endswith', 42)
  840. # test tuple arguments
  841. self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
  842. self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
  843. self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
  844. self.checkequal(False, 'hello', 'endswith', ())
  845. self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
  846. 'rld', 'lowo'), 3)
  847. self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
  848. 'rld'), 3, -1)
  849. self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
  850. self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
  851. self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
  852. self.checkraises(TypeError, 'hello', 'endswith', (42,))
  853. def test___contains__(self):
  854. self.checkequal(True, '', '__contains__', '')
  855. self.checkequal(True, 'abc', '__contains__', '')
  856. self.checkequal(False, 'abc', '__contains__', '\0')
  857. self.checkequal(True, '\0abc', '__contains__', '\0')
  858. self.checkequal(True, 'abc\0', '__contains__', '\0')
  859. self.checkequal(True, '\0abc', '__contains__', 'a')
  860. self.checkequal(True, 'asdf', '__contains__', 'asdf')
  861. self.checkequal(False, 'asd', '__contains__', 'asdf')
  862. self.checkequal(False, '', '__contains__', 'asdf')
  863. def test_subscript(self):
  864. self.checkequal(u'a', 'abc', '__getitem__', 0)
  865. self.checkequal(u'c', 'abc', '__getitem__', -1)
  866. self.checkequal(u'a', 'abc', '__getitem__', 0L)
  867. self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
  868. self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
  869. self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
  870. self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
  871. self.checkraises(TypeError, 'abc', '__getitem__', 'def')
  872. def test_slice(self):
  873. self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
  874. self.checkequal('abc', 'abc', '__getslice__', 0, 3)
  875. self.checkequal('ab', 'abc', '__getslice__', 0, 2)
  876. self.checkequal('bc', 'abc', '__getslice__', 1, 3)
  877. self.checkequal('b', 'abc', '__getslice__', 1, 2)
  878. self.checkequal('', 'abc', '__getslice__', 2, 2)
  879. self.checkequal('', 'abc', '__getslice__', 1000, 1000)
  880. self.checkequal('', 'abc', '__getslice__', 2000, 1000)
  881. self.checkequal('', 'abc', '__getslice__', 2, 1)
  882. self.checkraises(TypeError, 'abc', '__getslice__', 'def')
  883. def test_extended_getslice(self):
  884. # Test extended slicing by comparing with list slicing.
  885. s = string.ascii_letters + string.digits
  886. indices = (0, None, 1, 3, 41, -1, -2, -37)
  887. for start in indices:
  888. for stop in indices:
  889. # Skip step 0 (invalid)
  890. for step in indices[1:]:
  891. L = list(s)[start:stop:step]
  892. self.checkequal(u"".join(L), s, '__getitem__',
  893. slice(start, stop, step))
  894. def test_mul(self):
  895. self.checkequal('', 'abc', '__mul__', -1)
  896. self.checkequal('', 'abc', '__mul__', 0)
  897. self.checkequal('abc', 'abc', '__mul__', 1)
  898. self.checkequal('abcabcabc', 'abc', '__mul__', 3)
  899. self.checkraises(TypeError, 'abc', '__mul__')
  900. self.checkraises(TypeError, 'abc', '__mul__', '')
  901. # XXX: on a 64-bit system, this doesn't raise an overflow error,
  902. # but either raises a MemoryError, or succeeds (if you have 54TiB)
  903. #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
  904. def test_join(self):
  905. # join now works with any sequence type
  906. # moved here, because the argument order is
  907. # different in string.join (see the test in
  908. # test.test_string.StringTest.test_join)
  909. self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
  910. self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
  911. self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
  912. self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
  913. self.checkequal('w x y z', ' ', 'join', Sequence())
  914. self.checkequal('abc', 'a', 'join', ('abc',))
  915. self.checkequal('z', 'a', 'join', UserList(['z']))
  916. if test_support.have_unicode:
  917. self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
  918. self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
  919. self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
  920. self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
  921. self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
  922. for i in [5, 25, 125]:
  923. self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
  924. ['a' * i] * i)
  925. self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
  926. ('a' * i,) * i)
  927. self.checkraises(TypeError, ' ', 'join', BadSeq1())
  928. self.checkequal('a b c', ' ', 'join', BadSeq2())
  929. self.checkraises(TypeError, ' ', 'join')
  930. self.checkraises(TypeError, ' ', 'join', 7)
  931. self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
  932. try:
  933. def f():
  934. yield 4 + ""
  935. self.fixtype(' ').join(f())
  936. except TypeError, e:
  937. if '+' not in str(e):
  938. self.fail('join() ate exception message')
  939. else:
  940. self.fail('exception not raised')
  941. def test_formatting(self):
  942. self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
  943. self.checkequal('+10+', '+%d+', '__mod__', 10)
  944. self.checkequal('a', "%c", '__mod__', "a")
  945. self.checkequal('a', "%c", '__mod__', "a")
  946. self.checkequal('"', "%c", '__mod__', 34)
  947. self.checkequal('$', "%c", '__mod__', 36)
  948. self.checkequal('10', "%d", '__mod__', 10)
  949. self.checkequal('\x7f', "%c", '__mod__', 0x7f)
  950. for ordinal in (-100, 0x200000):
  951. # unicode raises ValueError, str raises OverflowError
  952. self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
  953. longvalue = sys.maxint + 10L
  954. slongvalue = str(longvalue)
  955. if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
  956. self.checkequal(' 42', '%3ld', '__mod__', 42)
  957. self.checkequal('42', '%d', '__mod__', 42L)
  958. self.checkequal('42', '%d', '__mod__', 42.0)
  959. self.checkequal(slongvalue, '%d', '__mod__', longvalue)
  960. self.checkcall('%d', '__mod__', float(longvalue))
  961. self.checkequal('0042.00', '%07.2f', '__mod__', 42)
  962. self.checkequal('0042.00', '%07.2F', '__mod__', 42)
  963. self.checkraises(TypeError, 'abc', '__mod__')
  964. self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
  965. self.checkraises(TypeError, '%s%s', '__mod__', (42,))
  966. self.checkraises(TypeError, '%c', '__mod__', (None,))
  967. self.checkraises(ValueError, '%(foo', '__mod__', {})
  968. self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
  969. self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
  970. self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided
  971. # argument names with properly nested brackets are supported
  972. self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
  973. # 100 is a magic number in PyUnicode_Format, this forces a resize
  974. self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
  975. self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
  976. self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
  977. self.checkraises(ValueError, '%10', '__mod__', (42,))
  978. def test_floatformatting(self):
  979. # float formatting
  980. for prec in xrange(100):
  981. format = '%%.%if' % prec
  982. value = 0.01
  983. for x in xrange(60):
  984. value = value * 3.14159265359 / 3.0 * 10.0
  985. self.checkcall(format, "__mod__", value)
  986. def test_inplace_rewrites(self):
  987. # Check that strings don't copy and modify cached single-character strings
  988. self.checkequal('a', 'A', 'lower')
  989. self.checkequal(True, 'A', 'isupper')
  990. self.checkequal('A', 'a', 'upper')
  991. self.checkequal(True, 'a', 'islower')
  992. self.checkequal('a', 'A', 'replace', 'A', 'a')
  993. self.checkequal(True, 'A', 'isupper')
  994. self.checkequal('A', 'a', 'capitalize')
  995. self.checkequal(True, 'a', 'islower')
  996. self.checkequal('A', 'a', 'swapcase')
  997. self.checkequal(True, 'a', 'islower')
  998. self.checkequal('A', 'a', 'title')
  999. self.checkequal(True, 'a', 'islower')
  1000. def test_partition(self):
  1001. self.checkequal(('this is the par', 'ti', 'tion method'),
  1002. 'this is the partition method', 'partition', 'ti')
  1003. # from raymond's original specification
  1004. S = 'http://www.python.org'
  1005. self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
  1006. self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
  1007. self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
  1008. self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
  1009. self.checkraises(ValueError, S, 'partition', '')
  1010. self.checkraises(TypeError, S, 'partition', None)
  1011. # mixed use of str and unicode
  1012. self.assertEqual('a/b/c'.partition(u'/'), ('a', '/', 'b/c'))
  1013. def test_rpartition(self):
  1014. self.checkequal(('this is the rparti', 'ti', 'on method'),
  1015. 'this is the rpartition method', 'rpartition', 'ti')
  1016. # from raymond's original specification
  1017. S = 'http://www.python.org'
  1018. self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
  1019. self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
  1020. self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
  1021. self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
  1022. self.checkraises(ValueError, S, 'rpartition', '')
  1023. self.checkraises(TypeError, S, 'rpartition', None)
  1024. # mixed use of str and unicode
  1025. self.assertEqual('a/b/c'.rpartition(u'/'), ('a/b', '/', 'c'))
  1026. def test_none_arguments(self):
  1027. # issue 11828
  1028. s = 'hello'
  1029. self.checkequal(2, s, 'find', 'l', None)
  1030. self.checkequal(3, s, 'find', 'l', -2, None)
  1031. self.checkequal(2, s, 'find', 'l', None, -2)
  1032. self.checkequal(0, s, 'find', 'h', None, None)
  1033. self.checkequal(3, s, 'rfind', 'l', None)
  1034. self.checkequal(3, s, 'rfind', 'l', -2, None)
  1035. self.checkequal(2, s, 'rfind', 'l', None, -2)
  1036. self.checkequal(0, s, 'rfind', 'h', None, None)
  1037. self.checkequal(2, s, 'index', 'l', None)
  1038. self.checkequal(3, s, 'index', 'l', -2, None)
  1039. self.checkequal(2, s, 'index', 'l', None, -2)
  1040. self.checkequal(0, s, 'index', 'h', None, None)
  1041. self.checkequal(3, s, 'rindex', 'l', None)
  1042. self.checkequal(3, s, 'rindex', 'l', -2, None)
  1043. self.checkequal(2, s, 'rindex', 'l', None, -2)
  1044. self.checkequal(0, s, 'rindex', 'h', None, None)
  1045. self.checkequal(2, s, 'count', 'l', None)
  1046. self.checkequal(1, s, 'count', 'l', -2, None)
  1047. self.checkequal(1, s, 'count', 'l', None, -2)
  1048. self.checkequal(0, s, 'count', 'x', None, None)
  1049. self.checkequal(True, s, 'endswith', 'o', None)
  1050. self.checkequal(True, s, 'endswith', 'lo', -2, None)
  1051. self.checkequal(True, s, 'endswith', 'l', None, -2)
  1052. self.checkequal(False, s, 'endswith', 'x', None, None)
  1053. self.checkequal(True, s, 'startswith', 'h', None)
  1054. self.checkequal(True, s, 'startswith', 'l', -2, None)
  1055. self.checkequal(True, s, 'startswith', 'h', None, -2)
  1056. self.checkequal(False, s, 'startswith', 'x', None, None)
  1057. def test_find_etc_raise_correct_error_messages(self):
  1058. # issue 11828
  1059. s = 'hello'
  1060. x = 'x'
  1061. self.assertRaisesRegexp(TypeError, r'\bfind\b', s.find,
  1062. x, None, None, None)
  1063. self.assertRaisesRegexp(TypeError, r'\brfind\b', s.rfind,
  1064. x, None, None, None)
  1065. self.assertRaisesRegexp(TypeError, r'\bindex\b', s.index,
  1066. x, None, None, None)
  1067. self.assertRaisesRegexp(TypeError, r'\brindex\b', s.rindex,
  1068. x, None, None, None)
  1069. self.assertRaisesRegexp(TypeError, r'^count\(', s.count,
  1070. x, None, None, None)
  1071. self.assertRaisesRegexp(TypeError, r'^startswith\(', s.startswith,
  1072. x, None, None, None)
  1073. self.assertRaisesRegexp(TypeError, r'^endswith\(', s.endswith,
  1074. x, None, None, None)
  1075. class MixinStrStringUserStringTest:
  1076. # Additional tests for 8bit strings, i.e. str, UserString and
  1077. # the string module
  1078. def test_maketrans(self):
  1079. self.assertEqual(
  1080. ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
  1081. string.maketrans('abc', 'xyz')
  1082. )
  1083. self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
  1084. def test_translate(self):
  1085. table = string.maketrans('abc', 'xyz')
  1086. self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
  1087. table = string.maketrans('a', 'A')
  1088. self.checkequal('Abc', 'abc', 'translate', table)
  1089. self.checkequal('xyz', 'xyz', 'translate', table)
  1090. self.checkequal('yz', 'xyz', 'translate', table, 'x')
  1091. self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
  1092. self.checkequal('zyzzx', 'zyzzx', 'translate', None, '')
  1093. self.checkequal('zyzzx', 'zyzzx', 'translate', None)
  1094. self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
  1095. self.checkraises(ValueError, 'xyz', 'translate', 'too short')
  1096. class MixinStrUserStringTest:
  1097. # Additional tests that only work with
  1098. # 8bit compatible object, i.e. str and UserString
  1099. if test_support.have_unicode:
  1100. def test_encoding_decoding(self):
  1101. codecs = [('rot13', 'uryyb jbeyq'),
  1102. ('base64', 'aGVsbG8gd29ybGQ=\n'),
  1103. ('hex', '68656c6c6f20776f726c64'),
  1104. ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
  1105. for encoding, data in codecs:
  1106. self.checkequal(data, 'hello world', 'encode', encoding)
  1107. self.checkequal('hello world', data, 'decode', encoding)
  1108. # zlib is optional, so we make the test optional too...
  1109. try:
  1110. import zlib
  1111. except ImportError:
  1112. pass
  1113. else:
  1114. data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
  1115. self.checkequal(data, 'hello world', 'encode', 'zlib')
  1116. self.checkequal('hello world', data, 'decode', 'zlib')
  1117. self.checkraises(TypeError, 'xyz', 'decode', 42)
  1118. self.checkraises(TypeError, 'xyz', 'encode', 42)
  1119. class MixinStrUnicodeTest:
  1120. # Additional tests that only work with str and unicode.
  1121. def test_bug1001011(self):
  1122. # Make sure join returns a NEW object for single item sequences
  1123. # involving a subclass.
  1124. # Make sure that it is of the appropriate type.
  1125. # Check the optimisation still occurs for standard objects.
  1126. t = self.type2test
  1127. class subclass(t):
  1128. pass
  1129. s1 = subclass("abcd")
  1130. s2 = t().join([s1])
  1131. self.assertTrue(s1 is not s2)
  1132. self.assertTrue(type(s2) is t)
  1133. s1 = t("abcd")
  1134. s2 = t().join([s1])
  1135. self.assertTrue(s1 is s2)
  1136. # Should also test mixed-type join.
  1137. if t is unicode:
  1138. s1 = subclass("abcd")
  1139. s2 = "".join([s1])
  1140. self.assertTrue(s1 is not s2)
  1141. self.assertTrue(type(s2) is t)
  1142. s1 = t("abcd")
  1143. s2 = "".join([s1])
  1144. self.assertTrue(s1 is s2)
  1145. elif t is str:
  1146. s1 = subclass("abcd")
  1147. s2 = u"".join([s1])
  1148. self.assertTrue(s1 is not s2)
  1149. self.assertTrue(type(s2) is unicode) # promotes!
  1150. s1 = t("abcd")
  1151. s2 = u"".join([s1])
  1152. self.assertTrue(s1 is not s2)
  1153. self.assertTrue(type(s2) is unicode) # promotes!
  1154. else:
  1155. self.fail("unexpected type for MixinStrUnicodeTest %r" % t)