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