blob: 2a58e582d4a29d38b21078f61859ff908db24238 [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
Georg Brandlc7885542007-03-06 19:16:20 +000022class BaseTest(unittest.TestCase):
23 # These tests are for buffers of values (bytes) and not
24 # specific to character interpretation, used for bytes objects
25 # and various string implementations
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
Walter Dörwald0fd583c2003-02-21 12:53:50 +000031 # All tests pass their arguments to the testing methods
32 # as str objects. fixtesttype() can be used to propagate
33 # these arguments to the appropriate type
34 def fixtype(self, obj):
35 if isinstance(obj, str):
36 return self.__class__.type2test(obj)
37 elif isinstance(obj, list):
38 return [self.fixtype(x) for x in obj]
39 elif isinstance(obj, tuple):
40 return tuple([self.fixtype(x) for x in obj])
41 elif isinstance(obj, dict):
42 return dict([
43 (self.fixtype(key), self.fixtype(value))
Guido van Rossumcc2b0162007-02-11 06:12:03 +000044 for (key, value) in obj.items()
Walter Dörwald0fd583c2003-02-21 12:53:50 +000045 ])
46 else:
47 return obj
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000048
Guido van Rossum09549f42007-08-27 20:40:10 +000049 # check that obj.method(*args) returns result
50 def checkequal(self, result, obj, methodname, *args):
Walter Dörwald0fd583c2003-02-21 12:53:50 +000051 result = self.fixtype(result)
Guido van Rossum09549f42007-08-27 20:40:10 +000052 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000053 args = self.fixtype(args)
Guido van Rossum09549f42007-08-27 20:40:10 +000054 realresult = getattr(obj, methodname)(*args)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000055 self.assertEqual(
56 result,
57 realresult
58 )
59 # if the original is returned make sure that
60 # this doesn't happen with subclasses
Guido van Rossum09549f42007-08-27 20:40:10 +000061 if obj is realresult:
62 try:
63 class subtype(self.__class__.type2test):
64 pass
65 except TypeError:
66 pass # Skip this if we can't subclass
67 else:
68 obj = subtype(obj)
69 realresult = getattr(obj, methodname)(*args)
70 self.assert_(obj is not realresult)
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000071
Guido van Rossum09549f42007-08-27 20:40:10 +000072 # check that obj.method(*args) raises exc
73 def checkraises(self, exc, obj, methodname, *args):
74 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000075 args = self.fixtype(args)
76 self.assertRaises(
77 exc,
Guido van Rossum09549f42007-08-27 20:40:10 +000078 getattr(obj, methodname),
Walter Dörwald0fd583c2003-02-21 12:53:50 +000079 *args
80 )
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000081
Guido van Rossum09549f42007-08-27 20:40:10 +000082 # call obj.method(*args) without any checks
83 def checkcall(self, obj, methodname, *args):
84 obj = self.fixtype(obj)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000085 args = self.fixtype(args)
Guido van Rossum09549f42007-08-27 20:40:10 +000086 getattr(obj, methodname)(*args)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000087
Walter Dörwald0fd583c2003-02-21 12:53:50 +000088 def test_count(self):
89 self.checkequal(3, 'aaa', 'count', 'a')
90 self.checkequal(0, 'aaa', 'count', 'b')
91 self.checkequal(3, 'aaa', 'count', 'a')
92 self.checkequal(0, 'aaa', 'count', 'b')
93 self.checkequal(3, 'aaa', 'count', 'a')
94 self.checkequal(0, 'aaa', 'count', 'b')
95 self.checkequal(0, 'aaa', 'count', 'b')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000096 self.checkequal(2, 'aaa', 'count', 'a', 1)
97 self.checkequal(0, 'aaa', 'count', 'a', 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000098 self.checkequal(1, 'aaa', 'count', 'a', -1)
99 self.checkequal(3, 'aaa', 'count', 'a', -10)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
101 self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000102 self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
103 self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000104 self.checkequal(3, 'aaa', 'count', '', 1)
105 self.checkequal(1, 'aaa', 'count', '', 3)
106 self.checkequal(0, 'aaa', 'count', '', 10)
107 self.checkequal(2, 'aaa', 'count', '', -1)
108 self.checkequal(4, 'aaa', 'count', '', -10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000109
Amaury Forgeot d'Arcf2e93682008-09-26 22:48:41 +0000110 self.checkequal(1, '', 'count', '')
111 self.checkequal(0, '', 'count', '', 1, 1)
112 self.checkequal(0, '', 'count', '', sys.maxsize, 0)
113
114 self.checkequal(0, '', 'count', 'xx')
115 self.checkequal(0, '', 'count', 'xx', 1, 1)
116 self.checkequal(0, '', 'count', 'xx', sys.maxsize, 0)
117
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000118 self.checkraises(TypeError, 'hello', 'count')
119 self.checkraises(TypeError, 'hello', 'count', 42)
120
Raymond Hettinger57e74472005-02-20 09:54:53 +0000121 # For a variety of combinations,
122 # verify that str.count() matches an equivalent function
123 # replacing all occurrences and then differencing the string lengths
124 charset = ['', 'a', 'b']
125 digits = 7
126 base = len(charset)
127 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000128 for i in range(base ** digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000129 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000130 for j in range(digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000131 i, m = divmod(i, base)
132 entry.append(charset[m])
133 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000134 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger57e74472005-02-20 09:54:53 +0000135 for i in teststrings:
Raymond Hettinger57e74472005-02-20 09:54:53 +0000136 n = len(i)
137 for j in teststrings:
138 r1 = i.count(j)
139 if j:
Guido van Rossum09549f42007-08-27 20:40:10 +0000140 r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))),
141 len(j))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000142 else:
143 r2, rem = len(i)+1, 0
144 if rem or r1 != r2:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
146 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000147
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000148 def test_find(self):
149 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
150 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
151 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
152
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000153 self.checkequal(0, 'abc', 'find', '', 0)
154 self.checkequal(3, 'abc', 'find', '', 3)
155 self.checkequal(-1, 'abc', 'find', '', 4)
156
Christian Heimes9cd17752007-11-18 19:35:23 +0000157 # to check the ability to pass None as defaults
158 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
159 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
160 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
161 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
162 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
163
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000164 self.checkraises(TypeError, 'hello', 'find')
165 self.checkraises(TypeError, 'hello', 'find', 42)
166
Amaury Forgeot d'Arcf2e93682008-09-26 22:48:41 +0000167 self.checkequal(0, '', 'find', '')
168 self.checkequal(-1, '', 'find', '', 1, 1)
169 self.checkequal(-1, '', 'find', '', sys.maxsize, 0)
170
171 self.checkequal(-1, '', 'find', 'xx')
172 self.checkequal(-1, '', 'find', 'xx', 1, 1)
173 self.checkequal(-1, '', 'find', 'xx', sys.maxsize, 0)
174
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000175 # For a variety of combinations,
176 # verify that str.find() matches __contains__
177 # and that the found substring is really at that location
178 charset = ['', 'a', 'b', 'c']
179 digits = 5
180 base = len(charset)
181 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000182 for i in range(base ** digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000183 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000184 for j in range(digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000185 i, m = divmod(i, base)
186 entry.append(charset[m])
187 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000188 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000189 for i in teststrings:
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000190 for j in teststrings:
191 loc = i.find(j)
192 r1 = (loc != -1)
193 r2 = j in i
194 if r1 != r2:
195 self.assertEqual(r1, r2)
196 if loc != -1:
197 self.assertEqual(i[loc:loc+len(j)], j)
198
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000199 def test_rfind(self):
200 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
201 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
202 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
203 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
204
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000205 self.checkequal(3, 'abc', 'rfind', '', 0)
206 self.checkequal(3, 'abc', 'rfind', '', 3)
207 self.checkequal(-1, 'abc', 'rfind', '', 4)
208
Christian Heimes9cd17752007-11-18 19:35:23 +0000209 # to check the ability to pass None as defaults
210 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
211 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
212 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
213 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
214 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
215
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000216 self.checkraises(TypeError, 'hello', 'rfind')
217 self.checkraises(TypeError, 'hello', 'rfind', 42)
218
219 def test_index(self):
220 self.checkequal(0, 'abcdefghiabc', 'index', '')
221 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
222 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
223 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
224
225 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
226 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
227 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
228 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
229
Christian Heimes9cd17752007-11-18 19:35:23 +0000230 # to check the ability to pass None as defaults
231 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
232 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
233 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
234 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
235 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
236
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000237 self.checkraises(TypeError, 'hello', 'index')
238 self.checkraises(TypeError, 'hello', 'index', 42)
239
240 def test_rindex(self):
241 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
242 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
243 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
244 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
245
246 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
247 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
248 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
249 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
250 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
251
Christian Heimes9cd17752007-11-18 19:35:23 +0000252 # to check the ability to pass None as defaults
253 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
254 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
255 self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
256 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
257 self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
258
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000259 self.checkraises(TypeError, 'hello', 'rindex')
260 self.checkraises(TypeError, 'hello', 'rindex', 42)
261
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000262 def test_lower(self):
263 self.checkequal('hello', 'HeLLo', 'lower')
264 self.checkequal('hello', 'hello', 'lower')
265 self.checkraises(TypeError, 'hello', 'lower', 42)
266
267 def test_upper(self):
268 self.checkequal('HELLO', 'HeLLo', 'upper')
269 self.checkequal('HELLO', 'HELLO', 'upper')
270 self.checkraises(TypeError, 'hello', 'upper', 42)
271
272 def test_expandtabs(self):
273 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
274 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
275 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
276 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
277 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
278 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
279 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
280 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
281
282 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
283 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000284 if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000285 self.checkraises(OverflowError,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000286 '\ta\n\tb', 'expandtabs', sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000287
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000288 def test_split(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000289 # by a char
290 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000291 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000292 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
293 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
294 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
295 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000296 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000297 sys.maxsize-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000298 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
299 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
300 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
302 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000303 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
304
Thomas Wouters477c8d52006-05-27 19:21:47 +0000305 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
306 self.checkequal(['a']*15 +['a|a|a|a|a'],
307 ('a|'*20)[:-1], 'split', '|', 15)
308
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000309 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000310 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000311 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
312 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
313 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
314 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000315 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000316 sys.maxsize-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000317 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
318 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000319 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
321 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
322 'split', 'test')
323 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
324 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
325 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
326 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
327 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
328 self.checkequal([''], '', 'split', 'aaa')
329 self.checkequal(['aa'], 'aa', 'split', 'aaa')
330 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
331 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
332
333 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
334 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
335 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
336 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000337
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000338 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000339 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
340
Thomas Wouters477c8d52006-05-27 19:21:47 +0000341 # null case
342 self.checkraises(ValueError, 'hello', 'split', '')
343 self.checkraises(ValueError, 'hello', 'split', '', 0)
344
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000345 def test_rsplit(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000346 # by a char
347 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
348 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
349 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
350 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
351 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000352 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000353 sys.maxsize-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000354 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
355 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
356 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000357 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
358 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
359
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000360 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
361
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
363 self.checkequal(['a|a|a|a|a']+['a']*15,
364 ('a|'*20)[:-1], 'rsplit', '|', 15)
365
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000366 # by string
367 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
368 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
369 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
370 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
371 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000372 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000373 sys.maxsize-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000374 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
375 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
376 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
378 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
379 'rsplit', 'test')
380 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
381 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
382 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
383 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
384 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
385 self.checkequal([''], '', 'rsplit', 'aaa')
386 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
387 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
388 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
389
390 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
391 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
392 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
393 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000394
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000395 # argument type
396 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000397
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398 # null case
399 self.checkraises(ValueError, 'hello', 'rsplit', '')
400 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
401
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000402 def test_replace(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000403 EQ = self.checkequal
404
405 # Operations on the empty string
406 EQ("", "", "replace", "", "")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000407 EQ("A", "", "replace", "", "A")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408 EQ("", "", "replace", "A", "")
409 EQ("", "", "replace", "A", "A")
410 EQ("", "", "replace", "", "", 100)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000411 EQ("", "", "replace", "", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000412
413 # interleave (from=="", 'to' gets inserted everywhere)
414 EQ("A", "A", "replace", "", "")
415 EQ("*A*", "A", "replace", "", "*")
416 EQ("*1A*1", "A", "replace", "", "*1")
417 EQ("*-#A*-#", "A", "replace", "", "*-#")
418 EQ("*-A*-A*-", "AA", "replace", "", "*-")
419 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000420 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000421 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
422 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
423 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
424 EQ("*-AA", "AA", "replace", "", "*-", 1)
425 EQ("AA", "AA", "replace", "", "*-", 0)
426
427 # single character deletion (from=="A", to=="")
428 EQ("", "A", "replace", "A", "")
429 EQ("", "AAA", "replace", "A", "")
430 EQ("", "AAA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000431 EQ("", "AAA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000432 EQ("", "AAA", "replace", "A", "", 4)
433 EQ("", "AAA", "replace", "A", "", 3)
434 EQ("A", "AAA", "replace", "A", "", 2)
435 EQ("AA", "AAA", "replace", "A", "", 1)
436 EQ("AAA", "AAA", "replace", "A", "", 0)
437 EQ("", "AAAAAAAAAA", "replace", "A", "")
438 EQ("BCD", "ABACADA", "replace", "A", "")
439 EQ("BCD", "ABACADA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000440 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441 EQ("BCD", "ABACADA", "replace", "A", "", 5)
442 EQ("BCD", "ABACADA", "replace", "A", "", 4)
443 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
444 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
445 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
446 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
447 EQ("BCD", "ABCAD", "replace", "A", "")
448 EQ("BCD", "ABCADAA", "replace", "A", "")
449 EQ("BCD", "BCD", "replace", "A", "")
450 EQ("*************", "*************", "replace", "A", "")
451 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
452
453 # substring deletion (from=="the", to=="")
454 EQ("", "the", "replace", "the", "")
455 EQ("ater", "theater", "replace", "the", "")
456 EQ("", "thethe", "replace", "the", "")
457 EQ("", "thethethethe", "replace", "the", "")
458 EQ("aaaa", "theatheatheathea", "replace", "the", "")
459 EQ("that", "that", "replace", "the", "")
460 EQ("thaet", "thaet", "replace", "the", "")
461 EQ("here and re", "here and there", "replace", "the", "")
462 EQ("here and re and re", "here and there and there",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000463 "replace", "the", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000464 EQ("here and re and re", "here and there and there",
465 "replace", "the", "", -1)
466 EQ("here and re and re", "here and there and there",
467 "replace", "the", "", 3)
468 EQ("here and re and re", "here and there and there",
469 "replace", "the", "", 2)
470 EQ("here and re and there", "here and there and there",
471 "replace", "the", "", 1)
472 EQ("here and there and there", "here and there and there",
473 "replace", "the", "", 0)
474 EQ("here and re and re", "here and there and there", "replace", "the", "")
475
476 EQ("abc", "abc", "replace", "the", "")
477 EQ("abcdefg", "abcdefg", "replace", "the", "")
478
479 # substring deletion (from=="bob", to=="")
480 EQ("bob", "bbobob", "replace", "bob", "")
481 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
482 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
483 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
484
485 # single character replace in place (len(from)==len(to)==1)
486 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
487 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000488 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000489 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
490 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
491 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
492 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
493 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
494
495 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
496 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
497 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
498 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
499 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
500
501 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
502
503 # substring replace in place (len(from)==len(to) > 1)
504 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000505 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000506 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
507 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
508 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
509 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
510 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
511 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
512 EQ("cobob", "bobob", "replace", "bob", "cob")
513 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
514 EQ("bobob", "bobob", "replace", "bot", "bot")
515
516 # replace single character (len(from)==1, len(to)>1)
517 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
518 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000519 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000520 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
521 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
522 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
523 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
524
525 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
526
527 # replace substring (len(from)>1, len(to)!=len(from))
528 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
529 "replace", "spam", "ham")
530 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000531 "replace", "spam", "ham", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
533 "replace", "spam", "ham", -1)
534 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
535 "replace", "spam", "ham", 4)
536 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
537 "replace", "spam", "ham", 3)
538 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
539 "replace", "spam", "ham", 2)
540 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
541 "replace", "spam", "ham", 1)
542 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
543 "replace", "spam", "ham", 0)
544
545 EQ("bobob", "bobobob", "replace", "bobob", "bob")
546 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
547 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
548
Guido van Rossum39478e82007-08-27 17:23:59 +0000549 # XXX Commented out. Is there any reason to support buffer objects
550 # as arguments for str.replace()? GvR
Guido van Rossum254348e2007-11-21 19:29:53 +0000551## ba = bytearray('a')
552## bb = bytearray('b')
Guido van Rossum39478e82007-08-27 17:23:59 +0000553## EQ("bbc", "abc", "replace", ba, bb)
554## EQ("aac", "abc", "replace", bb, ba)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000555
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000557 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
558 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
559 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
560 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
561 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
562 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
563 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
564 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
565 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
566 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
567 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
568 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
569 self.checkequal('', '', 'replace', '', '')
570 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
571 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
572 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
573 # MemoryError due to empty result (platform malloc issue when requesting
574 # 0 bytes).
575 self.checkequal('', '123', 'replace', '123', '')
576 self.checkequal('', '123123', 'replace', '123', '')
577 self.checkequal('x', '123x123', 'replace', '123', '')
578
579 self.checkraises(TypeError, 'hello', 'replace')
580 self.checkraises(TypeError, 'hello', 'replace', 42)
581 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
582 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
583
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584 def test_replace_overflow(self):
585 # Check for overflow checking on 32 bit machines
Christian Heimesa37d4c62007-12-04 23:02:19 +0000586 if sys.maxsize != 2147483647 or struct.calcsize("P") > 4:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 return
588 A2_16 = "A" * (2**16)
589 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
590 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
591 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
592
Georg Brandlc7885542007-03-06 19:16:20 +0000593
594
595class CommonTest(BaseTest):
596 # This testcase contains test that can be used in all
597 # stringlike classes. Currently this is str, unicode
598 # UserString and the string module.
599
600 def test_hash(self):
601 # SF bug 1054139: += optimization was not invalidating cached hash value
602 a = self.type2test('DNSSEC')
603 b = self.type2test('')
604 for c in a:
605 b += c
606 hash(b)
607 self.assertEqual(hash(a), hash(b))
608
609 def test_capitalize(self):
610 self.checkequal(' hello ', ' hello ', 'capitalize')
611 self.checkequal('Hello ', 'Hello ','capitalize')
612 self.checkequal('Hello ', 'hello ','capitalize')
613 self.checkequal('Aaaa', 'aaaa', 'capitalize')
614 self.checkequal('Aaaa', 'AaAa', 'capitalize')
615
616 self.checkraises(TypeError, 'hello', 'capitalize', 42)
617
618 def test_lower(self):
619 self.checkequal('hello', 'HeLLo', 'lower')
620 self.checkequal('hello', 'hello', 'lower')
621 self.checkraises(TypeError, 'hello', 'lower', 42)
622
623 def test_upper(self):
624 self.checkequal('HELLO', 'HeLLo', 'upper')
625 self.checkequal('HELLO', 'HELLO', 'upper')
626 self.checkraises(TypeError, 'hello', 'upper', 42)
627
628 def test_expandtabs(self):
629 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
630 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
631 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
632 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
633 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
634 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
635 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
636
637 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
638
639 def test_additional_split(self):
640 self.checkequal(['this', 'is', 'the', 'split', 'function'],
641 'this is the split function', 'split')
642
643 # by whitespace
644 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
645 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
646 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
647 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
648 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
649 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000650 sys.maxsize-1)
Georg Brandlc7885542007-03-06 19:16:20 +0000651 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
652 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
653 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
654
655 self.checkequal([], ' ', 'split')
656 self.checkequal(['a'], ' a ', 'split')
657 self.checkequal(['a', 'b'], ' a b ', 'split')
658 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
659 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
660 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
661 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
662 aaa = ' a '*20
663 self.checkequal(['a']*20, aaa, 'split')
664 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
665 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
666
667 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000668 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000669
670 def test_additional_rsplit(self):
671 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
672 'this is the rsplit function', 'rsplit')
673
674 # by whitespace
675 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
676 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
677 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
678 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
679 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
680 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000681 sys.maxsize-20)
Georg Brandlc7885542007-03-06 19:16:20 +0000682 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
683 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
684 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
685
686 self.checkequal([], ' ', 'rsplit')
687 self.checkequal(['a'], ' a ', 'rsplit')
688 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
689 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
690 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
691 None, 1)
692 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
693 None, 2)
694 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
695 aaa = ' a '*20
696 self.checkequal(['a']*20, aaa, 'rsplit')
697 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
698 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
699
700 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000701 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000702
703 def test_strip(self):
704 self.checkequal('hello', ' hello ', 'strip')
705 self.checkequal('hello ', ' hello ', 'lstrip')
706 self.checkequal(' hello', ' hello ', 'rstrip')
707 self.checkequal('hello', 'hello', 'strip')
708
709 # strip/lstrip/rstrip with None arg
710 self.checkequal('hello', ' hello ', 'strip', None)
711 self.checkequal('hello ', ' hello ', 'lstrip', None)
712 self.checkequal(' hello', ' hello ', 'rstrip', None)
713 self.checkequal('hello', 'hello', 'strip', None)
714
715 # strip/lstrip/rstrip with str arg
716 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
717 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
718 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
719 self.checkequal('hello', 'hello', 'strip', 'xyz')
720
Georg Brandlc7885542007-03-06 19:16:20 +0000721 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
722 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
723 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
724
725 def test_ljust(self):
726 self.checkequal('abc ', 'abc', 'ljust', 10)
727 self.checkequal('abc ', 'abc', 'ljust', 6)
728 self.checkequal('abc', 'abc', 'ljust', 3)
729 self.checkequal('abc', 'abc', 'ljust', 2)
730 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
731 self.checkraises(TypeError, 'abc', 'ljust')
732
733 def test_rjust(self):
734 self.checkequal(' abc', 'abc', 'rjust', 10)
735 self.checkequal(' abc', 'abc', 'rjust', 6)
736 self.checkequal('abc', 'abc', 'rjust', 3)
737 self.checkequal('abc', 'abc', 'rjust', 2)
738 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
739 self.checkraises(TypeError, 'abc', 'rjust')
740
741 def test_center(self):
742 self.checkequal(' abc ', 'abc', 'center', 10)
743 self.checkequal(' abc ', 'abc', 'center', 6)
744 self.checkequal('abc', 'abc', 'center', 3)
745 self.checkequal('abc', 'abc', 'center', 2)
746 self.checkequal('***abc****', 'abc', 'center', 10, '*')
747 self.checkraises(TypeError, 'abc', 'center')
748
749 def test_swapcase(self):
750 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
751
752 self.checkraises(TypeError, 'hello', 'swapcase', 42)
753
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000754 def test_zfill(self):
755 self.checkequal('123', '123', 'zfill', 2)
756 self.checkequal('123', '123', 'zfill', 3)
757 self.checkequal('0123', '123', 'zfill', 4)
758 self.checkequal('+123', '+123', 'zfill', 3)
759 self.checkequal('+123', '+123', 'zfill', 4)
760 self.checkequal('+0123', '+123', 'zfill', 5)
761 self.checkequal('-123', '-123', 'zfill', 3)
762 self.checkequal('-123', '-123', 'zfill', 4)
763 self.checkequal('-0123', '-123', 'zfill', 5)
764 self.checkequal('000', '', 'zfill', 3)
765 self.checkequal('34', '34', 'zfill', 1)
766 self.checkequal('0034', '34', 'zfill', 4)
767
768 self.checkraises(TypeError, '123', 'zfill')
769
770class MixinStrUnicodeUserStringTest:
771 # additional tests that only work for
772 # stringlike objects, i.e. str, unicode, UserString
773 # (but not the string module)
774
775 def test_islower(self):
776 self.checkequal(False, '', 'islower')
777 self.checkequal(True, 'a', 'islower')
778 self.checkequal(False, 'A', 'islower')
779 self.checkequal(False, '\n', 'islower')
780 self.checkequal(True, 'abc', 'islower')
781 self.checkequal(False, 'aBc', 'islower')
782 self.checkequal(True, 'abc\n', 'islower')
783 self.checkraises(TypeError, 'abc', 'islower', 42)
784
785 def test_isupper(self):
786 self.checkequal(False, '', 'isupper')
787 self.checkequal(False, 'a', 'isupper')
788 self.checkequal(True, 'A', 'isupper')
789 self.checkequal(False, '\n', 'isupper')
790 self.checkequal(True, 'ABC', 'isupper')
791 self.checkequal(False, 'AbC', 'isupper')
792 self.checkequal(True, 'ABC\n', 'isupper')
793 self.checkraises(TypeError, 'abc', 'isupper', 42)
794
795 def test_istitle(self):
796 self.checkequal(False, '', 'istitle')
797 self.checkequal(False, 'a', 'istitle')
798 self.checkequal(True, 'A', 'istitle')
799 self.checkequal(False, '\n', 'istitle')
800 self.checkequal(True, 'A Titlecased Line', 'istitle')
801 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
802 self.checkequal(True, 'A Titlecased, Line', 'istitle')
803 self.checkequal(False, 'Not a capitalized String', 'istitle')
804 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
805 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
806 self.checkequal(False, 'NOT', 'istitle')
807 self.checkraises(TypeError, 'abc', 'istitle', 42)
808
809 def test_isspace(self):
810 self.checkequal(False, '', 'isspace')
811 self.checkequal(False, 'a', 'isspace')
812 self.checkequal(True, ' ', 'isspace')
813 self.checkequal(True, '\t', 'isspace')
814 self.checkequal(True, '\r', 'isspace')
815 self.checkequal(True, '\n', 'isspace')
816 self.checkequal(True, ' \t\r\n', 'isspace')
817 self.checkequal(False, ' \t\r\na', 'isspace')
818 self.checkraises(TypeError, 'abc', 'isspace', 42)
819
820 def test_isalpha(self):
821 self.checkequal(False, '', 'isalpha')
822 self.checkequal(True, 'a', 'isalpha')
823 self.checkequal(True, 'A', 'isalpha')
824 self.checkequal(False, '\n', 'isalpha')
825 self.checkequal(True, 'abc', 'isalpha')
826 self.checkequal(False, 'aBc123', 'isalpha')
827 self.checkequal(False, 'abc\n', 'isalpha')
828 self.checkraises(TypeError, 'abc', 'isalpha', 42)
829
830 def test_isalnum(self):
831 self.checkequal(False, '', 'isalnum')
832 self.checkequal(True, 'a', 'isalnum')
833 self.checkequal(True, 'A', 'isalnum')
834 self.checkequal(False, '\n', 'isalnum')
835 self.checkequal(True, '123abc456', 'isalnum')
836 self.checkequal(True, 'a1b3c', 'isalnum')
837 self.checkequal(False, 'aBc000 ', 'isalnum')
838 self.checkequal(False, 'abc\n', 'isalnum')
839 self.checkraises(TypeError, 'abc', 'isalnum', 42)
840
841 def test_isdigit(self):
842 self.checkequal(False, '', 'isdigit')
843 self.checkequal(False, 'a', 'isdigit')
844 self.checkequal(True, '0', 'isdigit')
845 self.checkequal(True, '0123456789', 'isdigit')
846 self.checkequal(False, '0123456789a', 'isdigit')
847
848 self.checkraises(TypeError, 'abc', 'isdigit', 42)
849
850 def test_title(self):
851 self.checkequal(' Hello ', ' hello ', 'title')
852 self.checkequal('Hello ', 'hello ', 'title')
853 self.checkequal('Hello ', 'Hello ', 'title')
854 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
855 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
856 self.checkequal('Getint', "getInt", 'title')
857 self.checkraises(TypeError, 'hello', 'title', 42)
858
859 def test_splitlines(self):
860 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
861 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
862 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
863 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
864 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
865 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
866 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
867
868 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
869
870 def test_startswith(self):
871 self.checkequal(True, 'hello', 'startswith', 'he')
872 self.checkequal(True, 'hello', 'startswith', 'hello')
873 self.checkequal(False, 'hello', 'startswith', 'hello world')
874 self.checkequal(True, 'hello', 'startswith', '')
875 self.checkequal(False, 'hello', 'startswith', 'ello')
876 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
877 self.checkequal(True, 'hello', 'startswith', 'o', 4)
878 self.checkequal(False, 'hello', 'startswith', 'o', 5)
879 self.checkequal(True, 'hello', 'startswith', '', 5)
880 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
881 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
882 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
883 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
884
885 # test negative indices
886 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
887 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
888 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
889 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
890 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
891 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
892 self.checkequal(False, 'hello', 'startswith', 'o', -2)
893 self.checkequal(True, 'hello', 'startswith', 'o', -1)
894 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
895 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
896
897 self.checkraises(TypeError, 'hello', 'startswith')
898 self.checkraises(TypeError, 'hello', 'startswith', 42)
899
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000900 # test tuple arguments
901 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
902 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
903 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
904 self.checkequal(False, 'hello', 'startswith', ())
905 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
906 'rld', 'lowo'), 3)
907 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
908 'rld'), 3)
909 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
910 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
911 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
912
913 self.checkraises(TypeError, 'hello', 'startswith', (42,))
914
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000915 def test_endswith(self):
916 self.checkequal(True, 'hello', 'endswith', 'lo')
917 self.checkequal(False, 'hello', 'endswith', 'he')
918 self.checkequal(True, 'hello', 'endswith', '')
919 self.checkequal(False, 'hello', 'endswith', 'hello world')
920 self.checkequal(False, 'helloworld', 'endswith', 'worl')
921 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
922 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
923 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
924 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
925 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
926 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
927 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
928 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
929 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
930
931 # test negative indices
932 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
933 self.checkequal(False, 'hello', 'endswith', 'he', -2)
934 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
935 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
936 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
937 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
938 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
939 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
940 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
941 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
942 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
943 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
944 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
945
946 self.checkraises(TypeError, 'hello', 'endswith')
947 self.checkraises(TypeError, 'hello', 'endswith', 42)
948
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000949 # test tuple arguments
950 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
951 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
952 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
953 self.checkequal(False, 'hello', 'endswith', ())
954 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
955 'rld', 'lowo'), 3)
956 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
957 'rld'), 3, -1)
958 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
959 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
960 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
961
962 self.checkraises(TypeError, 'hello', 'endswith', (42,))
963
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000964 def test___contains__(self):
965 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
966 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
967 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
968 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
969 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
970 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
971 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
972 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
973 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
974
975 def test_subscript(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000976 self.checkequal('a', 'abc', '__getitem__', 0)
977 self.checkequal('c', 'abc', '__getitem__', -1)
978 self.checkequal('a', 'abc', '__getitem__', 0)
979 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
980 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
981 self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
982 self.checkequal('', 'abc', '__getitem__', slice(0, 0))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000983
984 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
985
986 def test_slice(self):
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000987 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
988 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
989 self.checkequal('ab', 'abc', '__getitem__', slice(0, 2))
990 self.checkequal('bc', 'abc', '__getitem__', slice(1, 3))
991 self.checkequal('b', 'abc', '__getitem__', slice(1, 2))
992 self.checkequal('', 'abc', '__getitem__', slice(2, 2))
993 self.checkequal('', 'abc', '__getitem__', slice(1000, 1000))
994 self.checkequal('', 'abc', '__getitem__', slice(2000, 1000))
995 self.checkequal('', 'abc', '__getitem__', slice(2, 1))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000996
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000997 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000998
Thomas Woutersed03b412007-08-28 21:37:11 +0000999 def test_extended_getslice(self):
1000 # Test extended slicing by comparing with list slicing.
1001 s = string.ascii_letters + string.digits
1002 indices = (0, None, 1, 3, 41, -1, -2, -37)
1003 for start in indices:
1004 for stop in indices:
1005 # Skip step 0 (invalid)
1006 for step in indices[1:]:
1007 L = list(s)[start:stop:step]
1008 self.checkequal("".join(L), s, '__getitem__',
1009 slice(start, stop, step))
1010
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001011 def test_mul(self):
1012 self.checkequal('', 'abc', '__mul__', -1)
1013 self.checkequal('', 'abc', '__mul__', 0)
1014 self.checkequal('abc', 'abc', '__mul__', 1)
1015 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
1016 self.checkraises(TypeError, 'abc', '__mul__')
1017 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +00001018 # XXX: on a 64-bit system, this doesn't raise an overflow error,
1019 # but either raises a MemoryError, or succeeds (if you have 54TiB)
1020 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001021
1022 def test_join(self):
1023 # join now works with any sequence type
1024 # moved here, because the argument order is
1025 # different in string.join (see the test in
1026 # test.test_string.StringTest.test_join)
1027 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
1028 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
1030 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001031 self.checkequal('w x y z', ' ', 'join', Sequence())
1032 self.checkequal('abc', 'a', 'join', ('abc',))
1033 self.checkequal('z', 'a', 'join', UserList(['z']))
Walter Dörwald67e83882007-05-05 12:26:27 +00001034 self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c'])
Guido van Rossum98297ee2007-11-06 21:34:58 +00001035 self.assertRaises(TypeError, '.'.join, ['a', 'b', 3])
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001036 for i in [5, 25, 125]:
1037 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1038 ['a' * i] * i)
1039 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1040 ('a' * i,) * i)
1041
Guido van Rossum98297ee2007-11-06 21:34:58 +00001042 #self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1())
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001043 self.checkequal('a b c', ' ', 'join', BadSeq2())
1044
1045 self.checkraises(TypeError, ' ', 'join')
1046 self.checkraises(TypeError, ' ', 'join', 7)
Guido van Rossumf1044292007-09-27 18:01:22 +00001047 self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()])
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001048 try:
1049 def f():
1050 yield 4 + ""
1051 self.fixtype(' ').join(f())
Guido van Rossumb940e112007-01-10 16:19:56 +00001052 except TypeError as e:
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001053 if '+' not in str(e):
1054 self.fail('join() ate exception message')
1055 else:
1056 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001057
1058 def test_formatting(self):
1059 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1060 self.checkequal('+10+', '+%d+', '__mod__', 10)
1061 self.checkequal('a', "%c", '__mod__', "a")
1062 self.checkequal('a', "%c", '__mod__', "a")
1063 self.checkequal('"', "%c", '__mod__', 34)
1064 self.checkequal('$', "%c", '__mod__', 36)
1065 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001066 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001067
1068 for ordinal in (-100, 0x200000):
1069 # unicode raises ValueError, str raises OverflowError
1070 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1071
Christian Heimesa612dc02008-02-24 13:08:18 +00001072 longvalue = sys.maxsize + 10
1073 slongvalue = str(longvalue)
1074 if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001075 self.checkequal(' 42', '%3ld', '__mod__', 42)
Christian Heimesa612dc02008-02-24 13:08:18 +00001076 self.checkequal('42', '%d', '__mod__', 42.0)
1077 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1078 self.checkcall('%d', '__mod__', float(longvalue))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001079 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001080 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001081
1082 self.checkraises(TypeError, 'abc', '__mod__')
1083 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1084 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1085 self.checkraises(TypeError, '%c', '__mod__', (None,))
1086 self.checkraises(ValueError, '%(foo', '__mod__', {})
1087 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
Christian Heimesa612dc02008-02-24 13:08:18 +00001088 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
1089 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001090
1091 # argument names with properly nested brackets are supported
1092 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1093
1094 # 100 is a magic number in PyUnicode_Format, this forces a resize
1095 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1096
1097 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1098 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1099 self.checkraises(ValueError, '%10', '__mod__', (42,))
1100
1101 def test_floatformatting(self):
1102 # float formatting
Guido van Rossum805365e2007-05-07 22:24:25 +00001103 for prec in range(100):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001104 format = '%%.%if' % prec
1105 value = 0.01
Guido van Rossum805365e2007-05-07 22:24:25 +00001106 for x in range(60):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001107 value = value * 3.141592655 / 3.0 * 10.0
1108 # The formatfloat() code in stringobject.c and
1109 # unicodeobject.c uses a 120 byte buffer and switches from
1110 # 'f' formatting to 'g' at precision 50, so we expect
1111 # OverflowErrors for the ranges x < 50 and prec >= 67.
1112 if x < 50 and prec >= 67:
1113 self.checkraises(OverflowError, format, "__mod__", value)
1114 else:
1115 self.checkcall(format, "__mod__", value)
1116
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 def test_inplace_rewrites(self):
1118 # Check that strings don't copy and modify cached single-character strings
1119 self.checkequal('a', 'A', 'lower')
1120 self.checkequal(True, 'A', 'isupper')
1121 self.checkequal('A', 'a', 'upper')
1122 self.checkequal(True, 'a', 'islower')
1123
1124 self.checkequal('a', 'A', 'replace', 'A', 'a')
1125 self.checkequal(True, 'A', 'isupper')
1126
1127 self.checkequal('A', 'a', 'capitalize')
1128 self.checkequal(True, 'a', 'islower')
1129
1130 self.checkequal('A', 'a', 'swapcase')
1131 self.checkequal(True, 'a', 'islower')
1132
1133 self.checkequal('A', 'a', 'title')
1134 self.checkequal(True, 'a', 'islower')
1135
1136 def test_partition(self):
1137
1138 self.checkequal(('this is the par', 'ti', 'tion method'),
1139 'this is the partition method', 'partition', 'ti')
1140
1141 # from raymond's original specification
1142 S = 'http://www.python.org'
1143 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1144 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1145 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1146 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1147
1148 self.checkraises(ValueError, S, 'partition', '')
1149 self.checkraises(TypeError, S, 'partition', None)
1150
1151 def test_rpartition(self):
1152
1153 self.checkequal(('this is the rparti', 'ti', 'on method'),
1154 'this is the rpartition method', 'rpartition', 'ti')
1155
1156 # from raymond's original specification
1157 S = 'http://www.python.org'
1158 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001159 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1161 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1162
1163 self.checkraises(ValueError, S, 'rpartition', '')
1164 self.checkraises(TypeError, S, 'rpartition', None)
1165
Walter Dörwald57d88e52004-08-26 16:53:04 +00001166
Walter Dörwald57d88e52004-08-26 16:53:04 +00001167class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001168 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001169
1170 def test_bug1001011(self):
1171 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001172 # involving a subclass.
1173 # Make sure that it is of the appropriate type.
1174 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001175 t = self.type2test
1176 class subclass(t):
1177 pass
1178 s1 = subclass("abcd")
1179 s2 = t().join([s1])
1180 self.assert_(s1 is not s2)
1181 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001182
1183 s1 = t("abcd")
1184 s2 = t().join([s1])
1185 self.assert_(s1 is s2)
1186
1187 # Should also test mixed-type join.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001188 if t is str:
Tim Peters108f1372004-08-27 05:36:07 +00001189 s1 = subclass("abcd")
1190 s2 = "".join([s1])
1191 self.assert_(s1 is not s2)
1192 self.assert_(type(s2) is t)
1193
1194 s1 = t("abcd")
1195 s2 = "".join([s1])
1196 self.assert_(s1 is s2)
1197
Guido van Rossum98297ee2007-11-06 21:34:58 +00001198## elif t is str8:
1199## s1 = subclass("abcd")
1200## s2 = "".join([s1])
1201## self.assert_(s1 is not s2)
1202## self.assert_(type(s2) is str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001203
Guido van Rossum98297ee2007-11-06 21:34:58 +00001204## s1 = t("abcd")
1205## s2 = "".join([s1])
1206## self.assert_(s1 is not s2)
1207## self.assert_(type(s2) is str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001208
1209 else:
1210 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)