Debian Codegraph @

Lib/test/string_tests.py

raw
1 """
2 Common tests shared by test_unicode, test_userstring and test_bytes.
3 """
4
5 import unittest, string, sys, struct
6 from test import support
7 from test.support import import_helper
8 from collections import UserList
9 import random
10
11
12 class Sequence:
13 def __init__(self, seq='wxyz'): self.seq = seq
14 def __len__(self): return len(self.seq)
15 def __getitem__(self, i): return self.seq[i]
16
17
18 class BaseTest:
19 # These tests are for buffers of values (bytes) and not
20 # specific to character interpretation, used for bytes objects
21 # and various string implementations
22
23 # The type to be tested
24 # Change in subclasses to change the behaviour of fixtype()
25 type2test = None
26
27 # Whether the "contained items" of the container are integers in
28 # range(0, 256) (i.e. bytes, bytearray) or strings of length 1
29 # (str)
30 contains_bytes = False
31
32 # All tests pass their arguments to the testing methods
33 # as str objects. fixtype() can be used to propagate
34 # these arguments to the appropriate type
35 def fixtype(self, obj):
36 if isinstance(obj, str):
37 return self.__class__.type2test(obj)
38 elif isinstance(obj, list):
39 return [self.fixtype(x) for x in obj]
40 elif isinstance(obj, tuple):
41 return tuple([self.fixtype(x) for x in obj])
42 elif isinstance(obj, dict):
43 return dict([
44 (self.fixtype(key), self.fixtype(value))
45 for (key, value) in obj.items()
46 ])
47 else:
48 return obj
49
50 def test_fixtype(self):
51 self.assertIs(type(self.fixtype("123")), self.type2test)
52
53 # check that obj.method(*args) returns result
54 def checkequal(self, result, obj, methodname, *args, **kwargs):
55 result = self.fixtype(result)
56 obj = self.fixtype(obj)
57 args = self.fixtype(args)
58 kwargs = {k: self.fixtype(v) for k,v in kwargs.items()}
59 realresult = getattr(obj, methodname)(*args, **kwargs)
60 self.assertEqual(
61 result,
62 realresult
63 )
64 # if the original is returned make sure that
65 # this doesn't happen with subclasses
66 if obj is realresult:
67 try:
68 class subtype(self.__class__.type2test):
69 pass
70 except TypeError:
71 pass # Skip this if we can't subclass
72 else:
73 obj = subtype(obj)
74 realresult = getattr(obj, methodname)(*args)
75 self.assertIsNot(obj, realresult)
76
77 # check that obj.method(*args) raises exc
78 def checkraises(self, exc, obj, methodname, *args, expected_msg=None):
79 obj = self.fixtype(obj)
80 args = self.fixtype(args)
81 with self.assertRaises(exc) as cm:
82 getattr(obj, methodname)(*args)
83 self.assertNotEqual(str(cm.exception), '')
84 if expected_msg is not None:
85 self.assertEqual(str(cm.exception), expected_msg)
86
87 # call obj.method(*args) without any checks
88 def checkcall(self, obj, methodname, *args):
89 obj = self.fixtype(obj)
90 args = self.fixtype(args)
91 getattr(obj, methodname)(*args)
92
93 def _get_teststrings(self, charset, digits):
94 base = len(charset)
95 teststrings = set()
96 for i in range(base ** digits):
97 entry = []
98 for j in range(digits):
99 i, m = divmod(i, base)
100 entry.append(charset[m])
101 teststrings.add(''.join(entry))
102 teststrings = [self.fixtype(ts) for ts in teststrings]
103 return teststrings
104
105 def test_count(self):
106 self.checkequal(3, 'aaa', 'count', 'a')
107 self.checkequal(0, 'aaa', 'count', 'b')
108 self.checkequal(3, 'aaa', 'count', 'a')
109 self.checkequal(0, 'aaa', 'count', 'b')
110 self.checkequal(3, 'aaa', 'count', 'a')
111 self.checkequal(0, 'aaa', 'count', 'b')
112 self.checkequal(0, 'aaa', 'count', 'b')
113 self.checkequal(2, 'aaa', 'count', 'a', 1)
114 self.checkequal(0, 'aaa', 'count', 'a', 10)
115 self.checkequal(1, 'aaa', 'count', 'a', -1)
116 self.checkequal(3, 'aaa', 'count', 'a', -10)
117 self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
118 self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
119 self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
120 self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
121 self.checkequal(3, 'aaa', 'count', '', 1)
122 self.checkequal(1, 'aaa', 'count', '', 3)
123 self.checkequal(0, 'aaa', 'count', '', 10)
124 self.checkequal(2, 'aaa', 'count', '', -1)
125 self.checkequal(4, 'aaa', 'count', '', -10)
126
127 self.checkequal(1, '', 'count', '')
128 self.checkequal(0, '', 'count', '', 1, 1)
129 self.checkequal(0, '', 'count', '', sys.maxsize, 0)
130
131 self.checkequal(0, '', 'count', 'xx')
132 self.checkequal(0, '', 'count', 'xx', 1, 1)
133 self.checkequal(0, '', 'count', 'xx', sys.maxsize, 0)
134
135 self.checkraises(TypeError, 'hello', 'count')
136
137 if self.contains_bytes:
138 self.checkequal(0, 'hello', 'count', 42)
139 else:
140 self.checkraises(TypeError, 'hello', 'count', 42)
141
142 # For a variety of combinations,
143 # verify that str.count() matches an equivalent function
144 # replacing all occurrences and then differencing the string lengths
145 teststrings = self._get_teststrings(['', 'a', 'b'], 7)
146 for i in teststrings:
147 n = len(i)
148 for j in teststrings:
149 r1 = i.count(j)
150 if j:
151 r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))),
152 len(j))
153 else:
154 r2, rem = len(i)+1, 0
155 if rem or r1 != r2:
156 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
157 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
158
159 def test_count_keyword(self):
160 self.assertEqual('aa'.replace('a', 'b', 0), 'aa'.replace('a', 'b', count=0))
161 self.assertEqual('aa'.replace('a', 'b', 1), 'aa'.replace('a', 'b', count=1))
162 self.assertEqual('aa'.replace('a', 'b', 2), 'aa'.replace('a', 'b', count=2))
163 self.assertEqual('aa'.replace('a', 'b', 3), 'aa'.replace('a', 'b', count=3))
164
165 def test_find(self):
166 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
167 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
168 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
169
170 self.checkequal(0, 'abc', 'find', '', 0)
171 self.checkequal(3, 'abc', 'find', '', 3)
172 self.checkequal(-1, 'abc', 'find', '', 4)
173
174 # to check the ability to pass None as defaults
175 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
176 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
177 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
178 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
179 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
180
181 self.checkraises(TypeError, 'hello', 'find')
182
183 if self.contains_bytes:
184 self.checkequal(-1, 'hello', 'find', 42)
185 else:
186 self.checkraises(TypeError, 'hello', 'find', 42)
187
188 self.checkequal(0, '', 'find', '')
189 self.checkequal(-1, '', 'find', '', 1, 1)
190 self.checkequal(-1, '', 'find', '', sys.maxsize, 0)
191
192 self.checkequal(-1, '', 'find', 'xx')
193 self.checkequal(-1, '', 'find', 'xx', 1, 1)
194 self.checkequal(-1, '', 'find', 'xx', sys.maxsize, 0)
195
196 # issue 7458
197 self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0)
198
199 # For a variety of combinations,
200 # verify that str.find() matches __contains__
201 # and that the found substring is really at that location
202 teststrings = self._get_teststrings(['', 'a', 'b', 'c'], 5)
203 for i in teststrings:
204 for j in teststrings:
205 loc = i.find(j)
206 r1 = (loc != -1)
207 r2 = j in i
208 self.assertEqual(r1, r2)
209 if loc != -1:
210 self.assertEqual(i[loc:loc+len(j)], j)
211
212 def test_rfind(self):
213 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
214 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
215 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
216 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
217
218 self.checkequal(3, 'abc', 'rfind', '', 0)
219 self.checkequal(3, 'abc', 'rfind', '', 3)
220 self.checkequal(-1, 'abc', 'rfind', '', 4)
221
222 # to check the ability to pass None as defaults
223 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
224 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
225 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
226 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
227 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
228
229 self.checkraises(TypeError, 'hello', 'rfind')
230
231 if self.contains_bytes:
232 self.checkequal(-1, 'hello', 'rfind', 42)
233 else:
234 self.checkraises(TypeError, 'hello', 'rfind', 42)
235
236 # For a variety of combinations,
237 # verify that str.rfind() matches __contains__
238 # and that the found substring is really at that location
239 teststrings = self._get_teststrings(['', 'a', 'b', 'c'], 5)
240 for i in teststrings:
241 for j in teststrings:
242 loc = i.rfind(j)
243 r1 = (loc != -1)
244 r2 = j in i
245 self.assertEqual(r1, r2)
246 if loc != -1:
247 self.assertEqual(i[loc:loc+len(j)], j)
248
249 # issue 7458
250 self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0)
251
252 # issue #15534
253 self.checkequal(0, '<......\u043c...', "rfind", "<")
254
255 def test_index(self):
256 self.checkequal(0, 'abcdefghiabc', 'index', '')
257 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
258 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
259 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
260
261 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
262 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
263 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
264 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
265
266 # to check the ability to pass None as defaults
267 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
268 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
269 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
270 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
271 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
272
273 self.checkraises(TypeError, 'hello', 'index')
274
275 if self.contains_bytes:
276 self.checkraises(ValueError, 'hello', 'index', 42)
277 else:
278 self.checkraises(TypeError, 'hello', 'index', 42)
279
280 # For a variety of combinations,
281 # verify that str.index() matches __contains__
282 # and that the found substring is really at that location
283 teststrings = self._get_teststrings(['', 'a', 'b', 'c'], 5)
284 for i in teststrings:
285 for j in teststrings:
286 if j in i:
287 loc = i.index(j)
288 self.assertGreaterEqual(loc, 0)
289 self.assertEqual(i[loc:loc+len(j)], j)
290 else:
291 self.assertRaises(ValueError, i.index, j)
292
293 def test_rindex(self):
294 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
295 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
296 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
297 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
298
299 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
300 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
301 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
302 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
303 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
304
305 # to check the ability to pass None as defaults
306 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
307 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
308 self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
309 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
310 self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
311
312 self.checkraises(TypeError, 'hello', 'rindex')
313
314 if self.contains_bytes:
315 self.checkraises(ValueError, 'hello', 'rindex', 42)
316 else:
317 self.checkraises(TypeError, 'hello', 'rindex', 42)
318
319 # For a variety of combinations,
320 # verify that str.rindex() matches __contains__
321 # and that the found substring is really at that location
322 teststrings = self._get_teststrings(['', 'a', 'b', 'c'], 5)
323 for i in teststrings:
324 for j in teststrings:
325 if j in i:
326 loc = i.rindex(j)
327 self.assertGreaterEqual(loc, 0)
328 self.assertEqual(i[loc:loc+len(j)], j)
329 else:
330 self.assertRaises(ValueError, i.rindex, j)
331
332 def test_find_periodic_pattern(self):
333 """Cover the special path for periodic patterns."""
334 def reference_find(p, s):
335 for i in range(len(s)):
336 if s.startswith(p, i):
337 return i
338 if p == '' and s == '':
339 return 0
340 return -1
341
342 def check_pattern(rr):
343 choices = random.choices
344 p0 = ''.join(choices('abcde', k=rr(10))) * rr(10, 20)
345 p = p0[:len(p0) - rr(10)] # pop off some characters
346 left = ''.join(choices('abcdef', k=rr(2000)))
347 right = ''.join(choices('abcdef', k=rr(2000)))
348 text = left + p + right
349 with self.subTest(p=p, text=text):
350 self.checkequal(reference_find(p, text),
351 text, 'find', p)
352
353 rr = random.randrange
354 for _ in range(1000):
355 check_pattern(rr)
356
357 # Test that empty string always work:
358 check_pattern(lambda *args: 0)
359
360 def test_find_many_lengths(self):
361 haystack_repeats = [a * 10**e for e in range(6) for a in (1,2,5)]
362 haystacks = [(n, self.fixtype("abcab"*n + "da")) for n in haystack_repeats]
363
364 needle_repeats = [a * 10**e for e in range(6) for a in (1, 3)]
365 needles = [(m, self.fixtype("abcab"*m + "da")) for m in needle_repeats]
366
367 for n, haystack1 in haystacks:
368 haystack2 = haystack1[:-1]
369 for m, needle in needles:
370 answer1 = 5 * (n - m) if m <= n else -1
371 self.assertEqual(haystack1.find(needle), answer1, msg=(n,m))
372 self.assertEqual(haystack2.find(needle), -1, msg=(n,m))
373
374 def test_adaptive_find(self):
375 # This would be very slow for the naive algorithm,
376 # but str.find() should be O(n + m).
377 for N in 1000, 10_000, 100_000, 1_000_000:
378 A, B = 'a' * N, 'b' * N
379 haystack = A + A + B + A + A
380 needle = A + B + B + A
381 self.checkequal(-1, haystack, 'find', needle)
382 self.checkequal(0, haystack, 'count', needle)
383 self.checkequal(len(haystack), haystack + needle, 'find', needle)
384 self.checkequal(1, haystack + needle, 'count', needle)
385
386 def test_find_with_memory(self):
387 # Test the "Skip with memory" path in the two-way algorithm.
388 for N in 1000, 3000, 10_000, 30_000:
389 needle = 'ab' * N
390 haystack = ('ab'*(N-1) + 'b') * 2
391 self.checkequal(-1, haystack, 'find', needle)
392 self.checkequal(0, haystack, 'count', needle)
393 self.checkequal(len(haystack), haystack + needle, 'find', needle)
394 self.checkequal(1, haystack + needle, 'count', needle)
395
396 def test_find_shift_table_overflow(self):
397 """When the table of 8-bit shifts overflows."""
398 N = 2**8 + 100
399
400 # first check the periodic case
401 # here, the shift for 'b' is N + 1.
402 pattern1 = 'a' * N + 'b' + 'a' * N
403 text1 = 'babbaa' * N + pattern1
404 self.checkequal(len(text1)-len(pattern1),
405 text1, 'find', pattern1)
406
407 # now check the non-periodic case
408 # here, the shift for 'd' is 3*(N+1)+1
409 pattern2 = 'ddd' + 'abc' * N + "eee"
410 text2 = pattern2[:-1] + "ddeede" * 2 * N + pattern2 + "de" * N
411 self.checkequal(len(text2) - N*len("de") - len(pattern2),
412 text2, 'find', pattern2)
413
414 def test_lower(self):
415 self.checkequal('hello', 'HeLLo', 'lower')
416 self.checkequal('hello', 'hello', 'lower')
417 self.checkraises(TypeError, 'hello', 'lower', 42)
418
419 def test_upper(self):
420 self.checkequal('HELLO', 'HeLLo', 'upper')
421 self.checkequal('HELLO', 'HELLO', 'upper')
422 self.checkraises(TypeError, 'hello', 'upper', 42)
423
424 def test_expandtabs(self):
425 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
426 'expandtabs')
427 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
428 'expandtabs', 8)
429 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
430 'expandtabs', 4)
431 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
432 'expandtabs')
433 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
434 'expandtabs', 8)
435 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
436 'expandtabs', 4)
437 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi',
438 'expandtabs', 4)
439 # check keyword args
440 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
441 'expandtabs', tabsize=8)
442 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
443 'expandtabs', tabsize=4)
444
445 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
446
447 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
448 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
449 if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
450 self.checkraises(OverflowError,
451 '\ta\n\tb', 'expandtabs', sys.maxsize)
452
453 def test_split(self):
454 # by a char
455 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
456 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
457 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
458 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
459 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
460 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
461 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
462 sys.maxsize-2)
463 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
464 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
465 self.checkequal(['abcd'], 'abcd', 'split', '|')
466 self.checkequal([''], '', 'split', '|')
467 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
468 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
469 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
470 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
471
472 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
473 self.checkequal(['a']*15 +['a|a|a|a|a'],
474 ('a|'*20)[:-1], 'split', '|', 15)
475
476 # by string
477 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
478 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
479 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
480 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
481 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
482 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
483 sys.maxsize-10)
484 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
485 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
486 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
487 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
488 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
489 'split', 'test')
490 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
491 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
492 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
493 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
494 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
495 self.checkequal([''], '', 'split', 'aaa')
496 self.checkequal(['aa'], 'aa', 'split', 'aaa')
497 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
498 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
499
500 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
501 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
502 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
503 'split', 'BLAH', 18)
504
505 # with keyword args
506 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', sep='|')
507 self.checkequal(['a', 'b|c|d'],
508 'a|b|c|d', 'split', '|', maxsplit=1)
509 self.checkequal(['a', 'b|c|d'],
510 'a|b|c|d', 'split', sep='|', maxsplit=1)
511 self.checkequal(['a', 'b|c|d'],
512 'a|b|c|d', 'split', maxsplit=1, sep='|')
513 self.checkequal(['a', 'b c d'],
514 'a b c d', 'split', maxsplit=1)
515
516 # argument type
517 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
518
519 # null case
520 self.checkraises(ValueError, 'hello', 'split', '')
521 self.checkraises(ValueError, 'hello', 'split', '', 0)
522
523 def test_rsplit(self):
524 # without arg
525 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit')
526 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit')
527 self.checkequal([], '', 'rsplit')
528
529 # by a char
530 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
531 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
532 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
533 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
534 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
535 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
536 sys.maxsize-100)
537 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
538 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
539 self.checkequal(['abcd'], 'abcd', 'rsplit', '|')
540 self.checkequal([''], '', 'rsplit', '|')
541 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
542 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
543 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
544
545 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
546
547 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
548 self.checkequal(['a|a|a|a|a']+['a']*15,
549 ('a|'*20)[:-1], 'rsplit', '|', 15)
550
551 # by string
552 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
553 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
554 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
555 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
556 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
557 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
558 sys.maxsize-5)
559 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
560 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
561 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
562 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
563 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
564 'rsplit', 'test')
565 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
566 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
567 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
568 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
569 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
570 self.checkequal([''], '', 'rsplit', 'aaa')
571 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
572 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
573 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
574
575 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
576 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
577 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
578 'rsplit', 'BLAH', 18)
579
580 # with keyword args
581 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', sep='|')
582 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', sep=None)
583 self.checkequal(['a b c', 'd'],
584 'a b c d', 'rsplit', sep=None, maxsplit=1)
585 self.checkequal(['a|b|c', 'd'],
586 'a|b|c|d', 'rsplit', '|', maxsplit=1)
587 self.checkequal(['a|b|c', 'd'],
588 'a|b|c|d', 'rsplit', sep='|', maxsplit=1)
589 self.checkequal(['a|b|c', 'd'],
590 'a|b|c|d', 'rsplit', maxsplit=1, sep='|')
591 self.checkequal(['a b c', 'd'],
592 'a b c d', 'rsplit', maxsplit=1)
593
594 # argument type
595 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
596
597 # null case
598 self.checkraises(ValueError, 'hello', 'rsplit', '')
599 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
600
601 def test_replace(self):
602 EQ = self.checkequal
603
604 # Operations on the empty string
605 EQ("", "", "replace", "", "")
606 EQ("A", "", "replace", "", "A")
607 EQ("", "", "replace", "A", "")
608 EQ("", "", "replace", "A", "A")
609 EQ("", "", "replace", "", "", 100)
610 EQ("A", "", "replace", "", "A", 100)
611 EQ("", "", "replace", "", "", sys.maxsize)
612
613 # interleave (from=="", 'to' gets inserted everywhere)
614 EQ("A", "A", "replace", "", "")
615 EQ("*A*", "A", "replace", "", "*")
616 EQ("*1A*1", "A", "replace", "", "*1")
617 EQ("*-#A*-#", "A", "replace", "", "*-#")
618 EQ("*-A*-A*-", "AA", "replace", "", "*-")
619 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
620 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize)
621 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
622 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
623 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
624 EQ("*-AA", "AA", "replace", "", "*-", 1)
625 EQ("AA", "AA", "replace", "", "*-", 0)
626
627 # single character deletion (from=="A", to=="")
628 EQ("", "A", "replace", "A", "")
629 EQ("", "AAA", "replace", "A", "")
630 EQ("", "AAA", "replace", "A", "", -1)
631 EQ("", "AAA", "replace", "A", "", sys.maxsize)
632 EQ("", "AAA", "replace", "A", "", 4)
633 EQ("", "AAA", "replace", "A", "", 3)
634 EQ("A", "AAA", "replace", "A", "", 2)
635 EQ("AA", "AAA", "replace", "A", "", 1)
636 EQ("AAA", "AAA", "replace", "A", "", 0)
637 EQ("", "AAAAAAAAAA", "replace", "A", "")
638 EQ("BCD", "ABACADA", "replace", "A", "")
639 EQ("BCD", "ABACADA", "replace", "A", "", -1)
640 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize)
641 EQ("BCD", "ABACADA", "replace", "A", "", 5)
642 EQ("BCD", "ABACADA", "replace", "A", "", 4)
643 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
644 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
645 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
646 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
647 EQ("BCD", "ABCAD", "replace", "A", "")
648 EQ("BCD", "ABCADAA", "replace", "A", "")
649 EQ("BCD", "BCD", "replace", "A", "")
650 EQ("*************", "*************", "replace", "A", "")
651 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
652
653 # substring deletion (from=="the", to=="")
654 EQ("", "the", "replace", "the", "")
655 EQ("ater", "theater", "replace", "the", "")
656 EQ("", "thethe", "replace", "the", "")
657 EQ("", "thethethethe", "replace", "the", "")
658 EQ("aaaa", "theatheatheathea", "replace", "the", "")
659 EQ("that", "that", "replace", "the", "")
660 EQ("thaet", "thaet", "replace", "the", "")
661 EQ("here and re", "here and there", "replace", "the", "")
662 EQ("here and re and re", "here and there and there",
663 "replace", "the", "", sys.maxsize)
664 EQ("here and re and re", "here and there and there",
665 "replace", "the", "", -1)
666 EQ("here and re and re", "here and there and there",
667 "replace", "the", "", 3)
668 EQ("here and re and re", "here and there and there",
669 "replace", "the", "", 2)
670 EQ("here and re and there", "here and there and there",
671 "replace", "the", "", 1)
672 EQ("here and there and there", "here and there and there",
673 "replace", "the", "", 0)
674 EQ("here and re and re", "here and there and there", "replace", "the", "")
675
676 EQ("abc", "abc", "replace", "the", "")
677 EQ("abcdefg", "abcdefg", "replace", "the", "")
678
679 # substring deletion (from=="bob", to=="")
680 EQ("bob", "bbobob", "replace", "bob", "")
681 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
682 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
683 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
684
685 # single character replace in place (len(from)==len(to)==1)
686 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
687 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
688 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize)
689 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
690 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
691 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
692 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
693 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
694
695 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
696 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
697 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
698 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
699 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
700
701 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
702
703 # substring replace in place (len(from)==len(to) > 1)
704 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
705 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize)
706 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
707 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
708 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
709 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
710 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
711 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
712 EQ("cobob", "bobob", "replace", "bob", "cob")
713 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
714 EQ("bobob", "bobob", "replace", "bot", "bot")
715
716 # replace single character (len(from)==1, len(to)>1)
717 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
718 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
719 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize)
720 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
721 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
722 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
723 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
724 # issue #15534
725 EQ('...\u043c......&lt;', '...\u043c......<', "replace", "<", "&lt;")
726
727 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
728
729 # replace substring (len(from)>1, len(to)!=len(from))
730 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
731 "replace", "spam", "ham")
732 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
733 "replace", "spam", "ham", sys.maxsize)
734 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
735 "replace", "spam", "ham", -1)
736 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
737 "replace", "spam", "ham", 4)
738 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
739 "replace", "spam", "ham", 3)
740 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
741 "replace", "spam", "ham", 2)
742 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
743 "replace", "spam", "ham", 1)
744 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
745 "replace", "spam", "ham", 0)
746
747 EQ("bobob", "bobobob", "replace", "bobob", "bob")
748 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
749 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
750
751 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
752 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
753 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
754 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
755 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
756 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
757 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
758 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
759 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
760 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
761 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
762 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
763 self.checkequal('', '', 'replace', '', '')
764 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
765 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
766 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
767 # MemoryError due to empty result (platform malloc issue when requesting
768 # 0 bytes).
769 self.checkequal('', '123', 'replace', '123', '')
770 self.checkequal('', '123123', 'replace', '123', '')
771 self.checkequal('x', '123x123', 'replace', '123', '')
772
773 self.checkraises(TypeError, 'hello', 'replace')
774 self.checkraises(TypeError, 'hello', 'replace', 42)
775 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
776 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
777
778 def test_replacement_on_buffer_boundary(self):
779 # gh-127971: Check we don't read past the end of the buffer when a
780 # potential match misses on the last character.
781 any_3_nonblank_codepoints = '!!!'
782 seven_codepoints = any_3_nonblank_codepoints + ' ' + any_3_nonblank_codepoints
783 a = (' ' * 243) + seven_codepoints + (' ' * 7)
784 b = ' ' * 6 + chr(256)
785 a.replace(seven_codepoints, b)
786
787 def test_replace_uses_two_way_maxcount(self):
788 # Test that maxcount works in _two_way_count in fastsearch.h
789 A, B = "A"*1000, "B"*1000
790 AABAA = A + A + B + A + A
791 ABBA = A + B + B + A
792 self.checkequal(AABAA + ABBA,
793 AABAA + ABBA, 'replace', ABBA, "ccc", 0)
794 self.checkequal(AABAA + "ccc",
795 AABAA + ABBA, 'replace', ABBA, "ccc", 1)
796 self.checkequal(AABAA + "ccc",
797 AABAA + ABBA, 'replace', ABBA, "ccc", 2)
798
799 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
800 'only applies to 32-bit platforms')
801 def test_replace_overflow(self):
802 # Check for overflow checking on 32 bit machines
803 A2_16 = "A" * (2**16)
804 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
805 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
806 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
807
808 def test_removeprefix(self):
809 self.checkequal('am', 'spam', 'removeprefix', 'sp')
810 self.checkequal('spamspam', 'spamspamspam', 'removeprefix', 'spam')
811 self.checkequal('spam', 'spam', 'removeprefix', 'python')
812 self.checkequal('spam', 'spam', 'removeprefix', 'spider')
813 self.checkequal('spam', 'spam', 'removeprefix', 'spam and eggs')
814
815 self.checkequal('', '', 'removeprefix', '')
816 self.checkequal('', '', 'removeprefix', 'abcde')
817 self.checkequal('abcde', 'abcde', 'removeprefix', '')
818 self.checkequal('', 'abcde', 'removeprefix', 'abcde')
819
820 self.checkraises(TypeError, 'hello', 'removeprefix')
821 self.checkraises(TypeError, 'hello', 'removeprefix', 42)
822 self.checkraises(TypeError, 'hello', 'removeprefix', 42, 'h')
823 self.checkraises(TypeError, 'hello', 'removeprefix', 'h', 42)
824 self.checkraises(TypeError, 'hello', 'removeprefix', ("he", "l"))
825
826 def test_removesuffix(self):
827 self.checkequal('sp', 'spam', 'removesuffix', 'am')
828 self.checkequal('spamspam', 'spamspamspam', 'removesuffix', 'spam')
829 self.checkequal('spam', 'spam', 'removesuffix', 'python')
830 self.checkequal('spam', 'spam', 'removesuffix', 'blam')
831 self.checkequal('spam', 'spam', 'removesuffix', 'eggs and spam')
832
833 self.checkequal('', '', 'removesuffix', '')
834 self.checkequal('', '', 'removesuffix', 'abcde')
835 self.checkequal('abcde', 'abcde', 'removesuffix', '')
836 self.checkequal('', 'abcde', 'removesuffix', 'abcde')
837
838 self.checkraises(TypeError, 'hello', 'removesuffix')
839 self.checkraises(TypeError, 'hello', 'removesuffix', 42)
840 self.checkraises(TypeError, 'hello', 'removesuffix', 42, 'h')
841 self.checkraises(TypeError, 'hello', 'removesuffix', 'h', 42)
842 self.checkraises(TypeError, 'hello', 'removesuffix', ("lo", "l"))
843
844 def test_capitalize(self):
845 self.checkequal(' hello ', ' hello ', 'capitalize')
846 self.checkequal('Hello ', 'Hello ','capitalize')
847 self.checkequal('Hello ', 'hello ','capitalize')
848 self.checkequal('Aaaa', 'aaaa', 'capitalize')
849 self.checkequal('Aaaa', 'AaAa', 'capitalize')
850
851 self.checkraises(TypeError, 'hello', 'capitalize', 42)
852
853 def test_additional_split(self):
854 self.checkequal(['this', 'is', 'the', 'split', 'function'],
855 'this is the split function', 'split')
856
857 # by whitespace
858 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
859 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
860 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
861 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
862 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
863 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
864 sys.maxsize-1)
865 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
866 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
867 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
868
869 self.checkequal([], ' ', 'split')
870 self.checkequal(['a'], ' a ', 'split')
871 self.checkequal(['a', 'b'], ' a b ', 'split')
872 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
873 self.checkequal(['a b c '], ' a b c ', 'split', None, 0)
874 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
875 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
876 self.checkequal(['a', 'b', 'c'], ' a b c ', 'split', None, 3)
877 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
878 aaa = ' a '*20
879 self.checkequal(['a']*20, aaa, 'split')
880 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
881 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
882
883 for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
884 'arf\fbarf', 'arf\vbarf'):
885 self.checkequal(['arf', 'barf'], b, 'split')
886 self.checkequal(['arf', 'barf'], b, 'split', None)
887 self.checkequal(['arf', 'barf'], b, 'split', None, 2)
888
889 def test_additional_rsplit(self):
890 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
891 'this is the rsplit function', 'rsplit')
892
893 # by whitespace
894 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
895 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
896 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
897 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
898 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
899 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
900 sys.maxsize-20)
901 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
902 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
903 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
904
905 self.checkequal([], ' ', 'rsplit')
906 self.checkequal(['a'], ' a ', 'rsplit')
907 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
908 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
909 self.checkequal([' a b c'], ' a b c ', 'rsplit',
910 None, 0)
911 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
912 None, 1)
913 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
914 None, 2)
915 self.checkequal(['a', 'b', 'c'], ' a b c ', 'rsplit',
916 None, 3)
917 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
918 aaa = ' a '*20
919 self.checkequal(['a']*20, aaa, 'rsplit')
920 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
921 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
922
923 for b in ('arf\tbarf', 'arf\nbarf', 'arf\rbarf',
924 'arf\fbarf', 'arf\vbarf'):
925 self.checkequal(['arf', 'barf'], b, 'rsplit')
926 self.checkequal(['arf', 'barf'], b, 'rsplit', None)
927 self.checkequal(['arf', 'barf'], b, 'rsplit', None, 2)
928
929 def test_strip_whitespace(self):
930 self.checkequal('hello', ' hello ', 'strip')
931 self.checkequal('hello ', ' hello ', 'lstrip')
932 self.checkequal(' hello', ' hello ', 'rstrip')
933 self.checkequal('hello', 'hello', 'strip')
934
935 b = ' \t\n\r\f\vabc \t\n\r\f\v'
936 self.checkequal('abc', b, 'strip')
937 self.checkequal('abc \t\n\r\f\v', b, 'lstrip')
938 self.checkequal(' \t\n\r\f\vabc', b, 'rstrip')
939
940 # strip/lstrip/rstrip with None arg
941 self.checkequal('hello', ' hello ', 'strip', None)
942 self.checkequal('hello ', ' hello ', 'lstrip', None)
943 self.checkequal(' hello', ' hello ', 'rstrip', None)
944 self.checkequal('hello', 'hello', 'strip', None)
945
946 def test_strip(self):
947 # strip/lstrip/rstrip with str arg
948 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
949 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
950 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
951 self.checkequal('hello', 'hello', 'strip', 'xyz')
952 self.checkequal('', 'mississippi', 'strip', 'mississippi')
953
954 # only trim the start and end; does not strip internal characters
955 self.checkequal('mississipp', 'mississippi', 'strip', 'i')
956
957 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
958 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
959 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
960
961 def test_ljust(self):
962 self.checkequal('abc ', 'abc', 'ljust', 10)
963 self.checkequal('abc ', 'abc', 'ljust', 6)
964 self.checkequal('abc', 'abc', 'ljust', 3)
965 self.checkequal('abc', 'abc', 'ljust', 2)
966 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
967 self.checkraises(TypeError, 'abc', 'ljust')
968
969 def test_rjust(self):
970 self.checkequal(' abc', 'abc', 'rjust', 10)
971 self.checkequal(' abc', 'abc', 'rjust', 6)
972 self.checkequal('abc', 'abc', 'rjust', 3)
973 self.checkequal('abc', 'abc', 'rjust', 2)
974 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
975 self.checkraises(TypeError, 'abc', 'rjust')
976
977 def test_center(self):
978 self.checkequal(' abc ', 'abc', 'center', 10)
979 self.checkequal(' abc ', 'abc', 'center', 6)
980 self.checkequal('abc', 'abc', 'center', 3)
981 self.checkequal('abc', 'abc', 'center', 2)
982 self.checkequal('***abc****', 'abc', 'center', 10, '*')
983 self.checkraises(TypeError, 'abc', 'center')
984
985 def test_swapcase(self):
986 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
987
988 self.checkraises(TypeError, 'hello', 'swapcase', 42)
989
990 def test_zfill(self):
991 self.checkequal('123', '123', 'zfill', 2)
992 self.checkequal('123', '123', 'zfill', 3)
993 self.checkequal('0123', '123', 'zfill', 4)
994 self.checkequal('+123', '+123', 'zfill', 3)
995 self.checkequal('+123', '+123', 'zfill', 4)
996 self.checkequal('+0123', '+123', 'zfill', 5)
997 self.checkequal('-123', '-123', 'zfill', 3)
998 self.checkequal('-123', '-123', 'zfill', 4)
999 self.checkequal('-0123', '-123', 'zfill', 5)
1000 self.checkequal('000', '', 'zfill', 3)
1001 self.checkequal('34', '34', 'zfill', 1)
1002 self.checkequal('0034', '34', 'zfill', 4)
1003
1004 self.checkraises(TypeError, '123', 'zfill')
1005
1006 def test_islower(self):
1007 self.checkequal(False, '', 'islower')
1008 self.checkequal(True, 'a', 'islower')
1009 self.checkequal(False, 'A', 'islower')
1010 self.checkequal(False, '\n', 'islower')
1011 self.checkequal(True, 'abc', 'islower')
1012 self.checkequal(False, 'aBc', 'islower')
1013 self.checkequal(True, 'abc\n', 'islower')
1014 self.checkraises(TypeError, 'abc', 'islower', 42)
1015
1016 def test_isupper(self):
1017 self.checkequal(False, '', 'isupper')
1018 self.checkequal(False, 'a', 'isupper')
1019 self.checkequal(True, 'A', 'isupper')
1020 self.checkequal(False, '\n', 'isupper')
1021 self.checkequal(True, 'ABC', 'isupper')
1022 self.checkequal(False, 'AbC', 'isupper')
1023 self.checkequal(True, 'ABC\n', 'isupper')
1024 self.checkraises(TypeError, 'abc', 'isupper', 42)
1025
1026 def test_istitle(self):
1027 self.checkequal(False, '', 'istitle')
1028 self.checkequal(False, 'a', 'istitle')
1029 self.checkequal(True, 'A', 'istitle')
1030 self.checkequal(False, '\n', 'istitle')
1031 self.checkequal(True, 'A Titlecased Line', 'istitle')
1032 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
1033 self.checkequal(True, 'A Titlecased, Line', 'istitle')
1034 self.checkequal(False, 'Not a capitalized String', 'istitle')
1035 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
1036 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
1037 self.checkequal(False, 'NOT', 'istitle')
1038 self.checkraises(TypeError, 'abc', 'istitle', 42)
1039
1040 def test_isspace(self):
1041 self.checkequal(False, '', 'isspace')
1042 self.checkequal(False, 'a', 'isspace')
1043 self.checkequal(True, ' ', 'isspace')
1044 self.checkequal(True, '\t', 'isspace')
1045 self.checkequal(True, '\r', 'isspace')
1046 self.checkequal(True, '\n', 'isspace')
1047 self.checkequal(True, ' \t\r\n', 'isspace')
1048 self.checkequal(False, ' \t\r\na', 'isspace')
1049 self.checkraises(TypeError, 'abc', 'isspace', 42)
1050
1051 def test_isalpha(self):
1052 self.checkequal(False, '', 'isalpha')
1053 self.checkequal(True, 'a', 'isalpha')
1054 self.checkequal(True, 'A', 'isalpha')
1055 self.checkequal(False, '\n', 'isalpha')
1056 self.checkequal(True, 'abc', 'isalpha')
1057 self.checkequal(False, 'aBc123', 'isalpha')
1058 self.checkequal(False, 'abc\n', 'isalpha')
1059 self.checkraises(TypeError, 'abc', 'isalpha', 42)
1060
1061 def test_isalnum(self):
1062 self.checkequal(False, '', 'isalnum')
1063 self.checkequal(True, 'a', 'isalnum')
1064 self.checkequal(True, 'A', 'isalnum')
1065 self.checkequal(False, '\n', 'isalnum')
1066 self.checkequal(True, '123abc456', 'isalnum')
1067 self.checkequal(True, 'a1b3c', 'isalnum')
1068 self.checkequal(False, 'aBc000 ', 'isalnum')
1069 self.checkequal(False, 'abc\n', 'isalnum')
1070 self.checkraises(TypeError, 'abc', 'isalnum', 42)
1071
1072 def test_isascii(self):
1073 self.checkequal(True, '', 'isascii')
1074 self.checkequal(True, '\x00', 'isascii')
1075 self.checkequal(True, '\x7f', 'isascii')
1076 self.checkequal(True, '\x00\x7f', 'isascii')
1077 self.checkequal(False, '\x80', 'isascii')
1078 self.checkequal(False, '\xe9', 'isascii')
1079 # bytes.isascii() and bytearray.isascii() has optimization which
1080 # check 4 or 8 bytes at once. So check some alignments.
1081 for p in range(8):
1082 self.checkequal(True, ' '*p + '\x7f', 'isascii')
1083 self.checkequal(False, ' '*p + '\x80', 'isascii')
1084 self.checkequal(True, ' '*p + '\x7f' + ' '*8, 'isascii')
1085 self.checkequal(False, ' '*p + '\x80' + ' '*8, 'isascii')
1086
1087 def test_isdigit(self):
1088 self.checkequal(False, '', 'isdigit')
1089 self.checkequal(False, 'a', 'isdigit')
1090 self.checkequal(True, '0', 'isdigit')
1091 self.checkequal(True, '0123456789', 'isdigit')
1092 self.checkequal(False, '0123456789a', 'isdigit')
1093
1094 self.checkraises(TypeError, 'abc', 'isdigit', 42)
1095
1096 def test_title(self):
1097 self.checkequal(' Hello ', ' hello ', 'title')
1098 self.checkequal('Hello ', 'hello ', 'title')
1099 self.checkequal('Hello ', 'Hello ', 'title')
1100 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
1101 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
1102 self.checkequal('Getint', "getInt", 'title')
1103 self.checkraises(TypeError, 'hello', 'title', 42)
1104
1105 def test_splitlines(self):
1106 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
1107 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
1108 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
1109 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
1110 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
1111 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
1112 self.checkequal(['', 'abc', 'def', 'ghi', ''],
1113 "\nabc\ndef\r\nghi\n\r", 'splitlines', False)
1114 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
1115 "\nabc\ndef\r\nghi\n\r", 'splitlines', True)
1116 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r",
1117 'splitlines', keepends=False)
1118 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
1119 "\nabc\ndef\r\nghi\n\r", 'splitlines', keepends=True)
1120
1121 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
1122
1123
1124 class StringLikeTest(BaseTest):
1125 # This testcase contains tests that can be used in all
1126 # stringlike classes. Currently this is str and UserString.
1127
1128 def test_hash(self):
1129 # SF bug 1054139: += optimization was not invalidating cached hash value
1130 a = self.type2test('DNSSEC')
1131 b = self.type2test('')
1132 for c in a:
1133 b += c
1134 hash(b)
1135 self.assertEqual(hash(a), hash(b))
1136
1137 def test_capitalize_nonascii(self):
1138 # check that titlecased chars are lowered correctly
1139 # \u1ffc is the titlecased char
1140 self.checkequal('\u1ffc\u1ff3\u1ff3\u1ff3',
1141 '\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize')
1142 # check with cased non-letter chars
1143 self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
1144 '\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize')
1145 self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
1146 '\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize')
1147 self.checkequal('\u2160\u2171\u2172',
1148 '\u2160\u2161\u2162', 'capitalize')
1149 self.checkequal('\u2160\u2171\u2172',
1150 '\u2170\u2171\u2172', 'capitalize')
1151 # check with Ll chars with no upper - nothing changes here
1152 self.checkequal('\u019b\u1d00\u1d86\u0221\u1fb7',
1153 '\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize')
1154
1155 def test_startswith(self):
1156 self.checkequal(True, 'hello', 'startswith', 'he')
1157 self.checkequal(True, 'hello', 'startswith', 'hello')
1158 self.checkequal(False, 'hello', 'startswith', 'hello world')
1159 self.checkequal(True, 'hello', 'startswith', '')
1160 self.checkequal(False, 'hello', 'startswith', 'ello')
1161 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
1162 self.checkequal(True, 'hello', 'startswith', 'o', 4)
1163 self.checkequal(False, 'hello', 'startswith', 'o', 5)
1164 self.checkequal(True, 'hello', 'startswith', '', 5)
1165 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
1166 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
1167 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
1168 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
1169 self.checkequal(True, '', 'startswith', '', 0, 1)
1170 self.checkequal(True, '', 'startswith', '', 0, 0)
1171 self.checkequal(False, '', 'startswith', '', 1, 0)
1172
1173 # test negative indices
1174 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
1175 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
1176 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
1177 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
1178 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
1179 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
1180 self.checkequal(False, 'hello', 'startswith', 'o', -2)
1181 self.checkequal(True, 'hello', 'startswith', 'o', -1)
1182 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
1183 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
1184
1185 self.checkraises(TypeError, 'hello', 'startswith')
1186 self.checkraises(TypeError, 'hello', 'startswith', 42)
1187
1188 # test tuple arguments
1189 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
1190 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
1191 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
1192 self.checkequal(False, 'hello', 'startswith', ())
1193 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
1194 'rld', 'lowo'), 3)
1195 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
1196 'rld'), 3)
1197 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
1198 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
1199 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
1200
1201 self.checkraises(TypeError, 'hello', 'startswith', (42,))
1202
1203 def test_endswith(self):
1204 self.checkequal(True, 'hello', 'endswith', 'lo')
1205 self.checkequal(False, 'hello', 'endswith', 'he')
1206 self.checkequal(True, 'hello', 'endswith', '')
1207 self.checkequal(False, 'hello', 'endswith', 'hello world')
1208 self.checkequal(False, 'helloworld', 'endswith', 'worl')
1209 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
1210 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
1211 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
1212 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
1213 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
1214 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
1215 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
1216 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
1217 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
1218 self.checkequal(True, '', 'endswith', '', 0, 1)
1219 self.checkequal(True, '', 'endswith', '', 0, 0)
1220 self.checkequal(False, '', 'endswith', '', 1, 0)
1221
1222 # test negative indices
1223 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
1224 self.checkequal(False, 'hello', 'endswith', 'he', -2)
1225 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
1226 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
1227 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
1228 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
1229 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
1230 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
1231 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
1232 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
1233 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
1234 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
1235 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
1236
1237 self.checkraises(TypeError, 'hello', 'endswith')
1238 self.checkraises(TypeError, 'hello', 'endswith', 42)
1239
1240 # test tuple arguments
1241 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
1242 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
1243 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
1244 self.checkequal(False, 'hello', 'endswith', ())
1245 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
1246 'rld', 'lowo'), 3)
1247 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
1248 'rld'), 3, -1)
1249 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
1250 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
1251 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
1252
1253 self.checkraises(TypeError, 'hello', 'endswith', (42,))
1254
1255 def test___contains__(self):
1256 self.checkequal(True, '', '__contains__', '')
1257 self.checkequal(True, 'abc', '__contains__', '')
1258 self.checkequal(False, 'abc', '__contains__', '\0')
1259 self.checkequal(True, '\0abc', '__contains__', '\0')
1260 self.checkequal(True, 'abc\0', '__contains__', '\0')
1261 self.checkequal(True, '\0abc', '__contains__', 'a')
1262 self.checkequal(True, 'asdf', '__contains__', 'asdf')
1263 self.checkequal(False, 'asd', '__contains__', 'asdf')
1264 self.checkequal(False, '', '__contains__', 'asdf')
1265
1266 def test_subscript(self):
1267 self.checkequal('a', 'abc', '__getitem__', 0)
1268 self.checkequal('c', 'abc', '__getitem__', -1)
1269 self.checkequal('a', 'abc', '__getitem__', 0)
1270 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
1271 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
1272 self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
1273 self.checkequal('', 'abc', '__getitem__', slice(0, 0))
1274
1275 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
1276
1277 for idx_type in ('def', object()):
1278 expected_msg = "string indices must be integers, not '{}'".format(type(idx_type).__name__)
1279 self.checkraises(TypeError, 'abc', '__getitem__', idx_type, expected_msg=expected_msg)
1280
1281 def test_slice(self):
1282 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
1283 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
1284 self.checkequal('ab', 'abc', '__getitem__', slice(0, 2))
1285 self.checkequal('bc', 'abc', '__getitem__', slice(1, 3))
1286 self.checkequal('b', 'abc', '__getitem__', slice(1, 2))
1287 self.checkequal('', 'abc', '__getitem__', slice(2, 2))
1288 self.checkequal('', 'abc', '__getitem__', slice(1000, 1000))
1289 self.checkequal('', 'abc', '__getitem__', slice(2000, 1000))
1290 self.checkequal('', 'abc', '__getitem__', slice(2, 1))
1291
1292 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
1293
1294 def test_extended_getslice(self):
1295 # Test extended slicing by comparing with list slicing.
1296 s = string.ascii_letters + string.digits
1297 indices = (0, None, 1, 3, 41, sys.maxsize, -1, -2, -37)
1298 for start in indices:
1299 for stop in indices:
1300 # Skip step 0 (invalid)
1301 for step in indices[1:]:
1302 L = list(s)[start:stop:step]
1303 self.checkequal("".join(L), s, '__getitem__',
1304 slice(start, stop, step))
1305
1306 def test_mul(self):
1307 self.checkequal('', 'abc', '__mul__', -1)
1308 self.checkequal('', 'abc', '__mul__', 0)
1309 self.checkequal('abc', 'abc', '__mul__', 1)
1310 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
1311 self.checkraises(TypeError, 'abc', '__mul__')
1312 self.checkraises(TypeError, 'abc', '__mul__', '')
1313 # XXX: on a 64-bit system, this doesn't raise an overflow error,
1314 # but either raises a MemoryError, or succeeds (if you have 54TiB)
1315 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
1316
1317 def test_join(self):
1318 # join now works with any sequence type
1319 # moved here, because the argument order is
1320 # different in string.join
1321 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
1322 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
1323 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
1324 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
1325 self.checkequal('w x y z', ' ', 'join', Sequence())
1326 self.checkequal('abc', 'a', 'join', ('abc',))
1327 self.checkequal('z', 'a', 'join', UserList(['z']))
1328 self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c'])
1329 self.assertRaises(TypeError, '.'.join, ['a', 'b', 3])
1330 for i in [5, 25, 125]:
1331 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1332 ['a' * i] * i)
1333 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1334 ('a' * i,) * i)
1335
1336 class LiesAboutLengthSeq(Sequence):
1337 def __init__(self): self.seq = ['a', 'b', 'c']
1338 def __len__(self): return 8
1339
1340 self.checkequal('a b c', ' ', 'join', LiesAboutLengthSeq())
1341
1342 self.checkraises(TypeError, ' ', 'join')
1343 self.checkraises(TypeError, ' ', 'join', None)
1344 self.checkraises(TypeError, ' ', 'join', 7)
1345 self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()])
1346 try:
1347 def f():
1348 yield 4 + ""
1349 self.fixtype(' ').join(f())
1350 except TypeError as e:
1351 if '+' not in str(e):
1352 self.fail('join() ate exception message')
1353 else:
1354 self.fail('exception not raised')
1355
1356 def test_formatting(self):
1357 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1358 self.checkequal('+10+', '+%d+', '__mod__', 10)
1359 self.checkequal('a', "%c", '__mod__', "a")
1360 self.checkequal('a', "%c", '__mod__', "a")
1361 self.checkequal('"', "%c", '__mod__', 34)
1362 self.checkequal('$', "%c", '__mod__', 36)
1363 self.checkequal('10', "%d", '__mod__', 10)
1364 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
1365
1366 for ordinal in (-100, 0x200000):
1367 # unicode raises ValueError, str raises OverflowError
1368 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1369
1370 longvalue = sys.maxsize + 10
1371 slongvalue = str(longvalue)
1372 self.checkequal(' 42', '%3ld', '__mod__', 42)
1373 self.checkequal('42', '%d', '__mod__', 42.0)
1374 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1375 self.checkcall('%d', '__mod__', float(longvalue))
1376 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
1377 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
1378
1379 self.checkraises(TypeError, 'abc', '__mod__')
1380 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1381 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1382 self.checkraises(TypeError, '%c', '__mod__', (None,))
1383 self.checkraises(ValueError, '%(foo', '__mod__', {})
1384 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
1385 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
1386 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int conversion provided
1387
1388 # argument names with properly nested brackets are supported
1389 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1390
1391 # 100 is a magic number in PyUnicode_Format, this forces a resize
1392 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1393
1394 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1395 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1396 self.checkraises(ValueError, '%10', '__mod__', (42,))
1397
1398 # Outrageously large width or precision should raise ValueError.
1399 self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2))
1400 self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2))
1401 self.checkraises(OverflowError, '%*s', '__mod__',
1402 (sys.maxsize + 1, ''))
1403 self.checkraises(OverflowError, '%.*f', '__mod__',
1404 (sys.maxsize + 1, 1. / 7))
1405
1406 class X(object): pass
1407 self.checkraises(TypeError, 'abc', '__mod__', X())
1408
1409 @support.cpython_only
1410 def test_formatting_c_limits(self):
1411 _testcapi = import_helper.import_module('_testcapi')
1412 SIZE_MAX = (1 << (_testcapi.PY_SSIZE_T_MAX.bit_length() + 1)) - 1
1413 self.checkraises(OverflowError, '%*s', '__mod__',
1414 (_testcapi.PY_SSIZE_T_MAX + 1, ''))
1415 self.checkraises(OverflowError, '%.*f', '__mod__',
1416 (_testcapi.INT_MAX + 1, 1. / 7))
1417 # Issue 15989
1418 self.checkraises(OverflowError, '%*s', '__mod__',
1419 (SIZE_MAX + 1, ''))
1420 self.checkraises(OverflowError, '%.*f', '__mod__',
1421 (_testcapi.UINT_MAX + 1, 1. / 7))
1422
1423 def test_floatformatting(self):
1424 # float formatting
1425 for prec in range(100):
1426 format = '%%.%if' % prec
1427 value = 0.01
1428 for x in range(60):
1429 value = value * 3.14159265359 / 3.0 * 10.0
1430 self.checkcall(format, "__mod__", value)
1431
1432 def test_inplace_rewrites(self):
1433 # Check that strings don't copy and modify cached single-character strings
1434 self.checkequal('a', 'A', 'lower')
1435 self.checkequal(True, 'A', 'isupper')
1436 self.checkequal('A', 'a', 'upper')
1437 self.checkequal(True, 'a', 'islower')
1438
1439 self.checkequal('a', 'A', 'replace', 'A', 'a')
1440 self.checkequal(True, 'A', 'isupper')
1441
1442 self.checkequal('A', 'a', 'capitalize')
1443 self.checkequal(True, 'a', 'islower')
1444
1445 self.checkequal('A', 'a', 'swapcase')
1446 self.checkequal(True, 'a', 'islower')
1447
1448 self.checkequal('A', 'a', 'title')
1449 self.checkequal(True, 'a', 'islower')
1450
1451 def test_partition(self):
1452
1453 self.checkequal(('this is the par', 'ti', 'tion method'),
1454 'this is the partition method', 'partition', 'ti')
1455
1456 # from raymond's original specification
1457 S = 'http://www.python.org'
1458 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1459 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1460 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1461 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1462
1463 self.checkraises(ValueError, S, 'partition', '')
1464 self.checkraises(TypeError, S, 'partition', None)
1465
1466 def test_rpartition(self):
1467
1468 self.checkequal(('this is the rparti', 'ti', 'on method'),
1469 'this is the rpartition method', 'rpartition', 'ti')
1470
1471 # from raymond's original specification
1472 S = 'http://www.python.org'
1473 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
1474 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
1475 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1476 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1477
1478 self.checkraises(ValueError, S, 'rpartition', '')
1479 self.checkraises(TypeError, S, 'rpartition', None)
1480
1481 def test_none_arguments(self):
1482 # issue 11828
1483 s = 'hello'
1484 self.checkequal(2, s, 'find', 'l', None)
1485 self.checkequal(3, s, 'find', 'l', -2, None)
1486 self.checkequal(2, s, 'find', 'l', None, -2)
1487 self.checkequal(0, s, 'find', 'h', None, None)
1488
1489 self.checkequal(3, s, 'rfind', 'l', None)
1490 self.checkequal(3, s, 'rfind', 'l', -2, None)
1491 self.checkequal(2, s, 'rfind', 'l', None, -2)
1492 self.checkequal(0, s, 'rfind', 'h', None, None)
1493
1494 self.checkequal(2, s, 'index', 'l', None)
1495 self.checkequal(3, s, 'index', 'l', -2, None)
1496 self.checkequal(2, s, 'index', 'l', None, -2)
1497 self.checkequal(0, s, 'index', 'h', None, None)
1498
1499 self.checkequal(3, s, 'rindex', 'l', None)
1500 self.checkequal(3, s, 'rindex', 'l', -2, None)
1501 self.checkequal(2, s, 'rindex', 'l', None, -2)
1502 self.checkequal(0, s, 'rindex', 'h', None, None)
1503
1504 self.checkequal(2, s, 'count', 'l', None)
1505 self.checkequal(1, s, 'count', 'l', -2, None)
1506 self.checkequal(1, s, 'count', 'l', None, -2)
1507 self.checkequal(0, s, 'count', 'x', None, None)
1508
1509 self.checkequal(True, s, 'endswith', 'o', None)
1510 self.checkequal(True, s, 'endswith', 'lo', -2, None)
1511 self.checkequal(True, s, 'endswith', 'l', None, -2)
1512 self.checkequal(False, s, 'endswith', 'x', None, None)
1513
1514 self.checkequal(True, s, 'startswith', 'h', None)
1515 self.checkequal(True, s, 'startswith', 'l', -2, None)
1516 self.checkequal(True, s, 'startswith', 'h', None, -2)
1517 self.checkequal(False, s, 'startswith', 'x', None, None)
1518
1519 def test_find_etc_raise_correct_error_messages(self):
1520 # issue 11828
1521 s = 'hello'
1522 x = 'x'
1523 self.assertRaisesRegex(TypeError, r'^find\b', s.find,
1524 x, None, None, None)
1525 self.assertRaisesRegex(TypeError, r'^rfind\b', s.rfind,
1526 x, None, None, None)
1527 self.assertRaisesRegex(TypeError, r'^index\b', s.index,
1528 x, None, None, None)
1529 self.assertRaisesRegex(TypeError, r'^rindex\b', s.rindex,
1530 x, None, None, None)
1531 self.assertRaisesRegex(TypeError, r'^count\b', s.count,
1532 x, None, None, None)
1533 self.assertRaisesRegex(TypeError, r'^startswith\b', s.startswith,
1534 x, None, None, None)
1535 self.assertRaisesRegex(TypeError, r'^endswith\b', s.endswith,
1536 x, None, None, None)
1537
1538 # issue #15534
1539 self.checkequal(10, "...\u043c......<", "find", "<")
1540
1541
1542 class MixinStrUnicodeTest:
1543 # Additional tests that only work with str.
1544
1545 def test_bug1001011(self):
1546 # Make sure join returns a NEW object for single item sequences
1547 # involving a subclass.
1548 # Make sure that it is of the appropriate type.
1549 # Check the optimisation still occurs for standard objects.
1550 t = self.type2test
1551 class subclass(t):
1552 pass
1553 s1 = subclass("abcd")
1554 s2 = t().join([s1])
1555 self.assertIsNot(s1, s2)
1556 self.assertIs(type(s2), t)
1557
1558 s1 = t("abcd")
1559 s2 = t().join([s1])
1560 self.assertIs(s1, s2)