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