blob: ecc41595a0ea09dc3e50af12d536ec26a187bfa5 [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
Walter Dörwald0fd583c2003-02-21 12:53:50 +00005import unittest, string, sys
6from test import test_support
Jeremy Hylton20f41b62000-07-11 03:31:55 +00007from UserList import UserList
8
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):
15 def __init__(self): self.seq = [7, 'hello', 123L]
16
17class BadSeq2(Sequence):
18 def __init__(self): self.seq = ['a', 'b', 'c']
19 def __len__(self): return 8
20
Walter Dörwald0fd583c2003-02-21 12:53:50 +000021class CommonTest(unittest.TestCase):
22 # This testcase contains test that can be used in all
23 # stringlike classes. Currently this is str, unicode
24 # UserString and the string module.
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000025
Walter Dörwald0fd583c2003-02-21 12:53:50 +000026 # The type to be tested
27 # Change in subclasses to change the behaviour of fixtesttype()
28 type2test = None
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000029
Walter Dörwald0fd583c2003-02-21 12:53:50 +000030 # All tests pass their arguments to the testing methods
31 # as str objects. fixtesttype() can be used to propagate
32 # these arguments to the appropriate type
33 def fixtype(self, obj):
34 if isinstance(obj, str):
35 return self.__class__.type2test(obj)
36 elif isinstance(obj, list):
37 return [self.fixtype(x) for x in obj]
38 elif isinstance(obj, tuple):
39 return tuple([self.fixtype(x) for x in obj])
40 elif isinstance(obj, dict):
41 return dict([
42 (self.fixtype(key), self.fixtype(value))
43 for (key, value) in obj.iteritems()
44 ])
45 else:
46 return obj
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000047
Walter Dörwald0fd583c2003-02-21 12:53:50 +000048 # check that object.method(*args) returns result
49 def checkequal(self, result, object, methodname, *args):
50 result = self.fixtype(result)
51 object = self.fixtype(object)
52 args = self.fixtype(args)
53 realresult = getattr(object, methodname)(*args)
54 self.assertEqual(
55 result,
56 realresult
57 )
58 # if the original is returned make sure that
59 # this doesn't happen with subclasses
60 if object == realresult:
61 class subtype(self.__class__.type2test):
62 pass
63 object = subtype(object)
64 realresult = getattr(object, methodname)(*args)
65 self.assert_(object is not realresult)
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000066
Walter Dörwald0fd583c2003-02-21 12:53:50 +000067 # check that object.method(*args) raises exc
68 def checkraises(self, exc, object, methodname, *args):
69 object = self.fixtype(object)
70 args = self.fixtype(args)
71 self.assertRaises(
72 exc,
73 getattr(object, methodname),
74 *args
75 )
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +000076
Walter Dörwald0fd583c2003-02-21 12:53:50 +000077 # call object.method(*args) without any checks
78 def checkcall(self, object, methodname, *args):
79 object = self.fixtype(object)
80 args = self.fixtype(args)
81 getattr(object, methodname)(*args)
82
Raymond Hettinger561fbf12004-10-26 01:52:37 +000083 def test_hash(self):
84 # SF bug 1054139: += optimization was not invalidating cached hash value
85 a = self.type2test('DNSSEC')
86 b = self.type2test('')
87 for c in a:
88 b += c
89 hash(b)
90 self.assertEqual(hash(a), hash(b))
91
Walter Dörwald0fd583c2003-02-21 12:53:50 +000092 def test_capitalize(self):
93 self.checkequal(' hello ', ' hello ', 'capitalize')
94 self.checkequal('Hello ', 'Hello ','capitalize')
95 self.checkequal('Hello ', 'hello ','capitalize')
96 self.checkequal('Aaaa', 'aaaa', 'capitalize')
97 self.checkequal('Aaaa', 'AaAa', 'capitalize')
98
99 self.checkraises(TypeError, 'hello', 'capitalize', 42)
100
101 def test_count(self):
102 self.checkequal(3, 'aaa', 'count', 'a')
103 self.checkequal(0, 'aaa', 'count', 'b')
104 self.checkequal(3, 'aaa', 'count', 'a')
105 self.checkequal(0, 'aaa', 'count', 'b')
106 self.checkequal(3, 'aaa', 'count', 'a')
107 self.checkequal(0, 'aaa', 'count', 'b')
108 self.checkequal(0, 'aaa', 'count', 'b')
109 self.checkequal(1, 'aaa', 'count', 'a', -1)
110 self.checkequal(3, 'aaa', 'count', 'a', -10)
111 self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
112 self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
113
114 self.checkraises(TypeError, 'hello', 'count')
115 self.checkraises(TypeError, 'hello', 'count', 42)
116
Raymond Hettinger57e74472005-02-20 09:54:53 +0000117 # For a variety of combinations,
118 # verify that str.count() matches an equivalent function
119 # replacing all occurrences and then differencing the string lengths
120 charset = ['', 'a', 'b']
121 digits = 7
122 base = len(charset)
123 teststrings = set()
124 for i in xrange(base ** digits):
125 entry = []
126 for j in xrange(digits):
127 i, m = divmod(i, base)
128 entry.append(charset[m])
129 teststrings.add(''.join(entry))
130 teststrings = list(teststrings)
131 for i in teststrings:
132 i = self.fixtype(i)
133 n = len(i)
134 for j in teststrings:
135 r1 = i.count(j)
136 if j:
137 r2, rem = divmod(n - len(i.replace(j, '')), len(j))
138 else:
139 r2, rem = len(i)+1, 0
140 if rem or r1 != r2:
141 self.assertEqual(rem, 0)
142 self.assertEqual(r1, r2)
143
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000144 def test_find(self):
145 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
146 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
147 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
148
149 self.checkraises(TypeError, 'hello', 'find')
150 self.checkraises(TypeError, 'hello', 'find', 42)
151
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000152 # For a variety of combinations,
153 # verify that str.find() matches __contains__
154 # and that the found substring is really at that location
155 charset = ['', 'a', 'b', 'c']
156 digits = 5
157 base = len(charset)
158 teststrings = set()
159 for i in xrange(base ** digits):
160 entry = []
161 for j in xrange(digits):
162 i, m = divmod(i, base)
163 entry.append(charset[m])
164 teststrings.add(''.join(entry))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000165 teststrings = list(teststrings)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000166 for i in teststrings:
167 i = self.fixtype(i)
168 for j in teststrings:
169 loc = i.find(j)
170 r1 = (loc != -1)
171 r2 = j in i
172 if r1 != r2:
173 self.assertEqual(r1, r2)
174 if loc != -1:
175 self.assertEqual(i[loc:loc+len(j)], j)
176
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000177 def test_rfind(self):
178 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
179 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
180 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
181 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
182
183 self.checkraises(TypeError, 'hello', 'rfind')
184 self.checkraises(TypeError, 'hello', 'rfind', 42)
185
186 def test_index(self):
187 self.checkequal(0, 'abcdefghiabc', 'index', '')
188 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
189 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
190 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
191
192 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
193 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
194 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
195 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
196
197 self.checkraises(TypeError, 'hello', 'index')
198 self.checkraises(TypeError, 'hello', 'index', 42)
199
200 def test_rindex(self):
201 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
202 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
203 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
204 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
205
206 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
207 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
208 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
209 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
210 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
211
212 self.checkraises(TypeError, 'hello', 'rindex')
213 self.checkraises(TypeError, 'hello', 'rindex', 42)
214
215 def test_lower(self):
216 self.checkequal('hello', 'HeLLo', 'lower')
217 self.checkequal('hello', 'hello', 'lower')
218 self.checkraises(TypeError, 'hello', 'lower', 42)
219
220 def test_upper(self):
221 self.checkequal('HELLO', 'HeLLo', 'upper')
222 self.checkequal('HELLO', 'HELLO', 'upper')
223 self.checkraises(TypeError, 'hello', 'upper', 42)
224
225 def test_expandtabs(self):
226 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
227 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
228 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
229 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
230 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
231 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
232 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
233
234 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
235
236 def test_split(self):
237 self.checkequal(['this', 'is', 'the', 'split', 'function'],
238 'this is the split function', 'split')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000239
240 # by whitespace
241 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000242 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
243 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
244 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
245 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
246 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
247 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000248
Andrew Dalke984b9712006-05-26 11:11:38 +0000249 self.checkequal([], ' ', 'split')
250 self.checkequal(['a'], ' a ', 'split')
251 self.checkequal(['a', 'b'], ' a b ', 'split')
252 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
253 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
254 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
Andrew Dalke03fb4442006-05-26 11:15:22 +0000255 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
Andrew Dalke984b9712006-05-26 11:11:38 +0000256
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000257 # by a char
258 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
259 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
260 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
261 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
262 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
263 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
264 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
265 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
266 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
267
268 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000269 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000270 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
271 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
272 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
273 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
274 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
275 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000276 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
277
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000278 # mixed use of str and unicode
279 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
280
281 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000282 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
283
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000284 def test_rsplit(self):
285 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
286 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000287
288 # by whitespace
289 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000290 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
291 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
292 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
293 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
294 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000295 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000296
297 # by a char
298 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
299 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
300 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
301 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
302 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
303 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
304 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
305 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
306 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
307
308 # by string
309 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
310 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
311 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
312 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
313 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
314 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
315 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
316 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
317
318 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000319 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000320
321 # argument type
322 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000323
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000324 def test_strip(self):
325 self.checkequal('hello', ' hello ', 'strip')
326 self.checkequal('hello ', ' hello ', 'lstrip')
327 self.checkequal(' hello', ' hello ', 'rstrip')
328 self.checkequal('hello', 'hello', 'strip')
329
Neal Norwitzffe33b72003-04-10 22:35:32 +0000330 # strip/lstrip/rstrip with None arg
331 self.checkequal('hello', ' hello ', 'strip', None)
332 self.checkequal('hello ', ' hello ', 'lstrip', None)
333 self.checkequal(' hello', ' hello ', 'rstrip', None)
334 self.checkequal('hello', 'hello', 'strip', None)
335
336 # strip/lstrip/rstrip with str arg
337 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
338 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
339 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
340 self.checkequal('hello', 'hello', 'strip', 'xyz')
341
342 # strip/lstrip/rstrip with unicode arg
343 if test_support.have_unicode:
344 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
345 'strip', unicode('xyz', 'ascii'))
346 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
347 'lstrip', unicode('xyz', 'ascii'))
348 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
349 'rstrip', unicode('xyz', 'ascii'))
350 self.checkequal(unicode('hello', 'ascii'), 'hello',
351 'strip', unicode('xyz', 'ascii'))
352
353 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
354 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
355 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
356
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000357 def test_ljust(self):
358 self.checkequal('abc ', 'abc', 'ljust', 10)
359 self.checkequal('abc ', 'abc', 'ljust', 6)
360 self.checkequal('abc', 'abc', 'ljust', 3)
361 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000362 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000363 self.checkraises(TypeError, 'abc', 'ljust')
364
365 def test_rjust(self):
366 self.checkequal(' abc', 'abc', 'rjust', 10)
367 self.checkequal(' abc', 'abc', 'rjust', 6)
368 self.checkequal('abc', 'abc', 'rjust', 3)
369 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000370 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000371 self.checkraises(TypeError, 'abc', 'rjust')
372
373 def test_center(self):
374 self.checkequal(' abc ', 'abc', 'center', 10)
375 self.checkequal(' abc ', 'abc', 'center', 6)
376 self.checkequal('abc', 'abc', 'center', 3)
377 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000378 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000379 self.checkraises(TypeError, 'abc', 'center')
380
381 def test_swapcase(self):
382 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
383
384 self.checkraises(TypeError, 'hello', 'swapcase', 42)
385
386 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000387 EQ = self.checkequal
388
389 # Operations on the empty string
390 EQ("", "", "replace", "", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000391
392 #EQ("A", "", "replace", "", "A")
393 # That was the correct result; this is the result we actually get
Tim Petersf4049082006-05-24 21:00:45 +0000394 # now (for str, but not for unicode):
395 #EQ("", "", "replace", "", "A")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000396
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000397 EQ("", "", "replace", "A", "")
398 EQ("", "", "replace", "A", "A")
399 EQ("", "", "replace", "", "", 100)
400 EQ("", "", "replace", "", "", sys.maxint)
401
402 # interleave (from=="", 'to' gets inserted everywhere)
403 EQ("A", "A", "replace", "", "")
404 EQ("*A*", "A", "replace", "", "*")
405 EQ("*1A*1", "A", "replace", "", "*1")
406 EQ("*-#A*-#", "A", "replace", "", "*-#")
407 EQ("*-A*-A*-", "AA", "replace", "", "*-")
408 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
409 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
410 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
411 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
412 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
413 EQ("*-AA", "AA", "replace", "", "*-", 1)
414 EQ("AA", "AA", "replace", "", "*-", 0)
415
416 # single character deletion (from=="A", to=="")
417 EQ("", "A", "replace", "A", "")
418 EQ("", "AAA", "replace", "A", "")
419 EQ("", "AAA", "replace", "A", "", -1)
420 EQ("", "AAA", "replace", "A", "", sys.maxint)
421 EQ("", "AAA", "replace", "A", "", 4)
422 EQ("", "AAA", "replace", "A", "", 3)
423 EQ("A", "AAA", "replace", "A", "", 2)
424 EQ("AA", "AAA", "replace", "A", "", 1)
425 EQ("AAA", "AAA", "replace", "A", "", 0)
426 EQ("", "AAAAAAAAAA", "replace", "A", "")
427 EQ("BCD", "ABACADA", "replace", "A", "")
428 EQ("BCD", "ABACADA", "replace", "A", "", -1)
429 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
430 EQ("BCD", "ABACADA", "replace", "A", "", 5)
431 EQ("BCD", "ABACADA", "replace", "A", "", 4)
432 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
433 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
434 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
435 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
436 EQ("BCD", "ABCAD", "replace", "A", "")
437 EQ("BCD", "ABCADAA", "replace", "A", "")
438 EQ("BCD", "BCD", "replace", "A", "")
439 EQ("*************", "*************", "replace", "A", "")
440 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
441
442 # substring deletion (from=="the", to=="")
443 EQ("", "the", "replace", "the", "")
444 EQ("ater", "theater", "replace", "the", "")
445 EQ("", "thethe", "replace", "the", "")
446 EQ("", "thethethethe", "replace", "the", "")
447 EQ("aaaa", "theatheatheathea", "replace", "the", "")
448 EQ("that", "that", "replace", "the", "")
449 EQ("thaet", "thaet", "replace", "the", "")
450 EQ("here and re", "here and there", "replace", "the", "")
451 EQ("here and re and re", "here and there and there",
452 "replace", "the", "", sys.maxint)
453 EQ("here and re and re", "here and there and there",
454 "replace", "the", "", -1)
455 EQ("here and re and re", "here and there and there",
456 "replace", "the", "", 3)
457 EQ("here and re and re", "here and there and there",
458 "replace", "the", "", 2)
459 EQ("here and re and there", "here and there and there",
460 "replace", "the", "", 1)
461 EQ("here and there and there", "here and there and there",
462 "replace", "the", "", 0)
463 EQ("here and re and re", "here and there and there", "replace", "the", "")
464
465 EQ("abc", "abc", "replace", "the", "")
466 EQ("abcdefg", "abcdefg", "replace", "the", "")
467
468 # substring deletion (from=="bob", to=="")
469 EQ("bob", "bbobob", "replace", "bob", "")
470 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
471 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
472 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000473
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000474 # single character replace in place (len(from)==len(to)==1)
475 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
476 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
477 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
478 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
479 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
480 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
481 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
482 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
483
484 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
485 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
486 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
487 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
488 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
489
490 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000491
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000492 # substring replace in place (len(from)==len(to) > 1)
493 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
494 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
495 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
496 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
497 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
498 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
499 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
500 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
501 EQ("cobob", "bobob", "replace", "bob", "cob")
502 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
503 EQ("bobob", "bobob", "replace", "bot", "bot")
504
505 # replace single character (len(from)==1, len(to)>1)
506 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
507 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
508 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
509 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
510 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
511 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
512 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
513
514 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
515
516 # replace substring (len(from)>1, len(to)!=len(from))
517 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
518 "replace", "spam", "ham")
519 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
520 "replace", "spam", "ham", sys.maxint)
521 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
522 "replace", "spam", "ham", -1)
523 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
524 "replace", "spam", "ham", 4)
525 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
526 "replace", "spam", "ham", 3)
527 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
528 "replace", "spam", "ham", 2)
529 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
530 "replace", "spam", "ham", 1)
531 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
532 "replace", "spam", "ham", 0)
533
534 EQ("bobob", "bobobob", "replace", "bobob", "bob")
535 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
536 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000537
538 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000539 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
540 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
541 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
542 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
543 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
544 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
545 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
546 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
547 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
548 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
549 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
550 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
551 self.checkequal('', '', 'replace', '', '')
552 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
553 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
554 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
555 # MemoryError due to empty result (platform malloc issue when requesting
556 # 0 bytes).
557 self.checkequal('', '123', 'replace', '123', '')
558 self.checkequal('', '123123', 'replace', '123', '')
559 self.checkequal('x', '123x123', 'replace', '123', '')
560
561 self.checkraises(TypeError, 'hello', 'replace')
562 self.checkraises(TypeError, 'hello', 'replace', 42)
563 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
564 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
565
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000566 def test_replace_overflow(self):
567 # Check for overflow checking on 32 bit machines
568 if sys.maxint != 2147483647:
569 return
570 A2_16 = "A" * (2**16)
571 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
572 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
573 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000574
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000575 def test_zfill(self):
576 self.checkequal('123', '123', 'zfill', 2)
577 self.checkequal('123', '123', 'zfill', 3)
578 self.checkequal('0123', '123', 'zfill', 4)
579 self.checkequal('+123', '+123', 'zfill', 3)
580 self.checkequal('+123', '+123', 'zfill', 4)
581 self.checkequal('+0123', '+123', 'zfill', 5)
582 self.checkequal('-123', '-123', 'zfill', 3)
583 self.checkequal('-123', '-123', 'zfill', 4)
584 self.checkequal('-0123', '-123', 'zfill', 5)
585 self.checkequal('000', '', 'zfill', 3)
586 self.checkequal('34', '34', 'zfill', 1)
587 self.checkequal('0034', '34', 'zfill', 4)
588
589 self.checkraises(TypeError, '123', 'zfill')
590
591class MixinStrUnicodeUserStringTest:
592 # additional tests that only work for
593 # stringlike objects, i.e. str, unicode, UserString
594 # (but not the string module)
595
596 def test_islower(self):
597 self.checkequal(False, '', 'islower')
598 self.checkequal(True, 'a', 'islower')
599 self.checkequal(False, 'A', 'islower')
600 self.checkequal(False, '\n', 'islower')
601 self.checkequal(True, 'abc', 'islower')
602 self.checkequal(False, 'aBc', 'islower')
603 self.checkequal(True, 'abc\n', 'islower')
604 self.checkraises(TypeError, 'abc', 'islower', 42)
605
606 def test_isupper(self):
607 self.checkequal(False, '', 'isupper')
608 self.checkequal(False, 'a', 'isupper')
609 self.checkequal(True, 'A', 'isupper')
610 self.checkequal(False, '\n', 'isupper')
611 self.checkequal(True, 'ABC', 'isupper')
612 self.checkequal(False, 'AbC', 'isupper')
613 self.checkequal(True, 'ABC\n', 'isupper')
614 self.checkraises(TypeError, 'abc', 'isupper', 42)
615
616 def test_istitle(self):
617 self.checkequal(False, '', 'istitle')
618 self.checkequal(False, 'a', 'istitle')
619 self.checkequal(True, 'A', 'istitle')
620 self.checkequal(False, '\n', 'istitle')
621 self.checkequal(True, 'A Titlecased Line', 'istitle')
622 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
623 self.checkequal(True, 'A Titlecased, Line', 'istitle')
624 self.checkequal(False, 'Not a capitalized String', 'istitle')
625 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
626 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
627 self.checkequal(False, 'NOT', 'istitle')
628 self.checkraises(TypeError, 'abc', 'istitle', 42)
629
630 def test_isspace(self):
631 self.checkequal(False, '', 'isspace')
632 self.checkequal(False, 'a', 'isspace')
633 self.checkequal(True, ' ', 'isspace')
634 self.checkequal(True, '\t', 'isspace')
635 self.checkequal(True, '\r', 'isspace')
636 self.checkequal(True, '\n', 'isspace')
637 self.checkequal(True, ' \t\r\n', 'isspace')
638 self.checkequal(False, ' \t\r\na', 'isspace')
639 self.checkraises(TypeError, 'abc', 'isspace', 42)
640
641 def test_isalpha(self):
642 self.checkequal(False, '', 'isalpha')
643 self.checkequal(True, 'a', 'isalpha')
644 self.checkequal(True, 'A', 'isalpha')
645 self.checkequal(False, '\n', 'isalpha')
646 self.checkequal(True, 'abc', 'isalpha')
647 self.checkequal(False, 'aBc123', 'isalpha')
648 self.checkequal(False, 'abc\n', 'isalpha')
649 self.checkraises(TypeError, 'abc', 'isalpha', 42)
650
651 def test_isalnum(self):
652 self.checkequal(False, '', 'isalnum')
653 self.checkequal(True, 'a', 'isalnum')
654 self.checkequal(True, 'A', 'isalnum')
655 self.checkequal(False, '\n', 'isalnum')
656 self.checkequal(True, '123abc456', 'isalnum')
657 self.checkequal(True, 'a1b3c', 'isalnum')
658 self.checkequal(False, 'aBc000 ', 'isalnum')
659 self.checkequal(False, 'abc\n', 'isalnum')
660 self.checkraises(TypeError, 'abc', 'isalnum', 42)
661
662 def test_isdigit(self):
663 self.checkequal(False, '', 'isdigit')
664 self.checkequal(False, 'a', 'isdigit')
665 self.checkequal(True, '0', 'isdigit')
666 self.checkequal(True, '0123456789', 'isdigit')
667 self.checkequal(False, '0123456789a', 'isdigit')
668
669 self.checkraises(TypeError, 'abc', 'isdigit', 42)
670
671 def test_title(self):
672 self.checkequal(' Hello ', ' hello ', 'title')
673 self.checkequal('Hello ', 'hello ', 'title')
674 self.checkequal('Hello ', 'Hello ', 'title')
675 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
676 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
677 self.checkequal('Getint', "getInt", 'title')
678 self.checkraises(TypeError, 'hello', 'title', 42)
679
680 def test_splitlines(self):
681 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
682 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
683 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
684 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
685 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
686 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
687 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
688
689 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
690
691 def test_startswith(self):
692 self.checkequal(True, 'hello', 'startswith', 'he')
693 self.checkequal(True, 'hello', 'startswith', 'hello')
694 self.checkequal(False, 'hello', 'startswith', 'hello world')
695 self.checkequal(True, 'hello', 'startswith', '')
696 self.checkequal(False, 'hello', 'startswith', 'ello')
697 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
698 self.checkequal(True, 'hello', 'startswith', 'o', 4)
699 self.checkequal(False, 'hello', 'startswith', 'o', 5)
700 self.checkequal(True, 'hello', 'startswith', '', 5)
701 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
702 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
703 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
704 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
705
706 # test negative indices
707 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
708 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
709 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
710 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
711 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
712 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
713 self.checkequal(False, 'hello', 'startswith', 'o', -2)
714 self.checkequal(True, 'hello', 'startswith', 'o', -1)
715 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
716 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
717
718 self.checkraises(TypeError, 'hello', 'startswith')
719 self.checkraises(TypeError, 'hello', 'startswith', 42)
720
721 def test_endswith(self):
722 self.checkequal(True, 'hello', 'endswith', 'lo')
723 self.checkequal(False, 'hello', 'endswith', 'he')
724 self.checkequal(True, 'hello', 'endswith', '')
725 self.checkequal(False, 'hello', 'endswith', 'hello world')
726 self.checkequal(False, 'helloworld', 'endswith', 'worl')
727 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
728 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
729 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
730 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
731 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
732 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
733 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
734 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
735 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
736
737 # test negative indices
738 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
739 self.checkequal(False, 'hello', 'endswith', 'he', -2)
740 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
741 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
742 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
743 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
744 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
745 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
746 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
747 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
748 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
749 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
750 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
751
752 self.checkraises(TypeError, 'hello', 'endswith')
753 self.checkraises(TypeError, 'hello', 'endswith', 42)
754
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000755 def test___contains__(self):
756 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
757 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
758 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
759 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
760 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
761 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
762 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
763 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
764 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
765
766 def test_subscript(self):
767 self.checkequal(u'a', 'abc', '__getitem__', 0)
768 self.checkequal(u'c', 'abc', '__getitem__', -1)
769 self.checkequal(u'a', 'abc', '__getitem__', 0L)
770 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
771 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
772 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
773 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
774 # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice)
775
776 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
777
778 def test_slice(self):
779 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
780 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
781 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
782 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
783 self.checkequal('b', 'abc', '__getslice__', 1, 2)
784 self.checkequal('', 'abc', '__getslice__', 2, 2)
785 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
786 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
787 self.checkequal('', 'abc', '__getslice__', 2, 1)
788 # FIXME What about negative indizes? This is handled differently by [] and __getslice__
789
790 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
791
792 def test_mul(self):
793 self.checkequal('', 'abc', '__mul__', -1)
794 self.checkequal('', 'abc', '__mul__', 0)
795 self.checkequal('abc', 'abc', '__mul__', 1)
796 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
797 self.checkraises(TypeError, 'abc', '__mul__')
798 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +0000799 # XXX: on a 64-bit system, this doesn't raise an overflow error,
800 # but either raises a MemoryError, or succeeds (if you have 54TiB)
801 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000802
803 def test_join(self):
804 # join now works with any sequence type
805 # moved here, because the argument order is
806 # different in string.join (see the test in
807 # test.test_string.StringTest.test_join)
808 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
809 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
810 self.checkequal('w x y z', ' ', 'join', Sequence())
811 self.checkequal('abc', 'a', 'join', ('abc',))
812 self.checkequal('z', 'a', 'join', UserList(['z']))
813 if test_support.have_unicode:
814 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
815 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
816 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
817 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
818 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
819 for i in [5, 25, 125]:
820 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
821 ['a' * i] * i)
822 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
823 ('a' * i,) * i)
824
825 self.checkraises(TypeError, ' ', 'join', BadSeq1())
826 self.checkequal('a b c', ' ', 'join', BadSeq2())
827
828 self.checkraises(TypeError, ' ', 'join')
829 self.checkraises(TypeError, ' ', 'join', 7)
830 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +0000831 try:
832 def f():
833 yield 4 + ""
834 self.fixtype(' ').join(f())
835 except TypeError, e:
836 if '+' not in str(e):
837 self.fail('join() ate exception message')
838 else:
839 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000840
841 def test_formatting(self):
842 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
843 self.checkequal('+10+', '+%d+', '__mod__', 10)
844 self.checkequal('a', "%c", '__mod__', "a")
845 self.checkequal('a', "%c", '__mod__', "a")
846 self.checkequal('"', "%c", '__mod__', 34)
847 self.checkequal('$', "%c", '__mod__', 36)
848 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +0000849 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000850
851 for ordinal in (-100, 0x200000):
852 # unicode raises ValueError, str raises OverflowError
853 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
854
855 self.checkequal(' 42', '%3ld', '__mod__', 42)
856 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +0000857 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000858
859 self.checkraises(TypeError, 'abc', '__mod__')
860 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
861 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
862 self.checkraises(TypeError, '%c', '__mod__', (None,))
863 self.checkraises(ValueError, '%(foo', '__mod__', {})
864 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
865
866 # argument names with properly nested brackets are supported
867 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
868
869 # 100 is a magic number in PyUnicode_Format, this forces a resize
870 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
871
872 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
873 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
874 self.checkraises(ValueError, '%10', '__mod__', (42,))
875
876 def test_floatformatting(self):
877 # float formatting
878 for prec in xrange(100):
879 format = '%%.%if' % prec
880 value = 0.01
881 for x in xrange(60):
882 value = value * 3.141592655 / 3.0 * 10.0
883 # The formatfloat() code in stringobject.c and
884 # unicodeobject.c uses a 120 byte buffer and switches from
885 # 'f' formatting to 'g' at precision 50, so we expect
886 # OverflowErrors for the ranges x < 50 and prec >= 67.
887 if x < 50 and prec >= 67:
888 self.checkraises(OverflowError, format, "__mod__", value)
889 else:
890 self.checkcall(format, "__mod__", value)
891
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000892 def test_inplace_rewrites(self):
893 # Check that strings don't copy and modify cached single-character strings
894 self.checkequal('a', 'A', 'lower')
895 self.checkequal(True, 'A', 'isupper')
896 self.checkequal('A', 'a', 'upper')
897 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +0000898
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000899 self.checkequal('a', 'A', 'replace', 'A', 'a')
900 self.checkequal(True, 'A', 'isupper')
901
902 self.checkequal('A', 'a', 'capitalize')
903 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +0000904
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000905 self.checkequal('A', 'a', 'swapcase')
906 self.checkequal(True, 'a', 'islower')
907
908 self.checkequal('A', 'a', 'title')
909 self.checkequal(True, 'a', 'islower')
910
Fredrik Lundh06a69dd2006-05-26 08:54:28 +0000911 def test_partition(self):
912
913 self.checkequal(('this', ' is ', 'the partition method'),
914 'this is the partition method', 'partition', ' is ')
915
916 # from raymond's original specification
917 S = 'http://www.python.org'
918 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
919 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
920 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
921 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
922
923 self.checkraises(ValueError, S, 'partition', '')
924 self.checkraises(TypeError, S, 'partition', None)
925
Walter Dörwald57d88e52004-08-26 16:53:04 +0000926
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000927class MixinStrStringUserStringTest:
928 # Additional tests for 8bit strings, i.e. str, UserString and
929 # the string module
930
931 def test_maketrans(self):
932 self.assertEqual(
933 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
934 string.maketrans('abc', 'xyz')
935 )
936 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
937
938 def test_translate(self):
939 table = string.maketrans('abc', 'xyz')
940 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
941
942 table = string.maketrans('a', 'A')
943 self.checkequal('Abc', 'abc', 'translate', table)
944 self.checkequal('xyz', 'xyz', 'translate', table)
945 self.checkequal('yz', 'xyz', 'translate', table, 'x')
946 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
947 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +0000948
949
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000950class MixinStrUserStringTest:
951 # Additional tests that only work with
952 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +0000953
Walter Dörwald6eea7892005-07-28 16:49:15 +0000954 if test_support.have_unicode:
955 def test_encoding_decoding(self):
956 codecs = [('rot13', 'uryyb jbeyq'),
957 ('base64', 'aGVsbG8gd29ybGQ=\n'),
958 ('hex', '68656c6c6f20776f726c64'),
959 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
960 for encoding, data in codecs:
961 self.checkequal(data, 'hello world', 'encode', encoding)
962 self.checkequal('hello world', data, 'decode', encoding)
963 # zlib is optional, so we make the test optional too...
964 try:
965 import zlib
966 except ImportError:
967 pass
968 else:
969 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
970 self.checkequal(data, 'hello world', 'encode', 'zlib')
971 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +0000972
Walter Dörwald6eea7892005-07-28 16:49:15 +0000973 self.checkraises(TypeError, 'xyz', 'decode', 42)
974 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +0000975
976
977class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +0000978 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +0000979
980 def test_bug1001011(self):
981 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +0000982 # involving a subclass.
983 # Make sure that it is of the appropriate type.
984 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +0000985 t = self.type2test
986 class subclass(t):
987 pass
988 s1 = subclass("abcd")
989 s2 = t().join([s1])
990 self.assert_(s1 is not s2)
991 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +0000992
993 s1 = t("abcd")
994 s2 = t().join([s1])
995 self.assert_(s1 is s2)
996
997 # Should also test mixed-type join.
998 if t is unicode:
999 s1 = subclass("abcd")
1000 s2 = "".join([s1])
1001 self.assert_(s1 is not s2)
1002 self.assert_(type(s2) is t)
1003
1004 s1 = t("abcd")
1005 s2 = "".join([s1])
1006 self.assert_(s1 is s2)
1007
1008 elif t is str:
1009 s1 = subclass("abcd")
1010 s2 = u"".join([s1])
1011 self.assert_(s1 is not s2)
1012 self.assert_(type(s2) is unicode) # promotes!
1013
1014 s1 = t("abcd")
1015 s2 = u"".join([s1])
1016 self.assert_(s1 is not s2)
1017 self.assert_(type(s2) is unicode) # promotes!
1018
1019 else:
1020 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)