blob: 4800d6d7f247cad1ba52b772ab8ca922ea820add [file] [log] [blame]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001"""
2Common tests shared by test_str, test_unicode, test_userstring and test_string.
3"""
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)
82 self.assertRaises(
83 exc,
Guido van Rossum09549f42007-08-27 20:40:10 +000084 getattr(obj, methodname),
Walter Dörwald0fd583c2003-02-21 12:53:50 +000085 *args
86 )
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000087
Guido van Rossum09549f42007-08-27 20:40:10 +000088 # call obj.method(*args) without any checks
89 def checkcall(self, obj, methodname, *args):
90 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000091 args = self.fixtype(args)
Guido van Rossum09549f42007-08-27 20:40:10 +000092 getattr(obj, methodname)(*args)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000093
Walter Dörwald0fd583c2003-02-21 12:53:50 +000094 def test_count(self):
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(3, 'aaa', 'count', 'a')
100 self.checkequal(0, 'aaa', 'count', 'b')
101 self.checkequal(0, 'aaa', 'count', 'b')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000102 self.checkequal(2, 'aaa', 'count', 'a', 1)
103 self.checkequal(0, 'aaa', 'count', 'a', 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000104 self.checkequal(1, 'aaa', 'count', 'a', -1)
105 self.checkequal(3, 'aaa', 'count', 'a', -10)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000106 self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
107 self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000108 self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
109 self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000110 self.checkequal(3, 'aaa', 'count', '', 1)
111 self.checkequal(1, 'aaa', 'count', '', 3)
112 self.checkequal(0, 'aaa', 'count', '', 10)
113 self.checkequal(2, 'aaa', 'count', '', -1)
114 self.checkequal(4, 'aaa', 'count', '', -10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000115
Amaury Forgeot d'Arcf2e93682008-09-26 22:48:41 +0000116 self.checkequal(1, '', 'count', '')
117 self.checkequal(0, '', 'count', '', 1, 1)
118 self.checkequal(0, '', 'count', '', sys.maxsize, 0)
119
120 self.checkequal(0, '', 'count', 'xx')
121 self.checkequal(0, '', 'count', 'xx', 1, 1)
122 self.checkequal(0, '', 'count', 'xx', sys.maxsize, 0)
123
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000124 self.checkraises(TypeError, 'hello', 'count')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200125
126 if self.contains_bytes:
127 self.checkequal(0, 'hello', 'count', 42)
128 else:
129 self.checkraises(TypeError, 'hello', 'count', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000130
Raymond Hettinger57e74472005-02-20 09:54:53 +0000131 # For a variety of combinations,
132 # verify that str.count() matches an equivalent function
133 # replacing all occurrences and then differencing the string lengths
134 charset = ['', 'a', 'b']
135 digits = 7
136 base = len(charset)
137 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000138 for i in range(base ** digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000139 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000140 for j in range(digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000141 i, m = divmod(i, base)
142 entry.append(charset[m])
143 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000144 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger57e74472005-02-20 09:54:53 +0000145 for i in teststrings:
Raymond Hettinger57e74472005-02-20 09:54:53 +0000146 n = len(i)
147 for j in teststrings:
148 r1 = i.count(j)
149 if j:
Guido van Rossum09549f42007-08-27 20:40:10 +0000150 r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))),
151 len(j))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000152 else:
153 r2, rem = len(i)+1, 0
154 if rem or r1 != r2:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
156 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000157
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000158 def test_find(self):
159 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
160 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
161 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
162
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000163 self.checkequal(0, 'abc', 'find', '', 0)
164 self.checkequal(3, 'abc', 'find', '', 3)
165 self.checkequal(-1, 'abc', 'find', '', 4)
166
Christian Heimes9cd17752007-11-18 19:35:23 +0000167 # to check the ability to pass None as defaults
168 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
169 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
170 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
171 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
172 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
173
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000174 self.checkraises(TypeError, 'hello', 'find')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200175
176 if self.contains_bytes:
177 self.checkequal(-1, 'hello', 'find', 42)
178 else:
179 self.checkraises(TypeError, 'hello', 'find', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000180
Amaury Forgeot d'Arcf2e93682008-09-26 22:48:41 +0000181 self.checkequal(0, '', 'find', '')
182 self.checkequal(-1, '', 'find', '', 1, 1)
183 self.checkequal(-1, '', 'find', '', sys.maxsize, 0)
184
185 self.checkequal(-1, '', 'find', 'xx')
186 self.checkequal(-1, '', 'find', 'xx', 1, 1)
187 self.checkequal(-1, '', 'find', 'xx', sys.maxsize, 0)
188
Antoine Pitrou74edda02010-01-02 21:51:33 +0000189 # issue 7458
190 self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0)
191
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000192 # For a variety of combinations,
193 # verify that str.find() matches __contains__
194 # and that the found substring is really at that location
195 charset = ['', 'a', 'b', 'c']
196 digits = 5
197 base = len(charset)
198 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000199 for i in range(base ** digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000200 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000201 for j in range(digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000202 i, m = divmod(i, base)
203 entry.append(charset[m])
204 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000205 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000206 for i in teststrings:
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000207 for j in teststrings:
208 loc = i.find(j)
209 r1 = (loc != -1)
210 r2 = j in i
Antoine Pitrou2e544fb2010-01-02 21:55:17 +0000211 self.assertEqual(r1, r2)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000212 if loc != -1:
213 self.assertEqual(i[loc:loc+len(j)], j)
214
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000215 def test_rfind(self):
216 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
217 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
218 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
219 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
220
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000221 self.checkequal(3, 'abc', 'rfind', '', 0)
222 self.checkequal(3, 'abc', 'rfind', '', 3)
223 self.checkequal(-1, 'abc', 'rfind', '', 4)
224
Christian Heimes9cd17752007-11-18 19:35:23 +0000225 # to check the ability to pass None as defaults
226 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
227 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
228 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
229 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
230 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
231
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000232 self.checkraises(TypeError, 'hello', 'rfind')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200233
234 if self.contains_bytes:
235 self.checkequal(-1, 'hello', 'rfind', 42)
236 else:
237 self.checkraises(TypeError, 'hello', 'rfind', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000238
Antoine Pitrouda2ecaf2010-01-02 21:40:36 +0000239 # For a variety of combinations,
240 # verify that str.rfind() matches __contains__
241 # and that the found substring is really at that location
242 charset = ['', 'a', 'b', 'c']
243 digits = 5
244 base = len(charset)
245 teststrings = set()
246 for i in range(base ** digits):
247 entry = []
248 for j in range(digits):
249 i, m = divmod(i, base)
250 entry.append(charset[m])
251 teststrings.add(''.join(entry))
252 teststrings = [self.fixtype(ts) for ts in teststrings]
253 for i in teststrings:
254 for j in teststrings:
255 loc = i.rfind(j)
256 r1 = (loc != -1)
257 r2 = j in i
Antoine Pitrou2e544fb2010-01-02 21:55:17 +0000258 self.assertEqual(r1, r2)
Antoine Pitrouda2ecaf2010-01-02 21:40:36 +0000259 if loc != -1:
260 self.assertEqual(i[loc:loc+len(j)], j)
261
Antoine Pitrou74edda02010-01-02 21:51:33 +0000262 # issue 7458
263 self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0)
264
Victor Stinnerb3f55012012-08-02 23:05:01 +0200265 # issue #15534
266 self.checkequal(0, '<......\u043c...', "rfind", "<")
267
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000268 def test_index(self):
269 self.checkequal(0, 'abcdefghiabc', 'index', '')
270 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
271 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
272 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
273
274 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
275 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
276 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
277 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
278
Christian Heimes9cd17752007-11-18 19:35:23 +0000279 # to check the ability to pass None as defaults
280 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
281 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
282 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
283 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
284 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
285
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000286 self.checkraises(TypeError, 'hello', 'index')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200287
288 if self.contains_bytes:
289 self.checkraises(ValueError, 'hello', 'index', 42)
290 else:
291 self.checkraises(TypeError, 'hello', 'index', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000292
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
Christian Heimes9cd17752007-11-18 19:35:23 +0000305 # 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
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000312 self.checkraises(TypeError, 'hello', 'rindex')
Antoine Pitrouac65d962011-10-20 23:54:17 +0200313
314 if self.contains_bytes:
315 self.checkraises(ValueError, 'hello', 'rindex', 42)
316 else:
317 self.checkraises(TypeError, 'hello', 'rindex', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000318
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000319 def test_lower(self):
320 self.checkequal('hello', 'HeLLo', 'lower')
321 self.checkequal('hello', 'hello', 'lower')
322 self.checkraises(TypeError, 'hello', 'lower', 42)
323
324 def test_upper(self):
325 self.checkequal('HELLO', 'HeLLo', 'upper')
326 self.checkequal('HELLO', 'HELLO', 'upper')
327 self.checkraises(TypeError, 'hello', 'upper', 42)
328
329 def test_expandtabs(self):
330 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
331 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
332 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
333 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
334 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
335 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
336 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
337 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
338
339 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
340 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000341 if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000342 self.checkraises(OverflowError,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000343 '\ta\n\tb', 'expandtabs', sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000344
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000345 def test_split(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000346 # by a char
347 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000348 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000349 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
350 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
351 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
352 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000353 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000354 sys.maxsize-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000355 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
356 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
357 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000358 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
359 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000360 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
361
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
363 self.checkequal(['a']*15 +['a|a|a|a|a'],
364 ('a|'*20)[:-1], 'split', '|', 15)
365
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000366 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000367 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000368 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
369 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
370 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
371 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000372 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000373 sys.maxsize-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000374 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
375 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000376 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
378 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
379 'split', 'test')
380 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
381 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
382 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
383 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
384 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
385 self.checkequal([''], '', 'split', 'aaa')
386 self.checkequal(['aa'], 'aa', 'split', 'aaa')
387 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
388 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
389
390 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
391 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
392 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
393 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000394
Ezio Melotticda6b6d2012-02-26 09:39:55 +0200395 # with keyword args
396 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', sep='|')
397 self.checkequal(['a', 'b|c|d'],
398 'a|b|c|d', 'split', '|', maxsplit=1)
399 self.checkequal(['a', 'b|c|d'],
400 'a|b|c|d', 'split', sep='|', maxsplit=1)
401 self.checkequal(['a', 'b|c|d'],
402 'a|b|c|d', 'split', maxsplit=1, sep='|')
403 self.checkequal(['a', 'b c d'],
404 'a b c d', 'split', maxsplit=1)
405
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000406 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000407 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
408
Thomas Wouters477c8d52006-05-27 19:21:47 +0000409 # null case
410 self.checkraises(ValueError, 'hello', 'split', '')
411 self.checkraises(ValueError, 'hello', 'split', '', 0)
412
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000413 def test_rsplit(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000414 # by a char
415 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
416 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
417 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
418 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
419 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000420 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000421 sys.maxsize-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000422 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
423 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
424 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
426 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
427
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000428 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
429
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
431 self.checkequal(['a|a|a|a|a']+['a']*15,
432 ('a|'*20)[:-1], 'rsplit', '|', 15)
433
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000434 # by string
435 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
436 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
437 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
438 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
439 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000441 sys.maxsize-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000442 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
443 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
444 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
446 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
447 'rsplit', 'test')
448 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
449 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
450 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
451 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
452 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
453 self.checkequal([''], '', 'rsplit', 'aaa')
454 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
455 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
456 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
457
458 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
459 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
460 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
461 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000462
Ezio Melotticda6b6d2012-02-26 09:39:55 +0200463 # with keyword args
464 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', sep='|')
465 self.checkequal(['a|b|c', 'd'],
466 'a|b|c|d', 'rsplit', '|', maxsplit=1)
467 self.checkequal(['a|b|c', 'd'],
468 'a|b|c|d', 'rsplit', sep='|', maxsplit=1)
469 self.checkequal(['a|b|c', 'd'],
470 'a|b|c|d', 'rsplit', maxsplit=1, sep='|')
471 self.checkequal(['a b c', 'd'],
472 'a b c d', 'rsplit', maxsplit=1)
473
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000474 # argument type
475 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000476
Thomas Wouters477c8d52006-05-27 19:21:47 +0000477 # null case
478 self.checkraises(ValueError, 'hello', 'rsplit', '')
479 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
480
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000481 def test_replace(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000482 EQ = self.checkequal
483
484 # Operations on the empty string
485 EQ("", "", "replace", "", "")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000486 EQ("A", "", "replace", "", "A")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000487 EQ("", "", "replace", "A", "")
488 EQ("", "", "replace", "A", "A")
489 EQ("", "", "replace", "", "", 100)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000490 EQ("", "", "replace", "", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000491
492 # interleave (from=="", 'to' gets inserted everywhere)
493 EQ("A", "A", "replace", "", "")
494 EQ("*A*", "A", "replace", "", "*")
495 EQ("*1A*1", "A", "replace", "", "*1")
496 EQ("*-#A*-#", "A", "replace", "", "*-#")
497 EQ("*-A*-A*-", "AA", "replace", "", "*-")
498 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000499 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000500 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
501 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
502 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
503 EQ("*-AA", "AA", "replace", "", "*-", 1)
504 EQ("AA", "AA", "replace", "", "*-", 0)
505
506 # single character deletion (from=="A", to=="")
507 EQ("", "A", "replace", "A", "")
508 EQ("", "AAA", "replace", "A", "")
509 EQ("", "AAA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000510 EQ("", "AAA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511 EQ("", "AAA", "replace", "A", "", 4)
512 EQ("", "AAA", "replace", "A", "", 3)
513 EQ("A", "AAA", "replace", "A", "", 2)
514 EQ("AA", "AAA", "replace", "A", "", 1)
515 EQ("AAA", "AAA", "replace", "A", "", 0)
516 EQ("", "AAAAAAAAAA", "replace", "A", "")
517 EQ("BCD", "ABACADA", "replace", "A", "")
518 EQ("BCD", "ABACADA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000519 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000520 EQ("BCD", "ABACADA", "replace", "A", "", 5)
521 EQ("BCD", "ABACADA", "replace", "A", "", 4)
522 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
523 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
524 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
525 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
526 EQ("BCD", "ABCAD", "replace", "A", "")
527 EQ("BCD", "ABCADAA", "replace", "A", "")
528 EQ("BCD", "BCD", "replace", "A", "")
529 EQ("*************", "*************", "replace", "A", "")
530 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
531
532 # substring deletion (from=="the", to=="")
533 EQ("", "the", "replace", "the", "")
534 EQ("ater", "theater", "replace", "the", "")
535 EQ("", "thethe", "replace", "the", "")
536 EQ("", "thethethethe", "replace", "the", "")
537 EQ("aaaa", "theatheatheathea", "replace", "the", "")
538 EQ("that", "that", "replace", "the", "")
539 EQ("thaet", "thaet", "replace", "the", "")
540 EQ("here and re", "here and there", "replace", "the", "")
541 EQ("here and re and re", "here and there and there",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000542 "replace", "the", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 EQ("here and re and re", "here and there and there",
544 "replace", "the", "", -1)
545 EQ("here and re and re", "here and there and there",
546 "replace", "the", "", 3)
547 EQ("here and re and re", "here and there and there",
548 "replace", "the", "", 2)
549 EQ("here and re and there", "here and there and there",
550 "replace", "the", "", 1)
551 EQ("here and there and there", "here and there and there",
552 "replace", "the", "", 0)
553 EQ("here and re and re", "here and there and there", "replace", "the", "")
554
555 EQ("abc", "abc", "replace", "the", "")
556 EQ("abcdefg", "abcdefg", "replace", "the", "")
557
558 # substring deletion (from=="bob", to=="")
559 EQ("bob", "bbobob", "replace", "bob", "")
560 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
561 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
562 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
563
564 # single character replace in place (len(from)==len(to)==1)
565 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
566 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000567 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
569 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
570 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
571 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
572 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
573
574 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
575 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
576 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
577 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
578 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
579
580 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
581
582 # substring replace in place (len(from)==len(to) > 1)
583 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000584 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
586 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
587 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
588 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
589 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
590 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
591 EQ("cobob", "bobob", "replace", "bob", "cob")
592 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
593 EQ("bobob", "bobob", "replace", "bot", "bot")
594
595 # replace single character (len(from)==1, len(to)>1)
596 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
597 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000598 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
600 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
601 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
602 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
Victor Stinnerb3f55012012-08-02 23:05:01 +0200603 # issue #15534
604 EQ('...\u043c......&lt;', '...\u043c......<', "replace", "<", "&lt;")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605
606 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
607
608 # replace substring (len(from)>1, len(to)!=len(from))
609 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
610 "replace", "spam", "ham")
611 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000612 "replace", "spam", "ham", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000613 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
614 "replace", "spam", "ham", -1)
615 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
616 "replace", "spam", "ham", 4)
617 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
618 "replace", "spam", "ham", 3)
619 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
620 "replace", "spam", "ham", 2)
621 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
622 "replace", "spam", "ham", 1)
623 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
624 "replace", "spam", "ham", 0)
625
626 EQ("bobob", "bobobob", "replace", "bobob", "bob")
627 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
628 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
629
Guido van Rossum39478e82007-08-27 17:23:59 +0000630 # XXX Commented out. Is there any reason to support buffer objects
631 # as arguments for str.replace()? GvR
Guido van Rossum254348e2007-11-21 19:29:53 +0000632## ba = bytearray('a')
633## bb = bytearray('b')
Guido van Rossum39478e82007-08-27 17:23:59 +0000634## EQ("bbc", "abc", "replace", ba, bb)
635## EQ("aac", "abc", "replace", bb, ba)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Thomas Wouters477c8d52006-05-27 19:21:47 +0000637 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000638 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
639 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
640 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
641 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
642 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
643 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
644 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
645 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
646 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
647 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
648 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
649 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
650 self.checkequal('', '', 'replace', '', '')
651 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
652 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
653 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
654 # MemoryError due to empty result (platform malloc issue when requesting
655 # 0 bytes).
656 self.checkequal('', '123', 'replace', '123', '')
657 self.checkequal('', '123123', 'replace', '123', '')
658 self.checkequal('x', '123x123', 'replace', '123', '')
659
660 self.checkraises(TypeError, 'hello', 'replace')
661 self.checkraises(TypeError, 'hello', 'replace', 42)
662 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
663 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
664
Zachary Ware9fe6d862013-12-08 00:20:35 -0600665 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
666 'only applies to 32-bit platforms')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000667 def test_replace_overflow(self):
668 # Check for overflow checking on 32 bit machines
Thomas Wouters477c8d52006-05-27 19:21:47 +0000669 A2_16 = "A" * (2**16)
670 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
671 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
672 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
673
Georg Brandlc7885542007-03-06 19:16:20 +0000674
675
676class CommonTest(BaseTest):
677 # This testcase contains test that can be used in all
678 # stringlike classes. Currently this is str, unicode
679 # UserString and the string module.
680
681 def test_hash(self):
682 # SF bug 1054139: += optimization was not invalidating cached hash value
683 a = self.type2test('DNSSEC')
684 b = self.type2test('')
685 for c in a:
686 b += c
687 hash(b)
688 self.assertEqual(hash(a), hash(b))
689
690 def test_capitalize(self):
691 self.checkequal(' hello ', ' hello ', 'capitalize')
692 self.checkequal('Hello ', 'Hello ','capitalize')
693 self.checkequal('Hello ', 'hello ','capitalize')
694 self.checkequal('Aaaa', 'aaaa', 'capitalize')
695 self.checkequal('Aaaa', 'AaAa', 'capitalize')
696
Ezio Melottiee8d9982011-08-15 09:09:57 +0300697 # check that titlecased chars are lowered correctly
698 # \u1ffc is the titlecased char
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500699 self.checkequal('\u03a9\u0399\u1ff3\u1ff3\u1ff3',
Ezio Melottiee8d9982011-08-15 09:09:57 +0300700 '\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize')
701 # check with cased non-letter chars
702 self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
703 '\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize')
704 self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
705 '\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize')
706 self.checkequal('\u2160\u2171\u2172',
707 '\u2160\u2161\u2162', 'capitalize')
708 self.checkequal('\u2160\u2171\u2172',
709 '\u2170\u2171\u2172', 'capitalize')
710 # check with Ll chars with no upper - nothing changes here
711 self.checkequal('\u019b\u1d00\u1d86\u0221\u1fb7',
712 '\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize')
713
Georg Brandlc7885542007-03-06 19:16:20 +0000714 self.checkraises(TypeError, 'hello', 'capitalize', 42)
715
Georg Brandlc7885542007-03-06 19:16:20 +0000716 def test_additional_split(self):
717 self.checkequal(['this', 'is', 'the', 'split', 'function'],
718 'this is the split function', 'split')
719
720 # by whitespace
721 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
722 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
723 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
724 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
725 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
726 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000727 sys.maxsize-1)
Georg Brandlc7885542007-03-06 19:16:20 +0000728 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
729 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
730 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
731
732 self.checkequal([], ' ', 'split')
733 self.checkequal(['a'], ' a ', 'split')
734 self.checkequal(['a', 'b'], ' a b ', 'split')
735 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
736 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
737 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
738 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
739 aaa = ' a '*20
740 self.checkequal(['a']*20, aaa, 'split')
741 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
742 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
743
744 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000745 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000746
747 def test_additional_rsplit(self):
748 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
749 'this is the rsplit function', 'rsplit')
750
751 # by whitespace
752 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
753 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
754 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
755 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
756 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
757 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000758 sys.maxsize-20)
Georg Brandlc7885542007-03-06 19:16:20 +0000759 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
760 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
761 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
762
763 self.checkequal([], ' ', 'rsplit')
764 self.checkequal(['a'], ' a ', 'rsplit')
765 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
766 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
767 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
768 None, 1)
769 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
770 None, 2)
771 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
772 aaa = ' a '*20
773 self.checkequal(['a']*20, aaa, 'rsplit')
774 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
775 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
776
777 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000778 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000779
780 def test_strip(self):
781 self.checkequal('hello', ' hello ', 'strip')
782 self.checkequal('hello ', ' hello ', 'lstrip')
783 self.checkequal(' hello', ' hello ', 'rstrip')
784 self.checkequal('hello', 'hello', 'strip')
785
786 # strip/lstrip/rstrip with None arg
787 self.checkequal('hello', ' hello ', 'strip', None)
788 self.checkequal('hello ', ' hello ', 'lstrip', None)
789 self.checkequal(' hello', ' hello ', 'rstrip', None)
790 self.checkequal('hello', 'hello', 'strip', None)
791
792 # strip/lstrip/rstrip with str arg
793 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
794 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
795 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
796 self.checkequal('hello', 'hello', 'strip', 'xyz')
797
Georg Brandlc7885542007-03-06 19:16:20 +0000798 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
799 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
800 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
801
802 def test_ljust(self):
803 self.checkequal('abc ', 'abc', 'ljust', 10)
804 self.checkequal('abc ', 'abc', 'ljust', 6)
805 self.checkequal('abc', 'abc', 'ljust', 3)
806 self.checkequal('abc', 'abc', 'ljust', 2)
807 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
808 self.checkraises(TypeError, 'abc', 'ljust')
809
810 def test_rjust(self):
811 self.checkequal(' abc', 'abc', 'rjust', 10)
812 self.checkequal(' abc', 'abc', 'rjust', 6)
813 self.checkequal('abc', 'abc', 'rjust', 3)
814 self.checkequal('abc', 'abc', 'rjust', 2)
815 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
816 self.checkraises(TypeError, 'abc', 'rjust')
817
818 def test_center(self):
819 self.checkequal(' abc ', 'abc', 'center', 10)
820 self.checkequal(' abc ', 'abc', 'center', 6)
821 self.checkequal('abc', 'abc', 'center', 3)
822 self.checkequal('abc', 'abc', 'center', 2)
823 self.checkequal('***abc****', 'abc', 'center', 10, '*')
824 self.checkraises(TypeError, 'abc', 'center')
825
826 def test_swapcase(self):
827 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
828
829 self.checkraises(TypeError, 'hello', 'swapcase', 42)
830
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000831 def test_zfill(self):
832 self.checkequal('123', '123', 'zfill', 2)
833 self.checkequal('123', '123', 'zfill', 3)
834 self.checkequal('0123', '123', 'zfill', 4)
835 self.checkequal('+123', '+123', 'zfill', 3)
836 self.checkequal('+123', '+123', 'zfill', 4)
837 self.checkequal('+0123', '+123', 'zfill', 5)
838 self.checkequal('-123', '-123', 'zfill', 3)
839 self.checkequal('-123', '-123', 'zfill', 4)
840 self.checkequal('-0123', '-123', 'zfill', 5)
841 self.checkequal('000', '', 'zfill', 3)
842 self.checkequal('34', '34', 'zfill', 1)
843 self.checkequal('0034', '34', 'zfill', 4)
844
845 self.checkraises(TypeError, '123', 'zfill')
846
847class MixinStrUnicodeUserStringTest:
848 # additional tests that only work for
849 # stringlike objects, i.e. str, unicode, UserString
850 # (but not the string module)
851
852 def test_islower(self):
853 self.checkequal(False, '', 'islower')
854 self.checkequal(True, 'a', 'islower')
855 self.checkequal(False, 'A', 'islower')
856 self.checkequal(False, '\n', 'islower')
857 self.checkequal(True, 'abc', 'islower')
858 self.checkequal(False, 'aBc', 'islower')
859 self.checkequal(True, 'abc\n', 'islower')
860 self.checkraises(TypeError, 'abc', 'islower', 42)
861
862 def test_isupper(self):
863 self.checkequal(False, '', 'isupper')
864 self.checkequal(False, 'a', 'isupper')
865 self.checkequal(True, 'A', 'isupper')
866 self.checkequal(False, '\n', 'isupper')
867 self.checkequal(True, 'ABC', 'isupper')
868 self.checkequal(False, 'AbC', 'isupper')
869 self.checkequal(True, 'ABC\n', 'isupper')
870 self.checkraises(TypeError, 'abc', 'isupper', 42)
871
872 def test_istitle(self):
873 self.checkequal(False, '', 'istitle')
874 self.checkequal(False, 'a', 'istitle')
875 self.checkequal(True, 'A', 'istitle')
876 self.checkequal(False, '\n', 'istitle')
877 self.checkequal(True, 'A Titlecased Line', 'istitle')
878 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
879 self.checkequal(True, 'A Titlecased, Line', 'istitle')
880 self.checkequal(False, 'Not a capitalized String', 'istitle')
881 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
882 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
883 self.checkequal(False, 'NOT', 'istitle')
884 self.checkraises(TypeError, 'abc', 'istitle', 42)
885
886 def test_isspace(self):
887 self.checkequal(False, '', 'isspace')
888 self.checkequal(False, 'a', 'isspace')
889 self.checkequal(True, ' ', 'isspace')
890 self.checkequal(True, '\t', 'isspace')
891 self.checkequal(True, '\r', 'isspace')
892 self.checkequal(True, '\n', 'isspace')
893 self.checkequal(True, ' \t\r\n', 'isspace')
894 self.checkequal(False, ' \t\r\na', 'isspace')
895 self.checkraises(TypeError, 'abc', 'isspace', 42)
896
897 def test_isalpha(self):
898 self.checkequal(False, '', 'isalpha')
899 self.checkequal(True, 'a', 'isalpha')
900 self.checkequal(True, 'A', 'isalpha')
901 self.checkequal(False, '\n', 'isalpha')
902 self.checkequal(True, 'abc', 'isalpha')
903 self.checkequal(False, 'aBc123', 'isalpha')
904 self.checkequal(False, 'abc\n', 'isalpha')
905 self.checkraises(TypeError, 'abc', 'isalpha', 42)
906
907 def test_isalnum(self):
908 self.checkequal(False, '', 'isalnum')
909 self.checkequal(True, 'a', 'isalnum')
910 self.checkequal(True, 'A', 'isalnum')
911 self.checkequal(False, '\n', 'isalnum')
912 self.checkequal(True, '123abc456', 'isalnum')
913 self.checkequal(True, 'a1b3c', 'isalnum')
914 self.checkequal(False, 'aBc000 ', 'isalnum')
915 self.checkequal(False, 'abc\n', 'isalnum')
916 self.checkraises(TypeError, 'abc', 'isalnum', 42)
917
918 def test_isdigit(self):
919 self.checkequal(False, '', 'isdigit')
920 self.checkequal(False, 'a', 'isdigit')
921 self.checkequal(True, '0', 'isdigit')
922 self.checkequal(True, '0123456789', 'isdigit')
923 self.checkequal(False, '0123456789a', 'isdigit')
924
925 self.checkraises(TypeError, 'abc', 'isdigit', 42)
926
927 def test_title(self):
928 self.checkequal(' Hello ', ' hello ', 'title')
929 self.checkequal('Hello ', 'hello ', 'title')
930 self.checkequal('Hello ', 'Hello ', 'title')
931 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
932 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
933 self.checkequal('Getint', "getInt", 'title')
934 self.checkraises(TypeError, 'hello', 'title', 42)
935
936 def test_splitlines(self):
937 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
938 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
939 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
940 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
941 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
942 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +0100943 self.checkequal(['', 'abc', 'def', 'ghi', ''],
944 "\nabc\ndef\r\nghi\n\r", 'splitlines', False)
945 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
946 "\nabc\ndef\r\nghi\n\r", 'splitlines', True)
947 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r",
948 'splitlines', keepends=False)
949 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'],
950 "\nabc\ndef\r\nghi\n\r", 'splitlines', keepends=True)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000951
952 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
953
954 def test_startswith(self):
955 self.checkequal(True, 'hello', 'startswith', 'he')
956 self.checkequal(True, 'hello', 'startswith', 'hello')
957 self.checkequal(False, 'hello', 'startswith', 'hello world')
958 self.checkequal(True, 'hello', 'startswith', '')
959 self.checkequal(False, 'hello', 'startswith', 'ello')
960 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
961 self.checkequal(True, 'hello', 'startswith', 'o', 4)
962 self.checkequal(False, 'hello', 'startswith', 'o', 5)
963 self.checkequal(True, 'hello', 'startswith', '', 5)
964 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
965 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
966 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
967 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
968
969 # test negative indices
970 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
971 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
972 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
973 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
974 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
975 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
976 self.checkequal(False, 'hello', 'startswith', 'o', -2)
977 self.checkequal(True, 'hello', 'startswith', 'o', -1)
978 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
979 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
980
981 self.checkraises(TypeError, 'hello', 'startswith')
982 self.checkraises(TypeError, 'hello', 'startswith', 42)
983
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984 # test tuple arguments
985 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
986 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
987 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
988 self.checkequal(False, 'hello', 'startswith', ())
989 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
990 'rld', 'lowo'), 3)
991 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
992 'rld'), 3)
993 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
994 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
995 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
996
997 self.checkraises(TypeError, 'hello', 'startswith', (42,))
998
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000999 def test_endswith(self):
1000 self.checkequal(True, 'hello', 'endswith', 'lo')
1001 self.checkequal(False, 'hello', 'endswith', 'he')
1002 self.checkequal(True, 'hello', 'endswith', '')
1003 self.checkequal(False, 'hello', 'endswith', 'hello world')
1004 self.checkequal(False, 'helloworld', 'endswith', 'worl')
1005 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
1006 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
1007 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
1008 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
1009 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
1010 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
1011 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
1012 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
1013 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
1014
1015 # test negative indices
1016 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
1017 self.checkequal(False, 'hello', 'endswith', 'he', -2)
1018 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
1019 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
1020 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
1021 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
1022 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
1023 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
1024 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
1025 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
1026 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
1027 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
1028 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
1029
1030 self.checkraises(TypeError, 'hello', 'endswith')
1031 self.checkraises(TypeError, 'hello', 'endswith', 42)
1032
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001033 # test tuple arguments
1034 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
1035 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
1036 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
1037 self.checkequal(False, 'hello', 'endswith', ())
1038 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
1039 'rld', 'lowo'), 3)
1040 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
1041 'rld'), 3, -1)
1042 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
1043 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
1044 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
1045
1046 self.checkraises(TypeError, 'hello', 'endswith', (42,))
1047
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001048 def test___contains__(self):
Ezio Melottib19f43d2010-01-24 20:59:24 +00001049 self.checkequal(True, '', '__contains__', '')
1050 self.checkequal(True, 'abc', '__contains__', '')
1051 self.checkequal(False, 'abc', '__contains__', '\0')
1052 self.checkequal(True, '\0abc', '__contains__', '\0')
1053 self.checkequal(True, 'abc\0', '__contains__', '\0')
1054 self.checkequal(True, '\0abc', '__contains__', 'a')
1055 self.checkequal(True, 'asdf', '__contains__', 'asdf')
1056 self.checkequal(False, 'asd', '__contains__', 'asdf')
1057 self.checkequal(False, '', '__contains__', 'asdf')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001058
1059 def test_subscript(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001060 self.checkequal('a', 'abc', '__getitem__', 0)
1061 self.checkequal('c', 'abc', '__getitem__', -1)
1062 self.checkequal('a', 'abc', '__getitem__', 0)
1063 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
1064 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
1065 self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
1066 self.checkequal('', 'abc', '__getitem__', slice(0, 0))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001067
1068 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
1069
1070 def test_slice(self):
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001071 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
1072 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
1073 self.checkequal('ab', 'abc', '__getitem__', slice(0, 2))
1074 self.checkequal('bc', 'abc', '__getitem__', slice(1, 3))
1075 self.checkequal('b', 'abc', '__getitem__', slice(1, 2))
1076 self.checkequal('', 'abc', '__getitem__', slice(2, 2))
1077 self.checkequal('', 'abc', '__getitem__', slice(1000, 1000))
1078 self.checkequal('', 'abc', '__getitem__', slice(2000, 1000))
1079 self.checkequal('', 'abc', '__getitem__', slice(2, 1))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001080
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001081 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001082
Thomas Woutersed03b412007-08-28 21:37:11 +00001083 def test_extended_getslice(self):
1084 # Test extended slicing by comparing with list slicing.
1085 s = string.ascii_letters + string.digits
1086 indices = (0, None, 1, 3, 41, -1, -2, -37)
1087 for start in indices:
1088 for stop in indices:
1089 # Skip step 0 (invalid)
1090 for step in indices[1:]:
1091 L = list(s)[start:stop:step]
1092 self.checkequal("".join(L), s, '__getitem__',
1093 slice(start, stop, step))
1094
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001095 def test_mul(self):
1096 self.checkequal('', 'abc', '__mul__', -1)
1097 self.checkequal('', 'abc', '__mul__', 0)
1098 self.checkequal('abc', 'abc', '__mul__', 1)
1099 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
1100 self.checkraises(TypeError, 'abc', '__mul__')
1101 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102 # XXX: on a 64-bit system, this doesn't raise an overflow error,
1103 # but either raises a MemoryError, or succeeds (if you have 54TiB)
1104 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001105
1106 def test_join(self):
1107 # join now works with any sequence type
1108 # moved here, because the argument order is
1109 # different in string.join (see the test in
1110 # test.test_string.StringTest.test_join)
1111 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
1112 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001113 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
1114 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001115 self.checkequal('w x y z', ' ', 'join', Sequence())
1116 self.checkequal('abc', 'a', 'join', ('abc',))
1117 self.checkequal('z', 'a', 'join', UserList(['z']))
Walter Dörwald67e83882007-05-05 12:26:27 +00001118 self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c'])
Guido van Rossum98297ee2007-11-06 21:34:58 +00001119 self.assertRaises(TypeError, '.'.join, ['a', 'b', 3])
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001120 for i in [5, 25, 125]:
1121 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1122 ['a' * i] * i)
1123 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1124 ('a' * i,) * i)
1125
Guido van Rossum98297ee2007-11-06 21:34:58 +00001126 #self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1())
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001127 self.checkequal('a b c', ' ', 'join', BadSeq2())
1128
1129 self.checkraises(TypeError, ' ', 'join')
1130 self.checkraises(TypeError, ' ', 'join', 7)
Guido van Rossumf1044292007-09-27 18:01:22 +00001131 self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()])
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001132 try:
1133 def f():
1134 yield 4 + ""
1135 self.fixtype(' ').join(f())
Guido van Rossumb940e112007-01-10 16:19:56 +00001136 except TypeError as e:
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001137 if '+' not in str(e):
1138 self.fail('join() ate exception message')
1139 else:
1140 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001141
1142 def test_formatting(self):
1143 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1144 self.checkequal('+10+', '+%d+', '__mod__', 10)
1145 self.checkequal('a', "%c", '__mod__', "a")
1146 self.checkequal('a', "%c", '__mod__', "a")
1147 self.checkequal('"', "%c", '__mod__', 34)
1148 self.checkequal('$', "%c", '__mod__', 36)
1149 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001150 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001151
1152 for ordinal in (-100, 0x200000):
1153 # unicode raises ValueError, str raises OverflowError
1154 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1155
Christian Heimesa612dc02008-02-24 13:08:18 +00001156 longvalue = sys.maxsize + 10
1157 slongvalue = str(longvalue)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001158 self.checkequal(' 42', '%3ld', '__mod__', 42)
Christian Heimesa612dc02008-02-24 13:08:18 +00001159 self.checkequal('42', '%d', '__mod__', 42.0)
1160 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1161 self.checkcall('%d', '__mod__', float(longvalue))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001162 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001163 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001164
1165 self.checkraises(TypeError, 'abc', '__mod__')
1166 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1167 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1168 self.checkraises(TypeError, '%c', '__mod__', (None,))
1169 self.checkraises(ValueError, '%(foo', '__mod__', {})
1170 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
Christian Heimesa612dc02008-02-24 13:08:18 +00001171 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
Mark Dickinson5c2db372009-12-05 20:28:34 +00001172 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int conversion provided
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001173
1174 # argument names with properly nested brackets are supported
1175 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1176
1177 # 100 is a magic number in PyUnicode_Format, this forces a resize
1178 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1179
1180 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1181 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1182 self.checkraises(ValueError, '%10', '__mod__', (42,))
1183
Mark Dickinson99e2e552012-05-07 11:20:50 +01001184 # Outrageously large width or precision should raise ValueError.
1185 self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2))
1186 self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2))
Serhiy Storchaka441d30f2013-01-19 12:26:26 +02001187 self.checkraises(OverflowError, '%*s', '__mod__',
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001188 (sys.maxsize + 1, ''))
Serhiy Storchaka441d30f2013-01-19 12:26:26 +02001189 self.checkraises(OverflowError, '%.*f', '__mod__',
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001190 (sys.maxsize + 1, 1. / 7))
Serhiy Storchaka441d30f2013-01-19 12:26:26 +02001191
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -04001192 class X(object): pass
1193 self.checkraises(TypeError, 'abc', '__mod__', X())
1194
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001195 @support.cpython_only
1196 def test_formatting_c_limits(self):
1197 from _testcapi import PY_SSIZE_T_MAX, INT_MAX, UINT_MAX
1198 SIZE_MAX = (1 << (PY_SSIZE_T_MAX.bit_length() + 1)) - 1
1199 self.checkraises(OverflowError, '%*s', '__mod__',
1200 (PY_SSIZE_T_MAX + 1, ''))
1201 self.checkraises(OverflowError, '%.*f', '__mod__',
1202 (INT_MAX + 1, 1. / 7))
1203 # Issue 15989
1204 self.checkraises(OverflowError, '%*s', '__mod__',
1205 (SIZE_MAX + 1, ''))
1206 self.checkraises(OverflowError, '%.*f', '__mod__',
1207 (UINT_MAX + 1, 1. / 7))
1208
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001209 def test_floatformatting(self):
1210 # float formatting
Guido van Rossum805365e2007-05-07 22:24:25 +00001211 for prec in range(100):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001212 format = '%%.%if' % prec
1213 value = 0.01
Guido van Rossum805365e2007-05-07 22:24:25 +00001214 for x in range(60):
Florent Xiclunaa87b3832010-09-13 02:28:18 +00001215 value = value * 3.14159265359 / 3.0 * 10.0
Mark Dickinsonf489caf2009-05-01 11:42:00 +00001216 self.checkcall(format, "__mod__", value)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001217
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 def test_inplace_rewrites(self):
1219 # Check that strings don't copy and modify cached single-character strings
1220 self.checkequal('a', 'A', 'lower')
1221 self.checkequal(True, 'A', 'isupper')
1222 self.checkequal('A', 'a', 'upper')
1223 self.checkequal(True, 'a', 'islower')
1224
1225 self.checkequal('a', 'A', 'replace', 'A', 'a')
1226 self.checkequal(True, 'A', 'isupper')
1227
1228 self.checkequal('A', 'a', 'capitalize')
1229 self.checkequal(True, 'a', 'islower')
1230
1231 self.checkequal('A', 'a', 'swapcase')
1232 self.checkequal(True, 'a', 'islower')
1233
1234 self.checkequal('A', 'a', 'title')
1235 self.checkequal(True, 'a', 'islower')
1236
1237 def test_partition(self):
1238
1239 self.checkequal(('this is the par', 'ti', 'tion method'),
1240 'this is the partition method', 'partition', 'ti')
1241
1242 # from raymond's original specification
1243 S = 'http://www.python.org'
1244 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1245 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1246 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1247 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1248
1249 self.checkraises(ValueError, S, 'partition', '')
1250 self.checkraises(TypeError, S, 'partition', None)
1251
1252 def test_rpartition(self):
1253
1254 self.checkequal(('this is the rparti', 'ti', 'on method'),
1255 'this is the rpartition method', 'rpartition', 'ti')
1256
1257 # from raymond's original specification
1258 S = 'http://www.python.org'
1259 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001260 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1262 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1263
1264 self.checkraises(ValueError, S, 'rpartition', '')
1265 self.checkraises(TypeError, S, 'rpartition', None)
1266
Jesus Ceaac451502011-04-20 17:09:23 +02001267 def test_none_arguments(self):
1268 # issue 11828
1269 s = 'hello'
1270 self.checkequal(2, s, 'find', 'l', None)
1271 self.checkequal(3, s, 'find', 'l', -2, None)
1272 self.checkequal(2, s, 'find', 'l', None, -2)
1273 self.checkequal(0, s, 'find', 'h', None, None)
1274
1275 self.checkequal(3, s, 'rfind', 'l', None)
1276 self.checkequal(3, s, 'rfind', 'l', -2, None)
1277 self.checkequal(2, s, 'rfind', 'l', None, -2)
1278 self.checkequal(0, s, 'rfind', 'h', None, None)
1279
1280 self.checkequal(2, s, 'index', 'l', None)
1281 self.checkequal(3, s, 'index', 'l', -2, None)
1282 self.checkequal(2, s, 'index', 'l', None, -2)
1283 self.checkequal(0, s, 'index', 'h', None, None)
1284
1285 self.checkequal(3, s, 'rindex', 'l', None)
1286 self.checkequal(3, s, 'rindex', 'l', -2, None)
1287 self.checkequal(2, s, 'rindex', 'l', None, -2)
1288 self.checkequal(0, s, 'rindex', 'h', None, None)
1289
1290 self.checkequal(2, s, 'count', 'l', None)
1291 self.checkequal(1, s, 'count', 'l', -2, None)
1292 self.checkequal(1, s, 'count', 'l', None, -2)
1293 self.checkequal(0, s, 'count', 'x', None, None)
1294
1295 self.checkequal(True, s, 'endswith', 'o', None)
1296 self.checkequal(True, s, 'endswith', 'lo', -2, None)
1297 self.checkequal(True, s, 'endswith', 'l', None, -2)
1298 self.checkequal(False, s, 'endswith', 'x', None, None)
1299
1300 self.checkequal(True, s, 'startswith', 'h', None)
1301 self.checkequal(True, s, 'startswith', 'l', -2, None)
1302 self.checkequal(True, s, 'startswith', 'h', None, -2)
1303 self.checkequal(False, s, 'startswith', 'x', None, None)
1304
1305 def test_find_etc_raise_correct_error_messages(self):
1306 # issue 11828
1307 s = 'hello'
1308 x = 'x'
Ezio Melottiaf928422011-04-20 21:56:21 +03001309 self.assertRaisesRegex(TypeError, r'^find\(', s.find,
Jesus Ceaac451502011-04-20 17:09:23 +02001310 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001311 self.assertRaisesRegex(TypeError, r'^rfind\(', s.rfind,
Jesus Ceaac451502011-04-20 17:09:23 +02001312 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001313 self.assertRaisesRegex(TypeError, r'^index\(', s.index,
Jesus Ceaac451502011-04-20 17:09:23 +02001314 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001315 self.assertRaisesRegex(TypeError, r'^rindex\(', s.rindex,
Jesus Ceaac451502011-04-20 17:09:23 +02001316 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001317 self.assertRaisesRegex(TypeError, r'^count\(', s.count,
Jesus Ceaac451502011-04-20 17:09:23 +02001318 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001319 self.assertRaisesRegex(TypeError, r'^startswith\(', s.startswith,
Jesus Ceaac451502011-04-20 17:09:23 +02001320 x, None, None, None)
Ezio Melottiaf928422011-04-20 21:56:21 +03001321 self.assertRaisesRegex(TypeError, r'^endswith\(', s.endswith,
Jesus Ceaac451502011-04-20 17:09:23 +02001322 x, None, None, None)
1323
Victor Stinnerb3f55012012-08-02 23:05:01 +02001324 # issue #15534
1325 self.checkequal(10, "...\u043c......<", "find", "<")
1326
Walter Dörwald57d88e52004-08-26 16:53:04 +00001327
Walter Dörwald57d88e52004-08-26 16:53:04 +00001328class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001329 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001330
1331 def test_bug1001011(self):
1332 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001333 # involving a subclass.
1334 # Make sure that it is of the appropriate type.
1335 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001336 t = self.type2test
1337 class subclass(t):
1338 pass
1339 s1 = subclass("abcd")
1340 s2 = t().join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001341 self.assertIsNot(s1, s2)
1342 self.assertIs(type(s2), t)
Tim Peters108f1372004-08-27 05:36:07 +00001343
1344 s1 = t("abcd")
1345 s2 = t().join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001346 self.assertIs(s1, s2)
Tim Peters108f1372004-08-27 05:36:07 +00001347
1348 # Should also test mixed-type join.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001349 if t is str:
Tim Peters108f1372004-08-27 05:36:07 +00001350 s1 = subclass("abcd")
1351 s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001352 self.assertIsNot(s1, s2)
1353 self.assertIs(type(s2), t)
Tim Peters108f1372004-08-27 05:36:07 +00001354
1355 s1 = t("abcd")
1356 s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001357 self.assertIs(s1, s2)
Tim Peters108f1372004-08-27 05:36:07 +00001358
Guido van Rossum98297ee2007-11-06 21:34:58 +00001359## elif t is str8:
1360## s1 = subclass("abcd")
1361## s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001362## self.assertIsNot(s1, s2)
1363## self.assertIs(type(s2), str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001364
Guido van Rossum98297ee2007-11-06 21:34:58 +00001365## s1 = t("abcd")
1366## s2 = "".join([s1])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001367## self.assertIsNot(s1, s2)
1368## self.assertIs(type(s2), str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001369
1370 else:
1371 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)