blob: da79ffa419276874837e0783a5e2184ceb1517af [file] [log] [blame]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001"""
Martin Panter275bd962016-02-02 10:37:15 +00002Common tests shared by test_unicode, test_userstring and test_bytes.
Walter Dörwald0fd583c2003-02-21 12:53:50 +00003"""
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00004
Guido van Rossum360e4b82007-05-14 22:51:27 +00005import unittest, string, sys, struct
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Raymond Hettinger53dbe392008-02-12 20:03:09 +00007from collections import UserList
Jeremy Hylton20f41b62000-07-11 03:31:55 +00008
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00009class Sequence:
Walter Dörwald0fd583c2003-02-21 12:53:50 +000010 def __init__(self, seq='wxyz'): self.seq = seq
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000011 def __len__(self): return len(self.seq)
12 def __getitem__(self, i): return self.seq[i]
13
14class BadSeq1(Sequence):
Guido van Rossume2a383d2007-01-15 16:59:06 +000015 def __init__(self): self.seq = [7, 'hello', 123]
Guido van Rossumf1044292007-09-27 18:01:22 +000016 def __str__(self): return '{0} {1} {2}'.format(*self.seq)
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000017
18class BadSeq2(Sequence):
19 def __init__(self): self.seq = ['a', 'b', 'c']
20 def __len__(self): return 8
21
Ezio Melotti0dceb562013-01-10 07:43:26 +020022class BaseTest:
Georg Brandlc7885542007-03-06 19:16:20 +000023 # These tests are for buffers of values (bytes) and not
24 # specific to character interpretation, used for bytes objects
25 # and various string implementations
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000026
Walter Dörwald0fd583c2003-02-21 12:53:50 +000027 # The type to be tested
28 # Change in subclasses to change the behaviour of fixtesttype()
29 type2test = None
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000030
Antoine Pitrouac65d962011-10-20 23:54:17 +020031 # Whether the "contained items" of the container are integers in
32 # range(0, 256) (i.e. bytes, bytearray) or strings of length 1
33 # (str)
34 contains_bytes = False
35
Walter Dörwald0fd583c2003-02-21 12:53:50 +000036 # All tests pass their arguments to the testing methods
37 # as str objects. fixtesttype() can be used to propagate
38 # these arguments to the appropriate type
39 def fixtype(self, obj):
40 if isinstance(obj, str):
41 return self.__class__.type2test(obj)
42 elif isinstance(obj, list):
43 return [self.fixtype(x) for x in obj]
44 elif isinstance(obj, tuple):
45 return tuple([self.fixtype(x) for x in obj])
46 elif isinstance(obj, dict):
47 return dict([
48 (self.fixtype(key), self.fixtype(value))
Guido van Rossumcc2b0162007-02-11 06:12:03 +000049 for (key, value) in obj.items()
Walter Dörwald0fd583c2003-02-21 12:53:50 +000050 ])
51 else:
52 return obj
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000053
Guido van Rossum09549f42007-08-27 20:40:10 +000054 # check that obj.method(*args) returns result
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010055 def checkequal(self, result, obj, methodname, *args, **kwargs):
Walter Dörwald0fd583c2003-02-21 12:53:50 +000056 result = self.fixtype(result)
Guido van Rossum09549f42007-08-27 20:40:10 +000057 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000058 args = self.fixtype(args)
Ezio Melotticda6b6d2012-02-26 09:39:55 +020059 kwargs = {k: self.fixtype(v) for k,v in kwargs.items()}
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010060 realresult = getattr(obj, methodname)(*args, **kwargs)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000061 self.assertEqual(
62 result,
63 realresult
64 )
65 # if the original is returned make sure that
66 # this doesn't happen with subclasses
Guido van Rossum09549f42007-08-27 20:40:10 +000067 if obj is realresult:
68 try:
69 class subtype(self.__class__.type2test):
70 pass
71 except TypeError:
72 pass # Skip this if we can't subclass
73 else:
74 obj = subtype(obj)
75 realresult = getattr(obj, methodname)(*args)
Ezio Melottib3aedd42010-11-20 19:04:17 +000076 self.assertIsNot(obj, realresult)
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000077
Guido van Rossum09549f42007-08-27 20:40:10 +000078 # check that obj.method(*args) raises exc
79 def checkraises(self, exc, obj, methodname, *args):
80 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000081 args = self.fixtype(args)
Benjamin Petersonc31f12d2014-09-28 12:56:42 -040082 with self.assertRaises(exc) as cm:
83 getattr(obj, methodname)(*args)
84 self.assertNotEqual(str(cm.exception), '')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000085
Guido van Rossum09549f42007-08-27 20:40:10 +000086 # call obj.method(*args) without any checks
87 def checkcall(self, obj, methodname, *args):
88 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000089 args = self.fixtype(args)
Guido van Rossum09549f42007-08-27 20:40:10 +000090 getattr(obj, methodname)(*args)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000091
Walter Dörwald0fd583c2003-02-21 12:53:50 +000092 def test_count(self):
93 self.checkequal(3, 'aaa', 'count', 'a')
94 self.checkequal(0, 'aaa', 'count', 'b')
95 self.checkequal(3, 'aaa', 'count', 'a')
96 self.checkequal(0, 'aaa', 'count', 'b')
97 self.checkequal(3, 'aaa', 'count', 'a')
98 self.checkequal(0, 'aaa', 'count', 'b')
99 self.checkequal(0, 'aaa', 'count', 'b')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.checkequal(2, 'aaa', 'count', 'a', 1)
101 self.checkequal(0, 'aaa', 'count', 'a', 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000102 self.checkequal(1, 'aaa', 'count', 'a', -1)
103 self.checkequal(3, 'aaa', 'count', 'a', -10)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000104 self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
105 self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000106 self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
107 self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000108 self.checkequal(3, 'aaa', 'count', '', 1)
109 self.checkequal(1, 'aaa', 'count', '', 3)
110 self.checkequal(0, 'aaa', 'count', '', 10)
111 self.checkequal(2, 'aaa', 'count', '', -1)
112 self.checkequal(4, 'aaa', 'count', '', -10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000113
Amaury Forgeot d'Arcf2e93682008-09-26 22:48:41 +0000114 self.checkequal(1, '', 'count', '')
115 self.checkequal(0, '', 'count', '', 1, 1)
116 self.checkequal(0, '', 'count', '', sys.maxsize, 0)
117
118 self.checkequal(0, '', 'count', 'xx')
119 self.checkequal(0, '', 'count', 'xx', 1, 1)
120 self.checkequal(0, '', 'count', 'xx', sys.maxsize, 0)
121
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000122 self.checkraises(TypeError, 'hello', 'count')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200123
124 if self.contains_bytes:
125 self.checkequal(0, 'hello', 'count', 42)
126 else:
127 self.checkraises(TypeError, 'hello', 'count', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000128
Raymond Hettinger57e74472005-02-20 09:54:53 +0000129 # For a variety of combinations,
130 # verify that str.count() matches an equivalent function
131 # replacing all occurrences and then differencing the string lengths
132 charset = ['', 'a', 'b']
133 digits = 7
134 base = len(charset)
135 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000136 for i in range(base ** digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000137 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000138 for j in range(digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000139 i, m = divmod(i, base)
140 entry.append(charset[m])
141 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000142 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger57e74472005-02-20 09:54:53 +0000143 for i in teststrings:
Raymond Hettinger57e74472005-02-20 09:54:53 +0000144 n = len(i)
145 for j in teststrings:
146 r1 = i.count(j)
147 if j:
Guido van Rossum09549f42007-08-27 20:40:10 +0000148 r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))),
149 len(j))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000150 else:
151 r2, rem = len(i)+1, 0
152 if rem or r1 != r2:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
154 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000155
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000156 def test_find(self):
157 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
158 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
159 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
160
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000161 self.checkequal(0, 'abc', 'find', '', 0)
162 self.checkequal(3, 'abc', 'find', '', 3)
163 self.checkequal(-1, 'abc', 'find', '', 4)
164
Christian Heimes9cd17752007-11-18 19:35:23 +0000165 # to check the ability to pass None as defaults
166 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
167 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
168 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
169 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
170 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
171
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000172 self.checkraises(TypeError, 'hello', 'find')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200173
174 if self.contains_bytes:
175 self.checkequal(-1, 'hello', 'find', 42)
176 else:
177 self.checkraises(TypeError, 'hello', 'find', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000178
Amaury Forgeot d'Arcf2e93682008-09-26 22:48:41 +0000179 self.checkequal(0, '', 'find', '')
180 self.checkequal(-1, '', 'find', '', 1, 1)
181 self.checkequal(-1, '', 'find', '', sys.maxsize, 0)
182
183 self.checkequal(-1, '', 'find', 'xx')
184 self.checkequal(-1, '', 'find', 'xx', 1, 1)
185 self.checkequal(-1, '', 'find', 'xx', sys.maxsize, 0)
186
Antoine Pitrou74edda02010-01-02 21:51:33 +0000187 # issue 7458
188 self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0)
189
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000190 # For a variety of combinations,
191 # verify that str.find() matches __contains__
192 # and that the found substring is really at that location
193 charset = ['', 'a', 'b', 'c']
194 digits = 5
195 base = len(charset)
196 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000197 for i in range(base ** digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000198 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000199 for j in range(digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000200 i, m = divmod(i, base)
201 entry.append(charset[m])
202 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000203 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000204 for i in teststrings:
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000205 for j in teststrings:
206 loc = i.find(j)
207 r1 = (loc != -1)
208 r2 = j in i
Antoine Pitrou2e544fb2010-01-02 21:55:17 +0000209 self.assertEqual(r1, r2)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000210 if loc != -1:
211 self.assertEqual(i[loc:loc+len(j)], j)
212
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000213 def test_rfind(self):
214 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
215 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
216 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
217 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
218
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000219 self.checkequal(3, 'abc', 'rfind', '', 0)
220 self.checkequal(3, 'abc', 'rfind', '', 3)
221 self.checkequal(-1, 'abc', 'rfind', '', 4)
222
Christian Heimes9cd17752007-11-18 19:35:23 +0000223 # to check the ability to pass None as defaults
224 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
225 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
226 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
227 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
228 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
229
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000230 self.checkraises(TypeError, 'hello', 'rfind')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200231
232 if self.contains_bytes:
233 self.checkequal(-1, 'hello', 'rfind', 42)
234 else:
235 self.checkraises(TypeError, 'hello', 'rfind', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000236
Antoine Pitrouda2ecaf2010-01-02 21:40:36 +0000237 # For a variety of combinations,
238 # verify that str.rfind() matches __contains__
239 # and that the found substring is really at that location
240 charset = ['', 'a', 'b', 'c']
241 digits = 5
242 base = len(charset)
243 teststrings = set()
244 for i in range(base ** digits):
245 entry = []
246 for j in range(digits):
247 i, m = divmod(i, base)
248 entry.append(charset[m])
249 teststrings.add(''.join(entry))
250 teststrings = [self.fixtype(ts) for ts in teststrings]
251 for i in teststrings:
252 for j in teststrings:
253 loc = i.rfind(j)
254 r1 = (loc != -1)
255 r2 = j in i
Antoine Pitrou2e544fb2010-01-02 21:55:17 +0000256 self.assertEqual(r1, r2)
Antoine Pitrouda2ecaf2010-01-02 21:40:36 +0000257 if loc != -1:
258 self.assertEqual(i[loc:loc+len(j)], j)
259
Antoine Pitrou74edda02010-01-02 21:51:33 +0000260 # issue 7458
261 self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0)
262
Victor Stinnerb3f55012012-08-02 23:05:01 +0200263 # issue #15534
264 self.checkequal(0, '<......\u043c...', "rfind", "<")
265
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000266 def test_index(self):
267 self.checkequal(0, 'abcdefghiabc', 'index', '')
268 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
269 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
270 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
271
272 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
273 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
274 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
275 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
276
Christian Heimes9cd17752007-11-18 19:35:23 +0000277 # to check the ability to pass None as defaults
278 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
279 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
280 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
281 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
282 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
283
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000284 self.checkraises(TypeError, 'hello', 'index')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200285
286 if self.contains_bytes:
287 self.checkraises(ValueError, 'hello', 'index', 42)
288 else:
289 self.checkraises(TypeError, 'hello', 'index', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000290
291 def test_rindex(self):
292 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
293 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
294 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
295 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
296
297 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
298 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
299 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
300 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
301 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
302
Christian Heimes9cd17752007-11-18 19:35:23 +0000303 # to check the ability to pass None as defaults
304 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
305 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
306 self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
307 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
308 self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
309
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000310 self.checkraises(TypeError, 'hello', 'rindex')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200311
312 if self.contains_bytes:
313 self.checkraises(ValueError, 'hello', 'rindex', 42)
314 else:
315 self.checkraises(TypeError, 'hello', 'rindex', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000316
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000317 def test_lower(self):
318 self.checkequal('hello', 'HeLLo', 'lower')
319 self.checkequal('hello', 'hello', 'lower')
320 self.checkraises(TypeError, 'hello', 'lower', 42)
321
322 def test_upper(self):
323 self.checkequal('HELLO', 'HeLLo', 'upper')
324 self.checkequal('HELLO', 'HELLO', 'upper')
325 self.checkraises(TypeError, 'hello', 'upper', 42)
326
327 def test_expandtabs(self):
Ezio Melotti745d54d2013-11-16 19:10:57 +0200328 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
329 'expandtabs')
330 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
331 'expandtabs', 8)
332 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
333 'expandtabs', 4)
334 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
335 'expandtabs')
336 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
337 'expandtabs', 8)
338 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi',
339 'expandtabs', 4)
340 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi',
341 'expandtabs', 4)
342 # check keyword args
343 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
344 'expandtabs', tabsize=8)
345 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi',
346 'expandtabs', tabsize=4)
347
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000348 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
349
350 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
351 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000352 if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000353 self.checkraises(OverflowError,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000354 '\ta\n\tb', 'expandtabs', sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000355
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000356 def test_split(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000357 # by a char
358 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000359 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000360 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
361 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
362 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
363 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000364 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000365 sys.maxsize-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000366 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
367 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
368 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000369 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
370 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000371 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
372
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
374 self.checkequal(['a']*15 +['a|a|a|a|a'],
375 ('a|'*20)[:-1], 'split', '|', 15)
376
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000377 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000378 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000379 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
380 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
381 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
382 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000384 sys.maxsize-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000385 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
386 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000387 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000388 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
389 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
390 'split', 'test')
391 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
392 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
393 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
394 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
395 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
396 self.checkequal([''], '', 'split', 'aaa')
397 self.checkequal(['aa'], 'aa', 'split', 'aaa')
398 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
399 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
400
401 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
402 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
403 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
404 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000405
Ezio Melotticda6b6d2012-02-26 09:39:55 +0200406 # with keyword args
407 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', sep='|')
408 self.checkequal(['a', 'b|c|d'],
409 'a|b|c|d', 'split', '|', maxsplit=1)
410 self.checkequal(['a', 'b|c|d'],
411 'a|b|c|d', 'split', sep='|', maxsplit=1)
412 self.checkequal(['a', 'b|c|d'],
413 'a|b|c|d', 'split', maxsplit=1, sep='|')
414 self.checkequal(['a', 'b c d'],
415 'a b c d', 'split', maxsplit=1)
416
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000417 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000418 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
419
Thomas Wouters477c8d52006-05-27 19:21:47 +0000420 # null case
421 self.checkraises(ValueError, 'hello', 'split', '')
422 self.checkraises(ValueError, 'hello', 'split', '', 0)
423
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000424 def test_rsplit(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000425 # by a char
426 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
427 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
428 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
429 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
430 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000432 sys.maxsize-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000433 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
434 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
435 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
437 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
438
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000439 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
440
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
442 self.checkequal(['a|a|a|a|a']+['a']*15,
443 ('a|'*20)[:-1], 'rsplit', '|', 15)
444
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000445 # by string
446 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
447 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
448 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
449 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
450 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000452 sys.maxsize-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000453 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
454 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
455 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000456 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
457 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
458 'rsplit', 'test')
459 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
460 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
461 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
462 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
463 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
464 self.checkequal([''], '', 'rsplit', 'aaa')
465 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
466 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
467 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
468
469 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
470 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
471 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
472 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000473
Ezio Melotticda6b6d2012-02-26 09:39:55 +0200474 # with keyword args
475 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', sep='|')
476 self.checkequal(['a|b|c', 'd'],
477 'a|b|c|d', 'rsplit', '|', maxsplit=1)
478 self.checkequal(['a|b|c', 'd'],
479 'a|b|c|d', 'rsplit', sep='|', maxsplit=1)
480 self.checkequal(['a|b|c', 'd'],
481 'a|b|c|d', 'rsplit', maxsplit=1, sep='|')
482 self.checkequal(['a b c', 'd'],
483 'a b c d', 'rsplit', maxsplit=1)
484
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000485 # argument type
486 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000487
Thomas Wouters477c8d52006-05-27 19:21:47 +0000488 # null case
489 self.checkraises(ValueError, 'hello', 'rsplit', '')
490 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
491
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000492 def test_replace(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000493 EQ = self.checkequal
494
495 # Operations on the empty string
496 EQ("", "", "replace", "", "")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000497 EQ("A", "", "replace", "", "A")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000498 EQ("", "", "replace", "A", "")
499 EQ("", "", "replace", "A", "A")
500 EQ("", "", "replace", "", "", 100)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000501 EQ("", "", "replace", "", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000502
503 # interleave (from=="", 'to' gets inserted everywhere)
504 EQ("A", "A", "replace", "", "")
505 EQ("*A*", "A", "replace", "", "*")
506 EQ("*1A*1", "A", "replace", "", "*1")
507 EQ("*-#A*-#", "A", "replace", "", "*-#")
508 EQ("*-A*-A*-", "AA", "replace", "", "*-")
509 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000510 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
512 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
513 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
514 EQ("*-AA", "AA", "replace", "", "*-", 1)
515 EQ("AA", "AA", "replace", "", "*-", 0)
516
517 # single character deletion (from=="A", to=="")
518 EQ("", "A", "replace", "A", "")
519 EQ("", "AAA", "replace", "A", "")
520 EQ("", "AAA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000521 EQ("", "AAA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522 EQ("", "AAA", "replace", "A", "", 4)
523 EQ("", "AAA", "replace", "A", "", 3)
524 EQ("A", "AAA", "replace", "A", "", 2)
525 EQ("AA", "AAA", "replace", "A", "", 1)
526 EQ("AAA", "AAA", "replace", "A", "", 0)
527 EQ("", "AAAAAAAAAA", "replace", "A", "")
528 EQ("BCD", "ABACADA", "replace", "A", "")
529 EQ("BCD", "ABACADA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000530 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000531 EQ("BCD", "ABACADA", "replace", "A", "", 5)
532 EQ("BCD", "ABACADA", "replace", "A", "", 4)
533 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
534 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
535 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
536 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
537 EQ("BCD", "ABCAD", "replace", "A", "")
538 EQ("BCD", "ABCADAA", "replace", "A", "")
539 EQ("BCD", "BCD", "replace", "A", "")
540 EQ("*************", "*************", "replace", "A", "")
541 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
542
543 # substring deletion (from=="the", to=="")
544 EQ("", "the", "replace", "the", "")
545 EQ("ater", "theater", "replace", "the", "")
546 EQ("", "thethe", "replace", "the", "")
547 EQ("", "thethethethe", "replace", "the", "")
548 EQ("aaaa", "theatheatheathea", "replace", "the", "")
549 EQ("that", "that", "replace", "the", "")
550 EQ("thaet", "thaet", "replace", "the", "")
551 EQ("here and re", "here and there", "replace", "the", "")
552 EQ("here and re and re", "here and there and there",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000553 "replace", "the", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554 EQ("here and re and re", "here and there and there",
555 "replace", "the", "", -1)
556 EQ("here and re and re", "here and there and there",
557 "replace", "the", "", 3)
558 EQ("here and re and re", "here and there and there",
559 "replace", "the", "", 2)
560 EQ("here and re and there", "here and there and there",
561 "replace", "the", "", 1)
562 EQ("here and there and there", "here and there and there",
563 "replace", "the", "", 0)
564 EQ("here and re and re", "here and there and there", "replace", "the", "")
565
566 EQ("abc", "abc", "replace", "the", "")
567 EQ("abcdefg", "abcdefg", "replace", "the", "")
568
569 # substring deletion (from=="bob", to=="")
570 EQ("bob", "bbobob", "replace", "bob", "")
571 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
572 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
573 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
574
575 # single character replace in place (len(from)==len(to)==1)
576 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
577 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000578 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
580 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
581 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
582 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
583 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
584
585 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
586 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
587 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
588 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
589 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
590
591 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
592
593 # substring replace in place (len(from)==len(to) > 1)
594 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000595 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000596 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
597 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
598 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
599 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
600 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
601 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
602 EQ("cobob", "bobob", "replace", "bob", "cob")
603 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
604 EQ("bobob", "bobob", "replace", "bot", "bot")
605
606 # replace single character (len(from)==1, len(to)>1)
607 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
608 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000609 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
611 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
612 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
613 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
Victor Stinnerb3f55012012-08-02 23:05:01 +0200614 # issue #15534
615 EQ('...\u043c......&lt;', '...\u043c......<', "replace", "<", "&lt;")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616
617 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
618
619 # replace substring (len(from)>1, len(to)!=len(from))
620 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
621 "replace", "spam", "ham")
622 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000623 "replace", "spam", "ham", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
625 "replace", "spam", "ham", -1)
626 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
627 "replace", "spam", "ham", 4)
628 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
629 "replace", "spam", "ham", 3)
630 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
631 "replace", "spam", "ham", 2)
632 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
633 "replace", "spam", "ham", 1)
634 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
635 "replace", "spam", "ham", 0)
636
637 EQ("bobob", "bobobob", "replace", "bobob", "bob")
638 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
639 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
640
Guido van Rossum39478e82007-08-27 17:23:59 +0000641 # XXX Commented out. Is there any reason to support buffer objects
642 # as arguments for str.replace()? GvR
Guido van Rossum254348e2007-11-21 19:29:53 +0000643## ba = bytearray('a')
644## bb = bytearray('b')
Guido van Rossum39478e82007-08-27 17:23:59 +0000645## EQ("bbc", "abc", "replace", ba, bb)
646## EQ("aac", "abc", "replace", bb, ba)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000647
Thomas Wouters477c8d52006-05-27 19:21:47 +0000648 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000649 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
650 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
651 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
652 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
653 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
654 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
655 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
656 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
657 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
658 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
659 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
660 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
661 self.checkequal('', '', 'replace', '', '')
662 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
663 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
664 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
665 # MemoryError due to empty result (platform malloc issue when requesting
666 # 0 bytes).
667 self.checkequal('', '123', 'replace', '123', '')
668 self.checkequal('', '123123', 'replace', '123', '')
669 self.checkequal('x', '123x123', 'replace', '123', '')
670
671 self.checkraises(TypeError, 'hello', 'replace')
672 self.checkraises(TypeError, 'hello', 'replace', 42)
673 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
674 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
675
Zachary Ware9fe6d862013-12-08 00:20:35 -0600676 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
677 'only applies to 32-bit platforms')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000678 def test_replace_overflow(self):
679 # Check for overflow checking on 32 bit machines
Thomas Wouters477c8d52006-05-27 19:21:47 +0000680 A2_16 = "A" * (2**16)
681 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
682 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
683 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
684
Georg Brandlc7885542007-03-06 19:16:20 +0000685
686
687class CommonTest(BaseTest):
Martin Panter6f9b0102015-12-17 10:18:28 +0000688 # This testcase contains tests that can be used in all
Martin Panter275bd962016-02-02 10:37:15 +0000689 # stringlike classes. Currently this is str and UserString.
Georg Brandlc7885542007-03-06 19:16:20 +0000690
691 def test_hash(self):
692 # SF bug 1054139: += optimization was not invalidating cached hash value
693 a = self.type2test('DNSSEC')
694 b = self.type2test('')
695 for c in a:
696 b += c
697 hash(b)
698 self.assertEqual(hash(a), hash(b))
699
700 def test_capitalize(self):
701 self.checkequal(' hello ', ' hello ', 'capitalize')
702 self.checkequal('Hello ', 'Hello ','capitalize')
703 self.checkequal('Hello ', 'hello ','capitalize')
704 self.checkequal('Aaaa', 'aaaa', 'capitalize')
705 self.checkequal('Aaaa', 'AaAa', 'capitalize')
706
Ezio Melottiee8d9982011-08-15 09:09:57 +0300707 # check that titlecased chars are lowered correctly
708 # \u1ffc is the titlecased char
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500709 self.checkequal('\u03a9\u0399\u1ff3\u1ff3\u1ff3',
Ezio Melottiee8d9982011-08-15 09:09:57 +0300710 '\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize')
711 # check with cased non-letter chars
712 self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
713 '\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize')
714 self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
715 '\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize')
716 self.checkequal('\u2160\u2171\u2172',
717 '\u2160\u2161\u2162', 'capitalize')
718 self.checkequal('\u2160\u2171\u2172',
719 '\u2170\u2171\u2172', 'capitalize')
720 # check with Ll chars with no upper - nothing changes here
721 self.checkequal('\u019b\u1d00\u1d86\u0221\u1fb7',
722 '\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize')
723
Georg Brandlc7885542007-03-06 19:16:20 +0000724 self.checkraises(TypeError, 'hello', 'capitalize', 42)
725
Georg Brandlc7885542007-03-06 19:16:20 +0000726 def test_additional_split(self):
727 self.checkequal(['this', 'is', 'the', 'split', 'function'],
728 'this is the split function', 'split')
729
730 # by whitespace
731 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
732 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
733 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
734 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
735 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
736 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000737 sys.maxsize-1)
Georg Brandlc7885542007-03-06 19:16:20 +0000738 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
739 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
740 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
741
742 self.checkequal([], ' ', 'split')
743 self.checkequal(['a'], ' a ', 'split')
744 self.checkequal(['a', 'b'], ' a b ', 'split')
745 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
746 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
747 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
748 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
749 aaa = ' a '*20
750 self.checkequal(['a']*20, aaa, 'split')
751 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
752 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
753
754 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000755 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000756
757 def test_additional_rsplit(self):
758 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
759 'this is the rsplit function', 'rsplit')
760
761 # by whitespace
762 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
763 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
764 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
765 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
766 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
767 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000768 sys.maxsize-20)
Georg Brandlc7885542007-03-06 19:16:20 +0000769 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
770 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
771 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
772
773 self.checkequal([], ' ', 'rsplit')
774 self.checkequal(['a'], ' a ', 'rsplit')
775 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
776 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
777 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
778 None, 1)
779 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
780 None, 2)
781 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
782 aaa = ' a '*20
783 self.checkequal(['a']*20, aaa, 'rsplit')
784 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
785 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
786
787 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000788 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000789
790 def test_strip(self):
791 self.checkequal('hello', ' hello ', 'strip')
792 self.checkequal('hello ', ' hello ', 'lstrip')
793 self.checkequal(' hello', ' hello ', 'rstrip')
794 self.checkequal('hello', 'hello', 'strip')
795
796 # strip/lstrip/rstrip with None arg
797 self.checkequal('hello', ' hello ', 'strip', None)
798 self.checkequal('hello ', ' hello ', 'lstrip', None)
799 self.checkequal(' hello', ' hello ', 'rstrip', None)
800 self.checkequal('hello', 'hello', 'strip', None)
801
802 # strip/lstrip/rstrip with str arg
803 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
804 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
805 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
806 self.checkequal('hello', 'hello', 'strip', 'xyz')
807
Georg Brandlc7885542007-03-06 19:16:20 +0000808 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
809 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
810 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
811
812 def test_ljust(self):
813 self.checkequal('abc ', 'abc', 'ljust', 10)
814 self.checkequal('abc ', 'abc', 'ljust', 6)
815 self.checkequal('abc', 'abc', 'ljust', 3)
816 self.checkequal('abc', 'abc', 'ljust', 2)
817 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
818 self.checkraises(TypeError, 'abc', 'ljust')
819
820 def test_rjust(self):
821 self.checkequal(' abc', 'abc', 'rjust', 10)
822 self.checkequal(' abc', 'abc', 'rjust', 6)
823 self.checkequal('abc', 'abc', 'rjust', 3)
824 self.checkequal('abc', 'abc', 'rjust', 2)
825 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
826 self.checkraises(TypeError, 'abc', 'rjust')
827
828 def test_center(self):
829 self.checkequal(' abc ', 'abc', 'center', 10)
830 self.checkequal(' abc ', 'abc', 'center', 6)
831 self.checkequal('abc', 'abc', 'center', 3)
832 self.checkequal('abc', 'abc', 'center', 2)
833 self.checkequal('***abc****', 'abc', 'center', 10, '*')
834 self.checkraises(TypeError, 'abc', 'center')
835
836 def test_swapcase(self):
837 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
838
839 self.checkraises(TypeError, 'hello', 'swapcase', 42)
840
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000841 def test_zfill(self):
842 self.checkequal('123', '123', 'zfill', 2)
843 self.checkequal('123', '123', 'zfill', 3)
844 self.checkequal('0123', '123', 'zfill', 4)
845 self.checkequal('+123', '+123', 'zfill', 3)
846 self.checkequal('+123', '+123', 'zfill', 4)
847 self.checkequal('+0123', '+123', 'zfill', 5)
848 self.checkequal('-123', '-123', 'zfill', 3)
849 self.checkequal('-123', '-123', 'zfill', 4)
850 self.checkequal('-0123', '-123', 'zfill', 5)
851 self.checkequal('000', '', 'zfill', 3)
852 self.checkequal('34', '34', 'zfill', 1)
853 self.checkequal('0034', '34', 'zfill', 4)
854
855 self.checkraises(TypeError, '123', 'zfill')
856
857class MixinStrUnicodeUserStringTest:
858 # additional tests that only work for
Martin Panter275bd962016-02-02 10:37:15 +0000859 # stringlike objects, i.e. str, UserString
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000860
861 def test_islower(self):
862 self.checkequal(False, '', 'islower')
863 self.checkequal(True, 'a', 'islower')
864 self.checkequal(False, 'A', 'islower')
865 self.checkequal(False, '\n', 'islower')
866 self.checkequal(True, 'abc', 'islower')
867 self.checkequal(False, 'aBc', 'islower')
868 self.checkequal(True, 'abc\n', 'islower')
869 self.checkraises(TypeError, 'abc', 'islower', 42)
870
871 def test_isupper(self):
872 self.checkequal(False, '', 'isupper')
873 self.checkequal(False, 'a', 'isupper')
874 self.checkequal(True, 'A', 'isupper')
875 self.checkequal(False, '\n', 'isupper')
876 self.checkequal(True, 'ABC', 'isupper')
877 self.checkequal(False, 'AbC', 'isupper')
878 self.checkequal(True, 'ABC\n', 'isupper')
879 self.checkraises(TypeError, 'abc', 'isupper', 42)
880
881 def test_istitle(self):
882 self.checkequal(False, '', 'istitle')
883 self.checkequal(False, 'a', 'istitle')
884 self.checkequal(True, 'A', 'istitle')
885 self.checkequal(False, '\n', 'istitle')
886 self.checkequal(True, 'A Titlecased Line', 'istitle')
887 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
888 self.checkequal(True, 'A Titlecased, Line', 'istitle')
889 self.checkequal(False, 'Not a capitalized String', 'istitle')
890 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
891 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
892 self.checkequal(False, 'NOT', 'istitle')
893 self.checkraises(TypeError, 'abc', 'istitle', 42)
894
895 def test_isspace(self):
896 self.checkequal(False, '', 'isspace')
897 self.checkequal(False, 'a', 'isspace')
898 self.checkequal(True, ' ', 'isspace')
899 self.checkequal(True, '\t', 'isspace')
900 self.checkequal(True, '\r', 'isspace')
901 self.checkequal(True, '\n', 'isspace')
902 self.checkequal(True, ' \t\r\n', 'isspace')
903 self.checkequal(False, ' \t\r\na', 'isspace')
904 self.checkraises(TypeError, 'abc', 'isspace', 42)
905
906 def test_isalpha(self):
907 self.checkequal(False, '', 'isalpha')
908 self.checkequal(True, 'a', 'isalpha')
909 self.checkequal(True, 'A', 'isalpha')
910 self.checkequal(False, '\n', 'isalpha')
911 self.checkequal(True, 'abc', 'isalpha')
912 self.checkequal(False, 'aBc123', 'isalpha')
913 self.checkequal(False, 'abc\n', 'isalpha')
914 self.checkraises(TypeError, 'abc', 'isalpha', 42)
915
916 def test_isalnum(self):
917 self.checkequal(False, '', 'isalnum')
918 self.checkequal(True, 'a', 'isalnum')
919 self.checkequal(True, 'A', 'isalnum')
920 self.checkequal(False, '\n', 'isalnum')
921 self.checkequal(True, '123abc456', 'isalnum')
922 self.checkequal(True, 'a1b3c', 'isalnum')
923 self.checkequal(False, 'aBc000 ', 'isalnum')
924 self.checkequal(False, 'abc\n', 'isalnum')
925 self.checkraises(TypeError, 'abc', 'isalnum', 42)
926
927 def test_isdigit(self):
928 self.checkequal(False, '', 'isdigit')
929 self.checkequal(False, 'a', 'isdigit')
930 self.checkequal(True, '0', 'isdigit')
931 self.checkequal(True, '0123456789', 'isdigit')
932 self.checkequal(False, '0123456789a', 'isdigit')
933
934 self.checkraises(TypeError, 'abc', 'isdigit', 42)
935
936 def test_title(self):
937 self.checkequal(' Hello ', ' hello ', 'title')
938 self.checkequal('Hello ', 'hello ', 'title')
939 self.checkequal('Hello ', 'Hello ', 'title')
940 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
941 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
942 self.checkequal('Getint', "getInt", 'title')
943 self.checkraises(TypeError, 'hello', 'title', 42)
944
945 def test_splitlines(self):
946 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
947 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
948 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
949 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
950 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
951 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +0100952 self.checkequal(['', 'abc', 'def', 'ghi', ''],
953 "\nabc\ndef\r\nghi\n\r", 'splitlines', False)
954 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
955 "\nabc\ndef\r\nghi\n\r", 'splitlines', True)
956 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r",
957 'splitlines', keepends=False)
958 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
959 "\nabc\ndef\r\nghi\n\r", 'splitlines', keepends=True)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000960
961 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
962
963 def test_startswith(self):
964 self.checkequal(True, 'hello', 'startswith', 'he')
965 self.checkequal(True, 'hello', 'startswith', 'hello')
966 self.checkequal(False, 'hello', 'startswith', 'hello world')
967 self.checkequal(True, 'hello', 'startswith', '')
968 self.checkequal(False, 'hello', 'startswith', 'ello')
969 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
970 self.checkequal(True, 'hello', 'startswith', 'o', 4)
971 self.checkequal(False, 'hello', 'startswith', 'o', 5)
972 self.checkequal(True, 'hello', 'startswith', '', 5)
973 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
974 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
975 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
976 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +0300977 self.checkequal(True, '', 'startswith', '', 0, 1)
978 self.checkequal(True, '', 'startswith', '', 0, 0)
979 self.checkequal(False, '', 'startswith', '', 1, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000980
981 # test negative indices
982 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
983 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
984 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
985 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
986 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
987 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
988 self.checkequal(False, 'hello', 'startswith', 'o', -2)
989 self.checkequal(True, 'hello', 'startswith', 'o', -1)
990 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
991 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
992
993 self.checkraises(TypeError, 'hello', 'startswith')
994 self.checkraises(TypeError, 'hello', 'startswith', 42)
995
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000996 # test tuple arguments
997 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
998 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
999 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
1000 self.checkequal(False, 'hello', 'startswith', ())
1001 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
1002 'rld', 'lowo'), 3)
1003 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
1004 'rld'), 3)
1005 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
1006 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
1007 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
1008
1009 self.checkraises(TypeError, 'hello', 'startswith', (42,))
1010
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001011 def test_endswith(self):
1012 self.checkequal(True, 'hello', 'endswith', 'lo')
1013 self.checkequal(False, 'hello', 'endswith', 'he')
1014 self.checkequal(True, 'hello', 'endswith', '')
1015 self.checkequal(False, 'hello', 'endswith', 'hello world')
1016 self.checkequal(False, 'helloworld', 'endswith', 'worl')
1017 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
1018 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
1019 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
1020 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
1021 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
1022 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
1023 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
1024 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
1025 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03001026 self.checkequal(True, '', 'endswith', '', 0, 1)
1027 self.checkequal(True, '', 'endswith', '', 0, 0)
1028 self.checkequal(False, '', 'endswith', '', 1, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001029
1030 # test negative indices
1031 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
1032 self.checkequal(False, 'hello', 'endswith', 'he', -2)
1033 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
1034 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
1035 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
1036 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
1037 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
1038 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
1039 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
1040 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
1041 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
1042 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
1043 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
1044
1045 self.checkraises(TypeError, 'hello', 'endswith')
1046 self.checkraises(TypeError, 'hello', 'endswith', 42)
1047
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001048 # test tuple arguments
1049 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
1050 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
1051 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
1052 self.checkequal(False, 'hello', 'endswith', ())
1053 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
1054 'rld', 'lowo'), 3)
1055 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
1056 'rld'), 3, -1)
1057 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
1058 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
1059 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
1060
1061 self.checkraises(TypeError, 'hello', 'endswith', (42,))
1062
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001063 def test___contains__(self):
Ezio Melottib19f43d2010-01-24 20:59:24 +00001064 self.checkequal(True, '', '__contains__', '')
1065 self.checkequal(True, 'abc', '__contains__', '')
1066 self.checkequal(False, 'abc', '__contains__', '\0')
1067 self.checkequal(True, '\0abc', '__contains__', '\0')
1068 self.checkequal(True, 'abc\0', '__contains__', '\0')
1069 self.checkequal(True, '\0abc', '__contains__', 'a')
1070 self.checkequal(True, 'asdf', '__contains__', 'asdf')
1071 self.checkequal(False, 'asd', '__contains__', 'asdf')
1072 self.checkequal(False, '', '__contains__', 'asdf')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001073
1074 def test_subscript(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001075 self.checkequal('a', 'abc', '__getitem__', 0)
1076 self.checkequal('c', 'abc', '__getitem__', -1)
1077 self.checkequal('a', 'abc', '__getitem__', 0)
1078 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
1079 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
1080 self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
1081 self.checkequal('', 'abc', '__getitem__', slice(0, 0))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001082
1083 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
1084
1085 def test_slice(self):
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001086 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
1087 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
1088 self.checkequal('ab', 'abc', '__getitem__', slice(0, 2))
1089 self.checkequal('bc', 'abc', '__getitem__', slice(1, 3))
1090 self.checkequal('b', 'abc', '__getitem__', slice(1, 2))
1091 self.checkequal('', 'abc', '__getitem__', slice(2, 2))
1092 self.checkequal('', 'abc', '__getitem__', slice(1000, 1000))
1093 self.checkequal('', 'abc', '__getitem__', slice(2000, 1000))
1094 self.checkequal('', 'abc', '__getitem__', slice(2, 1))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001095
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001096 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001097
Thomas Woutersed03b412007-08-28 21:37:11 +00001098 def test_extended_getslice(self):
1099 # Test extended slicing by comparing with list slicing.
1100 s = string.ascii_letters + string.digits
1101 indices = (0, None, 1, 3, 41, -1, -2, -37)
1102 for start in indices:
1103 for stop in indices:
1104 # Skip step 0 (invalid)
1105 for step in indices[1:]:
1106 L = list(s)[start:stop:step]
1107 self.checkequal("".join(L), s, '__getitem__',
1108 slice(start, stop, step))
1109
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001110 def test_mul(self):
1111 self.checkequal('', 'abc', '__mul__', -1)
1112 self.checkequal('', 'abc', '__mul__', 0)
1113 self.checkequal('abc', 'abc', '__mul__', 1)
1114 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
1115 self.checkraises(TypeError, 'abc', '__mul__')
1116 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117 # XXX: on a 64-bit system, this doesn't raise an overflow error,
1118 # but either raises a MemoryError, or succeeds (if you have 54TiB)
1119 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001120
1121 def test_join(self):
1122 # join now works with any sequence type
1123 # moved here, because the argument order is
Benjamin Petersonc31f12d2014-09-28 12:56:42 -04001124 # different in string.join
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001125 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
1126 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001127 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
1128 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001129 self.checkequal('w x y z', ' ', 'join', Sequence())
1130 self.checkequal('abc', 'a', 'join', ('abc',))
1131 self.checkequal('z', 'a', 'join', UserList(['z']))
Walter Dörwald67e83882007-05-05 12:26:27 +00001132 self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c'])
Guido van Rossum98297ee2007-11-06 21:34:58 +00001133 self.assertRaises(TypeError, '.'.join, ['a', 'b', 3])
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001134 for i in [5, 25, 125]:
1135 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1136 ['a' * i] * i)
1137 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1138 ('a' * i,) * i)
1139
Guido van Rossum98297ee2007-11-06 21:34:58 +00001140 #self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1())
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001141 self.checkequal('a b c', ' ', 'join', BadSeq2())
1142
1143 self.checkraises(TypeError, ' ', 'join')
Benjamin Petersonc31f12d2014-09-28 12:56:42 -04001144 self.checkraises(TypeError, ' ', 'join', None)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001145 self.checkraises(TypeError, ' ', 'join', 7)
Guido van Rossumf1044292007-09-27 18:01:22 +00001146 self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()])
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001147 try:
1148 def f():
1149 yield 4 + ""
1150 self.fixtype(' ').join(f())
Guido van Rossumb940e112007-01-10 16:19:56 +00001151 except TypeError as e:
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001152 if '+' not in str(e):
1153 self.fail('join() ate exception message')
1154 else:
1155 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001156
1157 def test_formatting(self):
1158 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1159 self.checkequal('+10+', '+%d+', '__mod__', 10)
1160 self.checkequal('a', "%c", '__mod__', "a")
1161 self.checkequal('a', "%c", '__mod__', "a")
1162 self.checkequal('"', "%c", '__mod__', 34)
1163 self.checkequal('$', "%c", '__mod__', 36)
1164 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001165 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001166
1167 for ordinal in (-100, 0x200000):
1168 # unicode raises ValueError, str raises OverflowError
1169 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1170
Christian Heimesa612dc02008-02-24 13:08:18 +00001171 longvalue = sys.maxsize + 10
1172 slongvalue = str(longvalue)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001173 self.checkequal(' 42', '%3ld', '__mod__', 42)
Christian Heimesa612dc02008-02-24 13:08:18 +00001174 self.checkequal('42', '%d', '__mod__', 42.0)
1175 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1176 self.checkcall('%d', '__mod__', float(longvalue))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001177 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001178 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001179
1180 self.checkraises(TypeError, 'abc', '__mod__')
1181 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1182 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
Ethan Furman38d872e2014-03-19 08:38:52 -07001183 self.checkraises(TypeError, '%c', '__mod__', (None,))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001184 self.checkraises(ValueError, '%(foo', '__mod__', {})
1185 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
Christian Heimesa612dc02008-02-24 13:08:18 +00001186 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
Mark Dickinson5c2db372009-12-05 20:28:34 +00001187 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int conversion provided
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001188
1189 # argument names with properly nested brackets are supported
1190 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1191
1192 # 100 is a magic number in PyUnicode_Format, this forces a resize
1193 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1194
1195 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1196 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1197 self.checkraises(ValueError, '%10', '__mod__', (42,))
1198
Mark Dickinson99e2e552012-05-07 11:20:50 +01001199 # Outrageously large width or precision should raise ValueError.
1200 self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2))
1201 self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2))
Serhiy Storchaka441d30f2013-01-19 12:26:26 +02001202 self.checkraises(OverflowError, '%*s', '__mod__',
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001203 (sys.maxsize + 1, ''))
Serhiy Storchaka441d30f2013-01-19 12:26:26 +02001204 self.checkraises(OverflowError, '%.*f', '__mod__',
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001205 (sys.maxsize + 1, 1. / 7))
Serhiy Storchaka441d30f2013-01-19 12:26:26 +02001206
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -04001207 class X(object): pass
1208 self.checkraises(TypeError, 'abc', '__mod__', X())
1209
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001210 @support.cpython_only
1211 def test_formatting_c_limits(self):
1212 from _testcapi import PY_SSIZE_T_MAX, INT_MAX, UINT_MAX
1213 SIZE_MAX = (1 << (PY_SSIZE_T_MAX.bit_length() + 1)) - 1
1214 self.checkraises(OverflowError, '%*s', '__mod__',
1215 (PY_SSIZE_T_MAX + 1, ''))
1216 self.checkraises(OverflowError, '%.*f', '__mod__',
1217 (INT_MAX + 1, 1. / 7))
1218 # Issue 15989
1219 self.checkraises(OverflowError, '%*s', '__mod__',
1220 (SIZE_MAX + 1, ''))
1221 self.checkraises(OverflowError, '%.*f', '__mod__',
1222 (UINT_MAX + 1, 1. / 7))
1223
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001224 def test_floatformatting(self):
1225 # float formatting
Guido van Rossum805365e2007-05-07 22:24:25 +00001226 for prec in range(100):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001227 format = '%%.%if' % prec
1228 value = 0.01
Guido van Rossum805365e2007-05-07 22:24:25 +00001229 for x in range(60):
Florent Xiclunaa87b3832010-09-13 02:28:18 +00001230 value = value * 3.14159265359 / 3.0 * 10.0
Mark Dickinsonf489caf2009-05-01 11:42:00 +00001231 self.checkcall(format, "__mod__", value)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001232
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233 def test_inplace_rewrites(self):
1234 # Check that strings don't copy and modify cached single-character strings
1235 self.checkequal('a', 'A', 'lower')
1236 self.checkequal(True, 'A', 'isupper')
1237 self.checkequal('A', 'a', 'upper')
1238 self.checkequal(True, 'a', 'islower')
1239
1240 self.checkequal('a', 'A', 'replace', 'A', 'a')
1241 self.checkequal(True, 'A', 'isupper')
1242
1243 self.checkequal('A', 'a', 'capitalize')
1244 self.checkequal(True, 'a', 'islower')
1245
1246 self.checkequal('A', 'a', 'swapcase')
1247 self.checkequal(True, 'a', 'islower')
1248
1249 self.checkequal('A', 'a', 'title')
1250 self.checkequal(True, 'a', 'islower')
1251
1252 def test_partition(self):
1253
1254 self.checkequal(('this is the par', 'ti', 'tion method'),
1255 'this is the partition method', 'partition', 'ti')
1256
1257 # from raymond's original specification
1258 S = 'http://www.python.org'
1259 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1260 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1261 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1262 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1263
1264 self.checkraises(ValueError, S, 'partition', '')
1265 self.checkraises(TypeError, S, 'partition', None)
1266
1267 def test_rpartition(self):
1268
1269 self.checkequal(('this is the rparti', 'ti', 'on method'),
1270 'this is the rpartition method', 'rpartition', 'ti')
1271
1272 # from raymond's original specification
1273 S = 'http://www.python.org'
1274 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001275 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1277 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1278
1279 self.checkraises(ValueError, S, 'rpartition', '')
1280 self.checkraises(TypeError, S, 'rpartition', None)
1281
Jesus Ceaac451502011-04-20 17:09:23 +02001282 def test_none_arguments(self):
1283 # issue 11828
1284 s = 'hello'
1285 self.checkequal(2, s, 'find', 'l', None)
1286 self.checkequal(3, s, 'find', 'l', -2, None)
1287 self.checkequal(2, s, 'find', 'l', None, -2)
1288 self.checkequal(0, s, 'find', 'h', None, None)
1289
1290 self.checkequal(3, s, 'rfind', 'l', None)
1291 self.checkequal(3, s, 'rfind', 'l', -2, None)
1292 self.checkequal(2, s, 'rfind', 'l', None, -2)
1293 self.checkequal(0, s, 'rfind', 'h', None, None)
1294
1295 self.checkequal(2, s, 'index', 'l', None)
1296 self.checkequal(3, s, 'index', 'l', -2, None)
1297 self.checkequal(2, s, 'index', 'l', None, -2)
1298 self.checkequal(0, s, 'index', 'h', None, None)
1299
1300 self.checkequal(3, s, 'rindex', 'l', None)
1301 self.checkequal(3, s, 'rindex', 'l', -2, None)
1302 self.checkequal(2, s, 'rindex', 'l', None, -2)
1303 self.checkequal(0, s, 'rindex', 'h', None, None)
1304
1305 self.checkequal(2, s, 'count', 'l', None)
1306 self.checkequal(1, s, 'count', 'l', -2, None)
1307 self.checkequal(1, s, 'count', 'l', None, -2)
1308 self.checkequal(0, s, 'count', 'x', None, None)
1309
1310 self.checkequal(True, s, 'endswith', 'o', None)
1311 self.checkequal(True, s, 'endswith', 'lo', -2, None)
1312 self.checkequal(True, s, 'endswith', 'l', None, -2)
1313 self.checkequal(False, s, 'endswith', 'x', None, None)
1314
1315 self.checkequal(True, s, 'startswith', 'h', None)
1316 self.checkequal(True, s, 'startswith', 'l', -2, None)
1317 self.checkequal(True, s, 'startswith', 'h', None, -2)
1318 self.checkequal(False, s, 'startswith', 'x', None, None)
1319
1320 def test_find_etc_raise_correct_error_messages(self):
1321 # issue 11828
1322 s = 'hello'
1323 x = 'x'
Ezio Melottiaf928422011-04-20 21:56:21 +03001324 self.assertRaisesRegex(TypeError, r'^find\(', s.find,
Jesus Ceaac451502011-04-20 17:09:23 +02001325 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001326 self.assertRaisesRegex(TypeError, r'^rfind\(', s.rfind,
Jesus Ceaac451502011-04-20 17:09:23 +02001327 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001328 self.assertRaisesRegex(TypeError, r'^index\(', s.index,
Jesus Ceaac451502011-04-20 17:09:23 +02001329 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001330 self.assertRaisesRegex(TypeError, r'^rindex\(', s.rindex,
Jesus Ceaac451502011-04-20 17:09:23 +02001331 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001332 self.assertRaisesRegex(TypeError, r'^count\(', s.count,
Jesus Ceaac451502011-04-20 17:09:23 +02001333 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001334 self.assertRaisesRegex(TypeError, r'^startswith\(', s.startswith,
Jesus Ceaac451502011-04-20 17:09:23 +02001335 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001336 self.assertRaisesRegex(TypeError, r'^endswith\(', s.endswith,
Jesus Ceaac451502011-04-20 17:09:23 +02001337 x, None, None, None)
1338
Victor Stinnerb3f55012012-08-02 23:05:01 +02001339 # issue #15534
1340 self.checkequal(10, "...\u043c......<", "find", "<")
1341
Walter Dörwald57d88e52004-08-26 16:53:04 +00001342
Walter Dörwald57d88e52004-08-26 16:53:04 +00001343class MixinStrUnicodeTest:
Martin Panter275bd962016-02-02 10:37:15 +00001344 # Additional tests that only work with str.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001345
1346 def test_bug1001011(self):
1347 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001348 # involving a subclass.
1349 # Make sure that it is of the appropriate type.
1350 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001351 t = self.type2test
1352 class subclass(t):
1353 pass
1354 s1 = subclass("abcd")
1355 s2 = t().join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001356 self.assertIsNot(s1, s2)
1357 self.assertIs(type(s2), t)
Tim Peters108f1372004-08-27 05:36:07 +00001358
1359 s1 = t("abcd")
1360 s2 = t().join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001361 self.assertIs(s1, s2)
Tim Peters108f1372004-08-27 05:36:07 +00001362
1363 # Should also test mixed-type join.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001364 if t is str:
Tim Peters108f1372004-08-27 05:36:07 +00001365 s1 = subclass("abcd")
1366 s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001367 self.assertIsNot(s1, s2)
1368 self.assertIs(type(s2), t)
Tim Peters108f1372004-08-27 05:36:07 +00001369
1370 s1 = t("abcd")
1371 s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001372 self.assertIs(s1, s2)
Tim Peters108f1372004-08-27 05:36:07 +00001373
Guido van Rossum98297ee2007-11-06 21:34:58 +00001374## elif t is str8:
1375## s1 = subclass("abcd")
1376## s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001377## self.assertIsNot(s1, s2)
1378## self.assertIs(type(s2), str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001379
Guido van Rossum98297ee2007-11-06 21:34:58 +00001380## s1 = t("abcd")
1381## s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001382## self.assertIsNot(s1, s2)
1383## self.assertIs(type(s2), str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001384
1385 else:
1386 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)