blob: 60308d740068f108c5b19c7759bfe6c347ae8a98 [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
110 self.checkraises(TypeError, 'hello', 'count')
111 self.checkraises(TypeError, 'hello', 'count', 42)
112
Raymond Hettinger57e74472005-02-20 09:54:53 +0000113 # For a variety of combinations,
114 # verify that str.count() matches an equivalent function
115 # replacing all occurrences and then differencing the string lengths
116 charset = ['', 'a', 'b']
117 digits = 7
118 base = len(charset)
119 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000120 for i in range(base ** digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000121 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000122 for j in range(digits):
Raymond Hettinger57e74472005-02-20 09:54:53 +0000123 i, m = divmod(i, base)
124 entry.append(charset[m])
125 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000126 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger57e74472005-02-20 09:54:53 +0000127 for i in teststrings:
Raymond Hettinger57e74472005-02-20 09:54:53 +0000128 n = len(i)
129 for j in teststrings:
130 r1 = i.count(j)
131 if j:
Guido van Rossum09549f42007-08-27 20:40:10 +0000132 r2, rem = divmod(n - len(i.replace(j, self.fixtype(''))),
133 len(j))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000134 else:
135 r2, rem = len(i)+1, 0
136 if rem or r1 != r2:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
138 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000139
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000140 def test_find(self):
141 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
142 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
143 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
144
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000145 self.checkequal(0, 'abc', 'find', '', 0)
146 self.checkequal(3, 'abc', 'find', '', 3)
147 self.checkequal(-1, 'abc', 'find', '', 4)
148
Christian Heimes9cd17752007-11-18 19:35:23 +0000149 # to check the ability to pass None as defaults
150 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
151 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
152 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
153 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
154 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
155
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000156 self.checkraises(TypeError, 'hello', 'find')
157 self.checkraises(TypeError, 'hello', 'find', 42)
158
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000159 # For a variety of combinations,
160 # verify that str.find() matches __contains__
161 # and that the found substring is really at that location
162 charset = ['', 'a', 'b', 'c']
163 digits = 5
164 base = len(charset)
165 teststrings = set()
Guido van Rossum805365e2007-05-07 22:24:25 +0000166 for i in range(base ** digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000167 entry = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000168 for j in range(digits):
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000169 i, m = divmod(i, base)
170 entry.append(charset[m])
171 teststrings.add(''.join(entry))
Guido van Rossum09549f42007-08-27 20:40:10 +0000172 teststrings = [self.fixtype(ts) for ts in teststrings]
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000173 for i in teststrings:
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000174 for j in teststrings:
175 loc = i.find(j)
176 r1 = (loc != -1)
177 r2 = j in i
178 if r1 != r2:
179 self.assertEqual(r1, r2)
180 if loc != -1:
181 self.assertEqual(i[loc:loc+len(j)], j)
182
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000183 def test_rfind(self):
184 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
185 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
186 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
187 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
188
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000189 self.checkequal(3, 'abc', 'rfind', '', 0)
190 self.checkequal(3, 'abc', 'rfind', '', 3)
191 self.checkequal(-1, 'abc', 'rfind', '', 4)
192
Christian Heimes9cd17752007-11-18 19:35:23 +0000193 # to check the ability to pass None as defaults
194 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
195 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
196 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
197 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
198 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
199
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000200 self.checkraises(TypeError, 'hello', 'rfind')
201 self.checkraises(TypeError, 'hello', 'rfind', 42)
202
203 def test_index(self):
204 self.checkequal(0, 'abcdefghiabc', 'index', '')
205 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
206 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
207 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
208
209 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
210 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
211 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
212 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
213
Christian Heimes9cd17752007-11-18 19:35:23 +0000214 # to check the ability to pass None as defaults
215 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
216 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
217 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
218 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
219 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
220
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000221 self.checkraises(TypeError, 'hello', 'index')
222 self.checkraises(TypeError, 'hello', 'index', 42)
223
224 def test_rindex(self):
225 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
226 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
227 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
228 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
229
230 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
231 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
232 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
233 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
234 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
235
Christian Heimes9cd17752007-11-18 19:35:23 +0000236 # to check the ability to pass None as defaults
237 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
238 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
239 self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
240 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
241 self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
242
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000243 self.checkraises(TypeError, 'hello', 'rindex')
244 self.checkraises(TypeError, 'hello', 'rindex', 42)
245
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000246 def test_lower(self):
247 self.checkequal('hello', 'HeLLo', 'lower')
248 self.checkequal('hello', 'hello', 'lower')
249 self.checkraises(TypeError, 'hello', 'lower', 42)
250
251 def test_upper(self):
252 self.checkequal('HELLO', 'HeLLo', 'upper')
253 self.checkequal('HELLO', 'HELLO', 'upper')
254 self.checkraises(TypeError, 'hello', 'upper', 42)
255
256 def test_expandtabs(self):
257 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
258 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
259 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
260 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
261 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
262 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
263 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
264 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
265
266 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
267 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000268 if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000269 self.checkraises(OverflowError,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000270 '\ta\n\tb', 'expandtabs', sys.maxsize)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000271
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000272 def test_split(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000273 # by a char
274 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000275 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000276 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
277 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
278 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
279 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000280 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000281 sys.maxsize-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000282 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
283 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
284 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000285 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
286 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000287 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
288
Thomas Wouters477c8d52006-05-27 19:21:47 +0000289 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
290 self.checkequal(['a']*15 +['a|a|a|a|a'],
291 ('a|'*20)[:-1], 'split', '|', 15)
292
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000293 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000294 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000295 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
296 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
297 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
298 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000299 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000300 sys.maxsize-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000301 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
302 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000303 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000304 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
305 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
306 'split', 'test')
307 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
308 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
309 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
310 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
311 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
312 self.checkequal([''], '', 'split', 'aaa')
313 self.checkequal(['aa'], 'aa', 'split', 'aaa')
314 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
315 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
316
317 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
318 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
319 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
320 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000321
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000322 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000323 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
324
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325 # null case
326 self.checkraises(ValueError, 'hello', 'split', '')
327 self.checkraises(ValueError, 'hello', 'split', '', 0)
328
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000329 def test_rsplit(self):
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000330 # by a char
331 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
332 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
333 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
334 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
335 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000336 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000337 sys.maxsize-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000338 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
339 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
340 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000341 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
342 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
343
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000344 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
345
Thomas Wouters477c8d52006-05-27 19:21:47 +0000346 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
347 self.checkequal(['a|a|a|a|a']+['a']*15,
348 ('a|'*20)[:-1], 'rsplit', '|', 15)
349
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000350 # by string
351 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
352 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
353 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
354 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
355 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
Christian Heimesa37d4c62007-12-04 23:02:19 +0000357 sys.maxsize-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000358 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
359 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
360 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
362 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
363 'rsplit', 'test')
364 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
365 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
366 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
367 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
368 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
369 self.checkequal([''], '', 'rsplit', 'aaa')
370 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
371 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
372 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
373
374 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
375 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
376 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
377 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000378
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000379 # argument type
380 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000381
Thomas Wouters477c8d52006-05-27 19:21:47 +0000382 # null case
383 self.checkraises(ValueError, 'hello', 'rsplit', '')
384 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
385
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000386 def test_replace(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000387 EQ = self.checkequal
388
389 # Operations on the empty string
390 EQ("", "", "replace", "", "")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000391 EQ("A", "", "replace", "", "A")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000392 EQ("", "", "replace", "A", "")
393 EQ("", "", "replace", "A", "A")
394 EQ("", "", "replace", "", "", 100)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000395 EQ("", "", "replace", "", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000396
397 # interleave (from=="", 'to' gets inserted everywhere)
398 EQ("A", "A", "replace", "", "")
399 EQ("*A*", "A", "replace", "", "*")
400 EQ("*1A*1", "A", "replace", "", "*1")
401 EQ("*-#A*-#", "A", "replace", "", "*-#")
402 EQ("*-A*-A*-", "AA", "replace", "", "*-")
403 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000404 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000405 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
406 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
407 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
408 EQ("*-AA", "AA", "replace", "", "*-", 1)
409 EQ("AA", "AA", "replace", "", "*-", 0)
410
411 # single character deletion (from=="A", to=="")
412 EQ("", "A", "replace", "A", "")
413 EQ("", "AAA", "replace", "A", "")
414 EQ("", "AAA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000415 EQ("", "AAA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000416 EQ("", "AAA", "replace", "A", "", 4)
417 EQ("", "AAA", "replace", "A", "", 3)
418 EQ("A", "AAA", "replace", "A", "", 2)
419 EQ("AA", "AAA", "replace", "A", "", 1)
420 EQ("AAA", "AAA", "replace", "A", "", 0)
421 EQ("", "AAAAAAAAAA", "replace", "A", "")
422 EQ("BCD", "ABACADA", "replace", "A", "")
423 EQ("BCD", "ABACADA", "replace", "A", "", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000424 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425 EQ("BCD", "ABACADA", "replace", "A", "", 5)
426 EQ("BCD", "ABACADA", "replace", "A", "", 4)
427 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
428 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
429 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
430 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
431 EQ("BCD", "ABCAD", "replace", "A", "")
432 EQ("BCD", "ABCADAA", "replace", "A", "")
433 EQ("BCD", "BCD", "replace", "A", "")
434 EQ("*************", "*************", "replace", "A", "")
435 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
436
437 # substring deletion (from=="the", to=="")
438 EQ("", "the", "replace", "the", "")
439 EQ("ater", "theater", "replace", "the", "")
440 EQ("", "thethe", "replace", "the", "")
441 EQ("", "thethethethe", "replace", "the", "")
442 EQ("aaaa", "theatheatheathea", "replace", "the", "")
443 EQ("that", "that", "replace", "the", "")
444 EQ("thaet", "thaet", "replace", "the", "")
445 EQ("here and re", "here and there", "replace", "the", "")
446 EQ("here and re and re", "here and there and there",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000447 "replace", "the", "", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448 EQ("here and re and re", "here and there and there",
449 "replace", "the", "", -1)
450 EQ("here and re and re", "here and there and there",
451 "replace", "the", "", 3)
452 EQ("here and re and re", "here and there and there",
453 "replace", "the", "", 2)
454 EQ("here and re and there", "here and there and there",
455 "replace", "the", "", 1)
456 EQ("here and there and there", "here and there and there",
457 "replace", "the", "", 0)
458 EQ("here and re and re", "here and there and there", "replace", "the", "")
459
460 EQ("abc", "abc", "replace", "the", "")
461 EQ("abcdefg", "abcdefg", "replace", "the", "")
462
463 # substring deletion (from=="bob", to=="")
464 EQ("bob", "bbobob", "replace", "bob", "")
465 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
466 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
467 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
468
469 # single character replace in place (len(from)==len(to)==1)
470 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
471 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000472 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000473 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
474 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
475 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
476 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
477 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
478
479 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
480 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
481 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
482 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
483 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
484
485 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
486
487 # substring replace in place (len(from)==len(to) > 1)
488 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
Christian Heimesa37d4c62007-12-04 23:02:19 +0000489 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000490 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
491 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
492 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
493 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
494 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
495 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
496 EQ("cobob", "bobob", "replace", "bob", "cob")
497 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
498 EQ("bobob", "bobob", "replace", "bot", "bot")
499
500 # replace single character (len(from)==1, len(to)>1)
501 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
502 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
Christian Heimesa37d4c62007-12-04 23:02:19 +0000503 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000504 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
505 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
506 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
507 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
508
509 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
510
511 # replace substring (len(from)>1, len(to)!=len(from))
512 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
513 "replace", "spam", "ham")
514 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
Christian Heimesa37d4c62007-12-04 23:02:19 +0000515 "replace", "spam", "ham", sys.maxsize)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000516 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
517 "replace", "spam", "ham", -1)
518 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
519 "replace", "spam", "ham", 4)
520 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
521 "replace", "spam", "ham", 3)
522 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
523 "replace", "spam", "ham", 2)
524 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
525 "replace", "spam", "ham", 1)
526 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
527 "replace", "spam", "ham", 0)
528
529 EQ("bobob", "bobobob", "replace", "bobob", "bob")
530 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
531 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
532
Guido van Rossum39478e82007-08-27 17:23:59 +0000533 # XXX Commented out. Is there any reason to support buffer objects
534 # as arguments for str.replace()? GvR
Guido van Rossum254348e2007-11-21 19:29:53 +0000535## ba = bytearray('a')
536## bb = bytearray('b')
Guido van Rossum39478e82007-08-27 17:23:59 +0000537## EQ("bbc", "abc", "replace", ba, bb)
538## EQ("aac", "abc", "replace", bb, ba)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000539
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000541 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
542 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
543 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
544 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
545 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
546 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
547 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
548 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
549 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
550 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
551 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
552 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
553 self.checkequal('', '', 'replace', '', '')
554 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
555 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
556 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
557 # MemoryError due to empty result (platform malloc issue when requesting
558 # 0 bytes).
559 self.checkequal('', '123', 'replace', '123', '')
560 self.checkequal('', '123123', 'replace', '123', '')
561 self.checkequal('x', '123x123', 'replace', '123', '')
562
563 self.checkraises(TypeError, 'hello', 'replace')
564 self.checkraises(TypeError, 'hello', 'replace', 42)
565 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
566 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
567
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 def test_replace_overflow(self):
569 # Check for overflow checking on 32 bit machines
Christian Heimesa37d4c62007-12-04 23:02:19 +0000570 if sys.maxsize != 2147483647 or struct.calcsize("P") > 4:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571 return
572 A2_16 = "A" * (2**16)
573 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
574 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
575 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
576
Georg Brandlc7885542007-03-06 19:16:20 +0000577
578
579class CommonTest(BaseTest):
580 # This testcase contains test that can be used in all
581 # stringlike classes. Currently this is str, unicode
582 # UserString and the string module.
583
584 def test_hash(self):
585 # SF bug 1054139: += optimization was not invalidating cached hash value
586 a = self.type2test('DNSSEC')
587 b = self.type2test('')
588 for c in a:
589 b += c
590 hash(b)
591 self.assertEqual(hash(a), hash(b))
592
593 def test_capitalize(self):
594 self.checkequal(' hello ', ' hello ', 'capitalize')
595 self.checkequal('Hello ', 'Hello ','capitalize')
596 self.checkequal('Hello ', 'hello ','capitalize')
597 self.checkequal('Aaaa', 'aaaa', 'capitalize')
598 self.checkequal('Aaaa', 'AaAa', 'capitalize')
599
600 self.checkraises(TypeError, 'hello', 'capitalize', 42)
601
602 def test_lower(self):
603 self.checkequal('hello', 'HeLLo', 'lower')
604 self.checkequal('hello', 'hello', 'lower')
605 self.checkraises(TypeError, 'hello', 'lower', 42)
606
607 def test_upper(self):
608 self.checkequal('HELLO', 'HeLLo', 'upper')
609 self.checkequal('HELLO', 'HELLO', 'upper')
610 self.checkraises(TypeError, 'hello', 'upper', 42)
611
612 def test_expandtabs(self):
613 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
614 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
615 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
616 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
617 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
618 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
619 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
620
621 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
622
623 def test_additional_split(self):
624 self.checkequal(['this', 'is', 'the', 'split', 'function'],
625 'this is the split function', 'split')
626
627 # by whitespace
628 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
629 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
630 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
631 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
632 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
633 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000634 sys.maxsize-1)
Georg Brandlc7885542007-03-06 19:16:20 +0000635 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
636 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
637 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
638
639 self.checkequal([], ' ', 'split')
640 self.checkequal(['a'], ' a ', 'split')
641 self.checkequal(['a', 'b'], ' a b ', 'split')
642 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
643 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
644 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
645 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
646 aaa = ' a '*20
647 self.checkequal(['a']*20, aaa, 'split')
648 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
649 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
650
651 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000652 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000653
654 def test_additional_rsplit(self):
655 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
656 'this is the rsplit function', 'rsplit')
657
658 # by whitespace
659 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
660 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
661 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
662 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
663 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
664 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000665 sys.maxsize-20)
Georg Brandlc7885542007-03-06 19:16:20 +0000666 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
667 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
668 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
669
670 self.checkequal([], ' ', 'rsplit')
671 self.checkequal(['a'], ' a ', 'rsplit')
672 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
673 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
674 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
675 None, 1)
676 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
677 None, 2)
678 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
679 aaa = ' a '*20
680 self.checkequal(['a']*20, aaa, 'rsplit')
681 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
682 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
683
684 # mixed use of str and unicode
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000685 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', ' ', 2)
Georg Brandlc7885542007-03-06 19:16:20 +0000686
687 def test_strip(self):
688 self.checkequal('hello', ' hello ', 'strip')
689 self.checkequal('hello ', ' hello ', 'lstrip')
690 self.checkequal(' hello', ' hello ', 'rstrip')
691 self.checkequal('hello', 'hello', 'strip')
692
693 # strip/lstrip/rstrip with None arg
694 self.checkequal('hello', ' hello ', 'strip', None)
695 self.checkequal('hello ', ' hello ', 'lstrip', None)
696 self.checkequal(' hello', ' hello ', 'rstrip', None)
697 self.checkequal('hello', 'hello', 'strip', None)
698
699 # strip/lstrip/rstrip with str arg
700 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
701 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
702 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
703 self.checkequal('hello', 'hello', 'strip', 'xyz')
704
Georg Brandlc7885542007-03-06 19:16:20 +0000705 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
706 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
707 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
708
709 def test_ljust(self):
710 self.checkequal('abc ', 'abc', 'ljust', 10)
711 self.checkequal('abc ', 'abc', 'ljust', 6)
712 self.checkequal('abc', 'abc', 'ljust', 3)
713 self.checkequal('abc', 'abc', 'ljust', 2)
714 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
715 self.checkraises(TypeError, 'abc', 'ljust')
716
717 def test_rjust(self):
718 self.checkequal(' abc', 'abc', 'rjust', 10)
719 self.checkequal(' abc', 'abc', 'rjust', 6)
720 self.checkequal('abc', 'abc', 'rjust', 3)
721 self.checkequal('abc', 'abc', 'rjust', 2)
722 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
723 self.checkraises(TypeError, 'abc', 'rjust')
724
725 def test_center(self):
726 self.checkequal(' abc ', 'abc', 'center', 10)
727 self.checkequal(' abc ', 'abc', 'center', 6)
728 self.checkequal('abc', 'abc', 'center', 3)
729 self.checkequal('abc', 'abc', 'center', 2)
730 self.checkequal('***abc****', 'abc', 'center', 10, '*')
731 self.checkraises(TypeError, 'abc', 'center')
732
733 def test_swapcase(self):
734 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
735
736 self.checkraises(TypeError, 'hello', 'swapcase', 42)
737
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000738 def test_zfill(self):
739 self.checkequal('123', '123', 'zfill', 2)
740 self.checkequal('123', '123', 'zfill', 3)
741 self.checkequal('0123', '123', 'zfill', 4)
742 self.checkequal('+123', '+123', 'zfill', 3)
743 self.checkequal('+123', '+123', 'zfill', 4)
744 self.checkequal('+0123', '+123', 'zfill', 5)
745 self.checkequal('-123', '-123', 'zfill', 3)
746 self.checkequal('-123', '-123', 'zfill', 4)
747 self.checkequal('-0123', '-123', 'zfill', 5)
748 self.checkequal('000', '', 'zfill', 3)
749 self.checkequal('34', '34', 'zfill', 1)
750 self.checkequal('0034', '34', 'zfill', 4)
751
752 self.checkraises(TypeError, '123', 'zfill')
753
754class MixinStrUnicodeUserStringTest:
755 # additional tests that only work for
756 # stringlike objects, i.e. str, unicode, UserString
757 # (but not the string module)
758
759 def test_islower(self):
760 self.checkequal(False, '', 'islower')
761 self.checkequal(True, 'a', 'islower')
762 self.checkequal(False, 'A', 'islower')
763 self.checkequal(False, '\n', 'islower')
764 self.checkequal(True, 'abc', 'islower')
765 self.checkequal(False, 'aBc', 'islower')
766 self.checkequal(True, 'abc\n', 'islower')
767 self.checkraises(TypeError, 'abc', 'islower', 42)
768
769 def test_isupper(self):
770 self.checkequal(False, '', 'isupper')
771 self.checkequal(False, 'a', 'isupper')
772 self.checkequal(True, 'A', 'isupper')
773 self.checkequal(False, '\n', 'isupper')
774 self.checkequal(True, 'ABC', 'isupper')
775 self.checkequal(False, 'AbC', 'isupper')
776 self.checkequal(True, 'ABC\n', 'isupper')
777 self.checkraises(TypeError, 'abc', 'isupper', 42)
778
779 def test_istitle(self):
780 self.checkequal(False, '', 'istitle')
781 self.checkequal(False, 'a', 'istitle')
782 self.checkequal(True, 'A', 'istitle')
783 self.checkequal(False, '\n', 'istitle')
784 self.checkequal(True, 'A Titlecased Line', 'istitle')
785 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
786 self.checkequal(True, 'A Titlecased, Line', 'istitle')
787 self.checkequal(False, 'Not a capitalized String', 'istitle')
788 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
789 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
790 self.checkequal(False, 'NOT', 'istitle')
791 self.checkraises(TypeError, 'abc', 'istitle', 42)
792
793 def test_isspace(self):
794 self.checkequal(False, '', 'isspace')
795 self.checkequal(False, 'a', 'isspace')
796 self.checkequal(True, ' ', 'isspace')
797 self.checkequal(True, '\t', 'isspace')
798 self.checkequal(True, '\r', 'isspace')
799 self.checkequal(True, '\n', 'isspace')
800 self.checkequal(True, ' \t\r\n', 'isspace')
801 self.checkequal(False, ' \t\r\na', 'isspace')
802 self.checkraises(TypeError, 'abc', 'isspace', 42)
803
804 def test_isalpha(self):
805 self.checkequal(False, '', 'isalpha')
806 self.checkequal(True, 'a', 'isalpha')
807 self.checkequal(True, 'A', 'isalpha')
808 self.checkequal(False, '\n', 'isalpha')
809 self.checkequal(True, 'abc', 'isalpha')
810 self.checkequal(False, 'aBc123', 'isalpha')
811 self.checkequal(False, 'abc\n', 'isalpha')
812 self.checkraises(TypeError, 'abc', 'isalpha', 42)
813
814 def test_isalnum(self):
815 self.checkequal(False, '', 'isalnum')
816 self.checkequal(True, 'a', 'isalnum')
817 self.checkequal(True, 'A', 'isalnum')
818 self.checkequal(False, '\n', 'isalnum')
819 self.checkequal(True, '123abc456', 'isalnum')
820 self.checkequal(True, 'a1b3c', 'isalnum')
821 self.checkequal(False, 'aBc000 ', 'isalnum')
822 self.checkequal(False, 'abc\n', 'isalnum')
823 self.checkraises(TypeError, 'abc', 'isalnum', 42)
824
825 def test_isdigit(self):
826 self.checkequal(False, '', 'isdigit')
827 self.checkequal(False, 'a', 'isdigit')
828 self.checkequal(True, '0', 'isdigit')
829 self.checkequal(True, '0123456789', 'isdigit')
830 self.checkequal(False, '0123456789a', 'isdigit')
831
832 self.checkraises(TypeError, 'abc', 'isdigit', 42)
833
834 def test_title(self):
835 self.checkequal(' Hello ', ' hello ', 'title')
836 self.checkequal('Hello ', 'hello ', 'title')
837 self.checkequal('Hello ', 'Hello ', 'title')
838 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
839 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
840 self.checkequal('Getint', "getInt", 'title')
841 self.checkraises(TypeError, 'hello', 'title', 42)
842
843 def test_splitlines(self):
844 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
845 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
846 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
847 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
848 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
849 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
850 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
851
852 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
853
854 def test_startswith(self):
855 self.checkequal(True, 'hello', 'startswith', 'he')
856 self.checkequal(True, 'hello', 'startswith', 'hello')
857 self.checkequal(False, 'hello', 'startswith', 'hello world')
858 self.checkequal(True, 'hello', 'startswith', '')
859 self.checkequal(False, 'hello', 'startswith', 'ello')
860 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
861 self.checkequal(True, 'hello', 'startswith', 'o', 4)
862 self.checkequal(False, 'hello', 'startswith', 'o', 5)
863 self.checkequal(True, 'hello', 'startswith', '', 5)
864 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
865 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
866 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
867 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
868
869 # test negative indices
870 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
871 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
872 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
873 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
874 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
875 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
876 self.checkequal(False, 'hello', 'startswith', 'o', -2)
877 self.checkequal(True, 'hello', 'startswith', 'o', -1)
878 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
879 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
880
881 self.checkraises(TypeError, 'hello', 'startswith')
882 self.checkraises(TypeError, 'hello', 'startswith', 42)
883
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000884 # test tuple arguments
885 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
886 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
887 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
888 self.checkequal(False, 'hello', 'startswith', ())
889 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
890 'rld', 'lowo'), 3)
891 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
892 'rld'), 3)
893 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
894 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
895 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
896
897 self.checkraises(TypeError, 'hello', 'startswith', (42,))
898
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000899 def test_endswith(self):
900 self.checkequal(True, 'hello', 'endswith', 'lo')
901 self.checkequal(False, 'hello', 'endswith', 'he')
902 self.checkequal(True, 'hello', 'endswith', '')
903 self.checkequal(False, 'hello', 'endswith', 'hello world')
904 self.checkequal(False, 'helloworld', 'endswith', 'worl')
905 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
906 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
907 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
908 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
909 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
910 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
911 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
912 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
913 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
914
915 # test negative indices
916 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
917 self.checkequal(False, 'hello', 'endswith', 'he', -2)
918 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
919 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
920 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
921 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
922 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
923 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
924 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
925 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
926 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
927 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
928 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
929
930 self.checkraises(TypeError, 'hello', 'endswith')
931 self.checkraises(TypeError, 'hello', 'endswith', 42)
932
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000933 # test tuple arguments
934 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
935 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
936 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
937 self.checkequal(False, 'hello', 'endswith', ())
938 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
939 'rld', 'lowo'), 3)
940 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
941 'rld'), 3, -1)
942 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
943 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
944 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
945
946 self.checkraises(TypeError, 'hello', 'endswith', (42,))
947
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000948 def test___contains__(self):
949 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
950 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
951 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
952 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
953 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
954 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
955 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
956 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
957 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
958
959 def test_subscript(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000960 self.checkequal('a', 'abc', '__getitem__', 0)
961 self.checkequal('c', 'abc', '__getitem__', -1)
962 self.checkequal('a', 'abc', '__getitem__', 0)
963 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
964 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
965 self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
966 self.checkequal('', 'abc', '__getitem__', slice(0, 0))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000967
968 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
969
970 def test_slice(self):
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000971 self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
972 self.checkequal('abc', 'abc', '__getitem__', slice(0, 3))
973 self.checkequal('ab', 'abc', '__getitem__', slice(0, 2))
974 self.checkequal('bc', 'abc', '__getitem__', slice(1, 3))
975 self.checkequal('b', 'abc', '__getitem__', slice(1, 2))
976 self.checkequal('', 'abc', '__getitem__', slice(2, 2))
977 self.checkequal('', 'abc', '__getitem__', slice(1000, 1000))
978 self.checkequal('', 'abc', '__getitem__', slice(2000, 1000))
979 self.checkequal('', 'abc', '__getitem__', slice(2, 1))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000980
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000981 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000982
Thomas Woutersed03b412007-08-28 21:37:11 +0000983 def test_extended_getslice(self):
984 # Test extended slicing by comparing with list slicing.
985 s = string.ascii_letters + string.digits
986 indices = (0, None, 1, 3, 41, -1, -2, -37)
987 for start in indices:
988 for stop in indices:
989 # Skip step 0 (invalid)
990 for step in indices[1:]:
991 L = list(s)[start:stop:step]
992 self.checkequal("".join(L), s, '__getitem__',
993 slice(start, stop, step))
994
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000995 def test_mul(self):
996 self.checkequal('', 'abc', '__mul__', -1)
997 self.checkequal('', 'abc', '__mul__', 0)
998 self.checkequal('abc', 'abc', '__mul__', 1)
999 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
1000 self.checkraises(TypeError, 'abc', '__mul__')
1001 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +00001002 # XXX: on a 64-bit system, this doesn't raise an overflow error,
1003 # but either raises a MemoryError, or succeeds (if you have 54TiB)
1004 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001005
1006 def test_join(self):
1007 # join now works with any sequence type
1008 # moved here, because the argument order is
1009 # different in string.join (see the test in
1010 # test.test_string.StringTest.test_join)
1011 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
1012 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
1014 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001015 self.checkequal('w x y z', ' ', 'join', Sequence())
1016 self.checkequal('abc', 'a', 'join', ('abc',))
1017 self.checkequal('z', 'a', 'join', UserList(['z']))
Walter Dörwald67e83882007-05-05 12:26:27 +00001018 self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c'])
Guido van Rossum98297ee2007-11-06 21:34:58 +00001019 self.assertRaises(TypeError, '.'.join, ['a', 'b', 3])
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001020 for i in [5, 25, 125]:
1021 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1022 ['a' * i] * i)
1023 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1024 ('a' * i,) * i)
1025
Guido van Rossum98297ee2007-11-06 21:34:58 +00001026 #self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1())
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001027 self.checkequal('a b c', ' ', 'join', BadSeq2())
1028
1029 self.checkraises(TypeError, ' ', 'join')
1030 self.checkraises(TypeError, ' ', 'join', 7)
Guido van Rossumf1044292007-09-27 18:01:22 +00001031 self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()])
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001032 try:
1033 def f():
1034 yield 4 + ""
1035 self.fixtype(' ').join(f())
Guido van Rossumb940e112007-01-10 16:19:56 +00001036 except TypeError as e:
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001037 if '+' not in str(e):
1038 self.fail('join() ate exception message')
1039 else:
1040 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001041
1042 def test_formatting(self):
1043 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1044 self.checkequal('+10+', '+%d+', '__mod__', 10)
1045 self.checkequal('a', "%c", '__mod__', "a")
1046 self.checkequal('a', "%c", '__mod__', "a")
1047 self.checkequal('"', "%c", '__mod__', 34)
1048 self.checkequal('$', "%c", '__mod__', 36)
1049 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001050 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001051
1052 for ordinal in (-100, 0x200000):
1053 # unicode raises ValueError, str raises OverflowError
1054 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1055
Christian Heimesa612dc02008-02-24 13:08:18 +00001056 longvalue = sys.maxsize + 10
1057 slongvalue = str(longvalue)
1058 if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001059 self.checkequal(' 42', '%3ld', '__mod__', 42)
Christian Heimesa612dc02008-02-24 13:08:18 +00001060 self.checkequal('42', '%d', '__mod__', 42.0)
1061 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1062 self.checkcall('%d', '__mod__', float(longvalue))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001063 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001064 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001065
1066 self.checkraises(TypeError, 'abc', '__mod__')
1067 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1068 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1069 self.checkraises(TypeError, '%c', '__mod__', (None,))
1070 self.checkraises(ValueError, '%(foo', '__mod__', {})
1071 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
Christian Heimesa612dc02008-02-24 13:08:18 +00001072 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
1073 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001074
1075 # argument names with properly nested brackets are supported
1076 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1077
1078 # 100 is a magic number in PyUnicode_Format, this forces a resize
1079 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1080
1081 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1082 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1083 self.checkraises(ValueError, '%10', '__mod__', (42,))
1084
1085 def test_floatformatting(self):
1086 # float formatting
Guido van Rossum805365e2007-05-07 22:24:25 +00001087 for prec in range(100):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001088 format = '%%.%if' % prec
1089 value = 0.01
Guido van Rossum805365e2007-05-07 22:24:25 +00001090 for x in range(60):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001091 value = value * 3.141592655 / 3.0 * 10.0
1092 # The formatfloat() code in stringobject.c and
1093 # unicodeobject.c uses a 120 byte buffer and switches from
1094 # 'f' formatting to 'g' at precision 50, so we expect
1095 # OverflowErrors for the ranges x < 50 and prec >= 67.
1096 if x < 50 and prec >= 67:
1097 self.checkraises(OverflowError, format, "__mod__", value)
1098 else:
1099 self.checkcall(format, "__mod__", value)
1100
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101 def test_inplace_rewrites(self):
1102 # Check that strings don't copy and modify cached single-character strings
1103 self.checkequal('a', 'A', 'lower')
1104 self.checkequal(True, 'A', 'isupper')
1105 self.checkequal('A', 'a', 'upper')
1106 self.checkequal(True, 'a', 'islower')
1107
1108 self.checkequal('a', 'A', 'replace', 'A', 'a')
1109 self.checkequal(True, 'A', 'isupper')
1110
1111 self.checkequal('A', 'a', 'capitalize')
1112 self.checkequal(True, 'a', 'islower')
1113
1114 self.checkequal('A', 'a', 'swapcase')
1115 self.checkequal(True, 'a', 'islower')
1116
1117 self.checkequal('A', 'a', 'title')
1118 self.checkequal(True, 'a', 'islower')
1119
1120 def test_partition(self):
1121
1122 self.checkequal(('this is the par', 'ti', 'tion method'),
1123 'this is the partition method', 'partition', 'ti')
1124
1125 # from raymond's original specification
1126 S = 'http://www.python.org'
1127 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1128 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1129 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1130 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1131
1132 self.checkraises(ValueError, S, 'partition', '')
1133 self.checkraises(TypeError, S, 'partition', None)
1134
1135 def test_rpartition(self):
1136
1137 self.checkequal(('this is the rparti', 'ti', 'on method'),
1138 'this is the rpartition method', 'rpartition', 'ti')
1139
1140 # from raymond's original specification
1141 S = 'http://www.python.org'
1142 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001143 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001144 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1145 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1146
1147 self.checkraises(ValueError, S, 'rpartition', '')
1148 self.checkraises(TypeError, S, 'rpartition', None)
1149
Walter Dörwald57d88e52004-08-26 16:53:04 +00001150
Walter Dörwald57d88e52004-08-26 16:53:04 +00001151class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001152 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001153
1154 def test_bug1001011(self):
1155 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001156 # involving a subclass.
1157 # Make sure that it is of the appropriate type.
1158 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001159 t = self.type2test
1160 class subclass(t):
1161 pass
1162 s1 = subclass("abcd")
1163 s2 = t().join([s1])
1164 self.assert_(s1 is not s2)
1165 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001166
1167 s1 = t("abcd")
1168 s2 = t().join([s1])
1169 self.assert_(s1 is s2)
1170
1171 # Should also test mixed-type join.
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001172 if t is str:
Tim Peters108f1372004-08-27 05:36:07 +00001173 s1 = subclass("abcd")
1174 s2 = "".join([s1])
1175 self.assert_(s1 is not s2)
1176 self.assert_(type(s2) is t)
1177
1178 s1 = t("abcd")
1179 s2 = "".join([s1])
1180 self.assert_(s1 is s2)
1181
Guido van Rossum98297ee2007-11-06 21:34:58 +00001182## elif t is str8:
1183## s1 = subclass("abcd")
1184## s2 = "".join([s1])
1185## self.assert_(s1 is not s2)
1186## self.assert_(type(s2) is str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001187
Guido van Rossum98297ee2007-11-06 21:34:58 +00001188## s1 = t("abcd")
1189## s2 = "".join([s1])
1190## self.assert_(s1 is not s2)
1191## self.assert_(type(s2) is str) # promotes!
Tim Peters108f1372004-08-27 05:36:07 +00001192
1193 else:
1194 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)