blob: 8f16f20e56e22473aab5514e820ef1dec8abe1f2 [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)
255
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000256 # by a char
257 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
258 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
259 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
260 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
261 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
262 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
263 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
264 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
265 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
266
267 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000268 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000269 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
270 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
271 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
272 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
273 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
274 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000275 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
276
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000277 # mixed use of str and unicode
278 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
279
280 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000281 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
282
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000283 def test_rsplit(self):
284 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
285 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000286
287 # by whitespace
288 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000289 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
290 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
291 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
292 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
293 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000294 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000295
296 # by a char
297 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
298 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
299 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
300 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
301 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
302 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
303 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
304 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
305 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
306
307 # by string
308 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
309 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
310 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
311 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
312 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
313 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
314 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
315 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
316
317 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000318 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000319
320 # argument type
321 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000322
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000323 def test_strip(self):
324 self.checkequal('hello', ' hello ', 'strip')
325 self.checkequal('hello ', ' hello ', 'lstrip')
326 self.checkequal(' hello', ' hello ', 'rstrip')
327 self.checkequal('hello', 'hello', 'strip')
328
Neal Norwitzffe33b72003-04-10 22:35:32 +0000329 # strip/lstrip/rstrip with None arg
330 self.checkequal('hello', ' hello ', 'strip', None)
331 self.checkequal('hello ', ' hello ', 'lstrip', None)
332 self.checkequal(' hello', ' hello ', 'rstrip', None)
333 self.checkequal('hello', 'hello', 'strip', None)
334
335 # strip/lstrip/rstrip with str arg
336 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
337 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
338 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
339 self.checkequal('hello', 'hello', 'strip', 'xyz')
340
341 # strip/lstrip/rstrip with unicode arg
342 if test_support.have_unicode:
343 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
344 'strip', unicode('xyz', 'ascii'))
345 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
346 'lstrip', unicode('xyz', 'ascii'))
347 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
348 'rstrip', unicode('xyz', 'ascii'))
349 self.checkequal(unicode('hello', 'ascii'), 'hello',
350 'strip', unicode('xyz', 'ascii'))
351
352 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
353 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
354 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
355
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000356 def test_ljust(self):
357 self.checkequal('abc ', 'abc', 'ljust', 10)
358 self.checkequal('abc ', 'abc', 'ljust', 6)
359 self.checkequal('abc', 'abc', 'ljust', 3)
360 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000361 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000362 self.checkraises(TypeError, 'abc', 'ljust')
363
364 def test_rjust(self):
365 self.checkequal(' abc', 'abc', 'rjust', 10)
366 self.checkequal(' abc', 'abc', 'rjust', 6)
367 self.checkequal('abc', 'abc', 'rjust', 3)
368 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000369 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000370 self.checkraises(TypeError, 'abc', 'rjust')
371
372 def test_center(self):
373 self.checkequal(' abc ', 'abc', 'center', 10)
374 self.checkequal(' abc ', 'abc', 'center', 6)
375 self.checkequal('abc', 'abc', 'center', 3)
376 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000377 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000378 self.checkraises(TypeError, 'abc', 'center')
379
380 def test_swapcase(self):
381 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
382
383 self.checkraises(TypeError, 'hello', 'swapcase', 42)
384
385 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000386 EQ = self.checkequal
387
388 # Operations on the empty string
389 EQ("", "", "replace", "", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000390
391 #EQ("A", "", "replace", "", "A")
392 # That was the correct result; this is the result we actually get
Tim Petersf4049082006-05-24 21:00:45 +0000393 # now (for str, but not for unicode):
394 #EQ("", "", "replace", "", "A")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000395
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000396 EQ("", "", "replace", "A", "")
397 EQ("", "", "replace", "A", "A")
398 EQ("", "", "replace", "", "", 100)
399 EQ("", "", "replace", "", "", sys.maxint)
400
401 # interleave (from=="", 'to' gets inserted everywhere)
402 EQ("A", "A", "replace", "", "")
403 EQ("*A*", "A", "replace", "", "*")
404 EQ("*1A*1", "A", "replace", "", "*1")
405 EQ("*-#A*-#", "A", "replace", "", "*-#")
406 EQ("*-A*-A*-", "AA", "replace", "", "*-")
407 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
408 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
409 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
410 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
411 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
412 EQ("*-AA", "AA", "replace", "", "*-", 1)
413 EQ("AA", "AA", "replace", "", "*-", 0)
414
415 # single character deletion (from=="A", to=="")
416 EQ("", "A", "replace", "A", "")
417 EQ("", "AAA", "replace", "A", "")
418 EQ("", "AAA", "replace", "A", "", -1)
419 EQ("", "AAA", "replace", "A", "", sys.maxint)
420 EQ("", "AAA", "replace", "A", "", 4)
421 EQ("", "AAA", "replace", "A", "", 3)
422 EQ("A", "AAA", "replace", "A", "", 2)
423 EQ("AA", "AAA", "replace", "A", "", 1)
424 EQ("AAA", "AAA", "replace", "A", "", 0)
425 EQ("", "AAAAAAAAAA", "replace", "A", "")
426 EQ("BCD", "ABACADA", "replace", "A", "")
427 EQ("BCD", "ABACADA", "replace", "A", "", -1)
428 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
429 EQ("BCD", "ABACADA", "replace", "A", "", 5)
430 EQ("BCD", "ABACADA", "replace", "A", "", 4)
431 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
432 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
433 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
434 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
435 EQ("BCD", "ABCAD", "replace", "A", "")
436 EQ("BCD", "ABCADAA", "replace", "A", "")
437 EQ("BCD", "BCD", "replace", "A", "")
438 EQ("*************", "*************", "replace", "A", "")
439 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
440
441 # substring deletion (from=="the", to=="")
442 EQ("", "the", "replace", "the", "")
443 EQ("ater", "theater", "replace", "the", "")
444 EQ("", "thethe", "replace", "the", "")
445 EQ("", "thethethethe", "replace", "the", "")
446 EQ("aaaa", "theatheatheathea", "replace", "the", "")
447 EQ("that", "that", "replace", "the", "")
448 EQ("thaet", "thaet", "replace", "the", "")
449 EQ("here and re", "here and there", "replace", "the", "")
450 EQ("here and re and re", "here and there and there",
451 "replace", "the", "", sys.maxint)
452 EQ("here and re and re", "here and there and there",
453 "replace", "the", "", -1)
454 EQ("here and re and re", "here and there and there",
455 "replace", "the", "", 3)
456 EQ("here and re and re", "here and there and there",
457 "replace", "the", "", 2)
458 EQ("here and re and there", "here and there and there",
459 "replace", "the", "", 1)
460 EQ("here and there and there", "here and there and there",
461 "replace", "the", "", 0)
462 EQ("here and re and re", "here and there and there", "replace", "the", "")
463
464 EQ("abc", "abc", "replace", "the", "")
465 EQ("abcdefg", "abcdefg", "replace", "the", "")
466
467 # substring deletion (from=="bob", to=="")
468 EQ("bob", "bbobob", "replace", "bob", "")
469 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
470 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
471 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000472
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000473 # single character replace in place (len(from)==len(to)==1)
474 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
475 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
476 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
477 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
478 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
479 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
480 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
481 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
482
483 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
484 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
485 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
486 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
487 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
488
489 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000490
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000491 # substring replace in place (len(from)==len(to) > 1)
492 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
493 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
494 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
495 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
496 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
497 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
498 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
499 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
500 EQ("cobob", "bobob", "replace", "bob", "cob")
501 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
502 EQ("bobob", "bobob", "replace", "bot", "bot")
503
504 # replace single character (len(from)==1, len(to)>1)
505 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
506 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
507 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
508 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
509 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
510 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
511 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
512
513 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
514
515 # replace substring (len(from)>1, len(to)!=len(from))
516 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
517 "replace", "spam", "ham")
518 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
519 "replace", "spam", "ham", sys.maxint)
520 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
521 "replace", "spam", "ham", -1)
522 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
523 "replace", "spam", "ham", 4)
524 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
525 "replace", "spam", "ham", 3)
526 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
527 "replace", "spam", "ham", 2)
528 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
529 "replace", "spam", "ham", 1)
530 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
531 "replace", "spam", "ham", 0)
532
533 EQ("bobob", "bobobob", "replace", "bobob", "bob")
534 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
535 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000536
537 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000538 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
539 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
540 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
541 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
542 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
543 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
544 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
545 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
546 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
547 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
548 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
549 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
550 self.checkequal('', '', 'replace', '', '')
551 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
552 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
553 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
554 # MemoryError due to empty result (platform malloc issue when requesting
555 # 0 bytes).
556 self.checkequal('', '123', 'replace', '123', '')
557 self.checkequal('', '123123', 'replace', '123', '')
558 self.checkequal('x', '123x123', 'replace', '123', '')
559
560 self.checkraises(TypeError, 'hello', 'replace')
561 self.checkraises(TypeError, 'hello', 'replace', 42)
562 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
563 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
564
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000565 def test_replace_overflow(self):
566 # Check for overflow checking on 32 bit machines
567 if sys.maxint != 2147483647:
568 return
569 A2_16 = "A" * (2**16)
570 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
571 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
572 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000573
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000574 def test_zfill(self):
575 self.checkequal('123', '123', 'zfill', 2)
576 self.checkequal('123', '123', 'zfill', 3)
577 self.checkequal('0123', '123', 'zfill', 4)
578 self.checkequal('+123', '+123', 'zfill', 3)
579 self.checkequal('+123', '+123', 'zfill', 4)
580 self.checkequal('+0123', '+123', 'zfill', 5)
581 self.checkequal('-123', '-123', 'zfill', 3)
582 self.checkequal('-123', '-123', 'zfill', 4)
583 self.checkequal('-0123', '-123', 'zfill', 5)
584 self.checkequal('000', '', 'zfill', 3)
585 self.checkequal('34', '34', 'zfill', 1)
586 self.checkequal('0034', '34', 'zfill', 4)
587
588 self.checkraises(TypeError, '123', 'zfill')
589
590class MixinStrUnicodeUserStringTest:
591 # additional tests that only work for
592 # stringlike objects, i.e. str, unicode, UserString
593 # (but not the string module)
594
595 def test_islower(self):
596 self.checkequal(False, '', 'islower')
597 self.checkequal(True, 'a', 'islower')
598 self.checkequal(False, 'A', 'islower')
599 self.checkequal(False, '\n', 'islower')
600 self.checkequal(True, 'abc', 'islower')
601 self.checkequal(False, 'aBc', 'islower')
602 self.checkequal(True, 'abc\n', 'islower')
603 self.checkraises(TypeError, 'abc', 'islower', 42)
604
605 def test_isupper(self):
606 self.checkequal(False, '', 'isupper')
607 self.checkequal(False, 'a', 'isupper')
608 self.checkequal(True, 'A', 'isupper')
609 self.checkequal(False, '\n', 'isupper')
610 self.checkequal(True, 'ABC', 'isupper')
611 self.checkequal(False, 'AbC', 'isupper')
612 self.checkequal(True, 'ABC\n', 'isupper')
613 self.checkraises(TypeError, 'abc', 'isupper', 42)
614
615 def test_istitle(self):
616 self.checkequal(False, '', 'istitle')
617 self.checkequal(False, 'a', 'istitle')
618 self.checkequal(True, 'A', 'istitle')
619 self.checkequal(False, '\n', 'istitle')
620 self.checkequal(True, 'A Titlecased Line', 'istitle')
621 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
622 self.checkequal(True, 'A Titlecased, Line', 'istitle')
623 self.checkequal(False, 'Not a capitalized String', 'istitle')
624 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
625 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
626 self.checkequal(False, 'NOT', 'istitle')
627 self.checkraises(TypeError, 'abc', 'istitle', 42)
628
629 def test_isspace(self):
630 self.checkequal(False, '', 'isspace')
631 self.checkequal(False, 'a', 'isspace')
632 self.checkequal(True, ' ', 'isspace')
633 self.checkequal(True, '\t', 'isspace')
634 self.checkequal(True, '\r', 'isspace')
635 self.checkequal(True, '\n', 'isspace')
636 self.checkequal(True, ' \t\r\n', 'isspace')
637 self.checkequal(False, ' \t\r\na', 'isspace')
638 self.checkraises(TypeError, 'abc', 'isspace', 42)
639
640 def test_isalpha(self):
641 self.checkequal(False, '', 'isalpha')
642 self.checkequal(True, 'a', 'isalpha')
643 self.checkequal(True, 'A', 'isalpha')
644 self.checkequal(False, '\n', 'isalpha')
645 self.checkequal(True, 'abc', 'isalpha')
646 self.checkequal(False, 'aBc123', 'isalpha')
647 self.checkequal(False, 'abc\n', 'isalpha')
648 self.checkraises(TypeError, 'abc', 'isalpha', 42)
649
650 def test_isalnum(self):
651 self.checkequal(False, '', 'isalnum')
652 self.checkequal(True, 'a', 'isalnum')
653 self.checkequal(True, 'A', 'isalnum')
654 self.checkequal(False, '\n', 'isalnum')
655 self.checkequal(True, '123abc456', 'isalnum')
656 self.checkequal(True, 'a1b3c', 'isalnum')
657 self.checkequal(False, 'aBc000 ', 'isalnum')
658 self.checkequal(False, 'abc\n', 'isalnum')
659 self.checkraises(TypeError, 'abc', 'isalnum', 42)
660
661 def test_isdigit(self):
662 self.checkequal(False, '', 'isdigit')
663 self.checkequal(False, 'a', 'isdigit')
664 self.checkequal(True, '0', 'isdigit')
665 self.checkequal(True, '0123456789', 'isdigit')
666 self.checkequal(False, '0123456789a', 'isdigit')
667
668 self.checkraises(TypeError, 'abc', 'isdigit', 42)
669
670 def test_title(self):
671 self.checkequal(' Hello ', ' hello ', 'title')
672 self.checkequal('Hello ', 'hello ', 'title')
673 self.checkequal('Hello ', 'Hello ', 'title')
674 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
675 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
676 self.checkequal('Getint', "getInt", 'title')
677 self.checkraises(TypeError, 'hello', 'title', 42)
678
679 def test_splitlines(self):
680 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
681 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
682 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
683 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
684 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
685 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
686 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
687
688 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
689
690 def test_startswith(self):
691 self.checkequal(True, 'hello', 'startswith', 'he')
692 self.checkequal(True, 'hello', 'startswith', 'hello')
693 self.checkequal(False, 'hello', 'startswith', 'hello world')
694 self.checkequal(True, 'hello', 'startswith', '')
695 self.checkequal(False, 'hello', 'startswith', 'ello')
696 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
697 self.checkequal(True, 'hello', 'startswith', 'o', 4)
698 self.checkequal(False, 'hello', 'startswith', 'o', 5)
699 self.checkequal(True, 'hello', 'startswith', '', 5)
700 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
701 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
702 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
703 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
704
705 # test negative indices
706 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
707 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
708 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
709 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
710 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
711 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
712 self.checkequal(False, 'hello', 'startswith', 'o', -2)
713 self.checkequal(True, 'hello', 'startswith', 'o', -1)
714 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
715 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
716
717 self.checkraises(TypeError, 'hello', 'startswith')
718 self.checkraises(TypeError, 'hello', 'startswith', 42)
719
720 def test_endswith(self):
721 self.checkequal(True, 'hello', 'endswith', 'lo')
722 self.checkequal(False, 'hello', 'endswith', 'he')
723 self.checkequal(True, 'hello', 'endswith', '')
724 self.checkequal(False, 'hello', 'endswith', 'hello world')
725 self.checkequal(False, 'helloworld', 'endswith', 'worl')
726 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
727 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
728 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
729 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
730 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
731 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
732 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
733 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
734 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
735
736 # test negative indices
737 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
738 self.checkequal(False, 'hello', 'endswith', 'he', -2)
739 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
740 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
741 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
742 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
743 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
744 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
745 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
746 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
747 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
748 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
749 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
750
751 self.checkraises(TypeError, 'hello', 'endswith')
752 self.checkraises(TypeError, 'hello', 'endswith', 42)
753
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000754 def test___contains__(self):
755 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
756 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
757 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
758 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
759 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
760 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
761 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
762 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
763 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
764
765 def test_subscript(self):
766 self.checkequal(u'a', 'abc', '__getitem__', 0)
767 self.checkequal(u'c', 'abc', '__getitem__', -1)
768 self.checkequal(u'a', 'abc', '__getitem__', 0L)
769 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
770 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
771 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
772 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
773 # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice)
774
775 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
776
777 def test_slice(self):
778 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
779 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
780 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
781 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
782 self.checkequal('b', 'abc', '__getslice__', 1, 2)
783 self.checkequal('', 'abc', '__getslice__', 2, 2)
784 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
785 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
786 self.checkequal('', 'abc', '__getslice__', 2, 1)
787 # FIXME What about negative indizes? This is handled differently by [] and __getslice__
788
789 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
790
791 def test_mul(self):
792 self.checkequal('', 'abc', '__mul__', -1)
793 self.checkequal('', 'abc', '__mul__', 0)
794 self.checkequal('abc', 'abc', '__mul__', 1)
795 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
796 self.checkraises(TypeError, 'abc', '__mul__')
797 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +0000798 # XXX: on a 64-bit system, this doesn't raise an overflow error,
799 # but either raises a MemoryError, or succeeds (if you have 54TiB)
800 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000801
802 def test_join(self):
803 # join now works with any sequence type
804 # moved here, because the argument order is
805 # different in string.join (see the test in
806 # test.test_string.StringTest.test_join)
807 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
808 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
809 self.checkequal('w x y z', ' ', 'join', Sequence())
810 self.checkequal('abc', 'a', 'join', ('abc',))
811 self.checkequal('z', 'a', 'join', UserList(['z']))
812 if test_support.have_unicode:
813 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
814 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
815 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
816 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
817 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
818 for i in [5, 25, 125]:
819 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
820 ['a' * i] * i)
821 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
822 ('a' * i,) * i)
823
824 self.checkraises(TypeError, ' ', 'join', BadSeq1())
825 self.checkequal('a b c', ' ', 'join', BadSeq2())
826
827 self.checkraises(TypeError, ' ', 'join')
828 self.checkraises(TypeError, ' ', 'join', 7)
829 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +0000830 try:
831 def f():
832 yield 4 + ""
833 self.fixtype(' ').join(f())
834 except TypeError, e:
835 if '+' not in str(e):
836 self.fail('join() ate exception message')
837 else:
838 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000839
840 def test_formatting(self):
841 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
842 self.checkequal('+10+', '+%d+', '__mod__', 10)
843 self.checkequal('a', "%c", '__mod__', "a")
844 self.checkequal('a', "%c", '__mod__', "a")
845 self.checkequal('"', "%c", '__mod__', 34)
846 self.checkequal('$', "%c", '__mod__', 36)
847 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +0000848 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000849
850 for ordinal in (-100, 0x200000):
851 # unicode raises ValueError, str raises OverflowError
852 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
853
854 self.checkequal(' 42', '%3ld', '__mod__', 42)
855 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +0000856 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000857
858 self.checkraises(TypeError, 'abc', '__mod__')
859 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
860 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
861 self.checkraises(TypeError, '%c', '__mod__', (None,))
862 self.checkraises(ValueError, '%(foo', '__mod__', {})
863 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
864
865 # argument names with properly nested brackets are supported
866 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
867
868 # 100 is a magic number in PyUnicode_Format, this forces a resize
869 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
870
871 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
872 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
873 self.checkraises(ValueError, '%10', '__mod__', (42,))
874
875 def test_floatformatting(self):
876 # float formatting
877 for prec in xrange(100):
878 format = '%%.%if' % prec
879 value = 0.01
880 for x in xrange(60):
881 value = value * 3.141592655 / 3.0 * 10.0
882 # The formatfloat() code in stringobject.c and
883 # unicodeobject.c uses a 120 byte buffer and switches from
884 # 'f' formatting to 'g' at precision 50, so we expect
885 # OverflowErrors for the ranges x < 50 and prec >= 67.
886 if x < 50 and prec >= 67:
887 self.checkraises(OverflowError, format, "__mod__", value)
888 else:
889 self.checkcall(format, "__mod__", value)
890
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000891 def test_inplace_rewrites(self):
892 # Check that strings don't copy and modify cached single-character strings
893 self.checkequal('a', 'A', 'lower')
894 self.checkequal(True, 'A', 'isupper')
895 self.checkequal('A', 'a', 'upper')
896 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +0000897
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000898 self.checkequal('a', 'A', 'replace', 'A', 'a')
899 self.checkequal(True, 'A', 'isupper')
900
901 self.checkequal('A', 'a', 'capitalize')
902 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +0000903
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000904 self.checkequal('A', 'a', 'swapcase')
905 self.checkequal(True, 'a', 'islower')
906
907 self.checkequal('A', 'a', 'title')
908 self.checkequal(True, 'a', 'islower')
909
Fredrik Lundh06a69dd2006-05-26 08:54:28 +0000910 def test_partition(self):
911
912 self.checkequal(('this', ' is ', 'the partition method'),
913 'this is the partition method', 'partition', ' is ')
914
915 # from raymond's original specification
916 S = 'http://www.python.org'
917 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
918 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
919 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
920 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
921
922 self.checkraises(ValueError, S, 'partition', '')
923 self.checkraises(TypeError, S, 'partition', None)
924
Walter Dörwald57d88e52004-08-26 16:53:04 +0000925
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000926class MixinStrStringUserStringTest:
927 # Additional tests for 8bit strings, i.e. str, UserString and
928 # the string module
929
930 def test_maketrans(self):
931 self.assertEqual(
932 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
933 string.maketrans('abc', 'xyz')
934 )
935 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
936
937 def test_translate(self):
938 table = string.maketrans('abc', 'xyz')
939 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
940
941 table = string.maketrans('a', 'A')
942 self.checkequal('Abc', 'abc', 'translate', table)
943 self.checkequal('xyz', 'xyz', 'translate', table)
944 self.checkequal('yz', 'xyz', 'translate', table, 'x')
945 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
946 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +0000947
948
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000949class MixinStrUserStringTest:
950 # Additional tests that only work with
951 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +0000952
Walter Dörwald6eea7892005-07-28 16:49:15 +0000953 if test_support.have_unicode:
954 def test_encoding_decoding(self):
955 codecs = [('rot13', 'uryyb jbeyq'),
956 ('base64', 'aGVsbG8gd29ybGQ=\n'),
957 ('hex', '68656c6c6f20776f726c64'),
958 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
959 for encoding, data in codecs:
960 self.checkequal(data, 'hello world', 'encode', encoding)
961 self.checkequal('hello world', data, 'decode', encoding)
962 # zlib is optional, so we make the test optional too...
963 try:
964 import zlib
965 except ImportError:
966 pass
967 else:
968 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
969 self.checkequal(data, 'hello world', 'encode', 'zlib')
970 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +0000971
Walter Dörwald6eea7892005-07-28 16:49:15 +0000972 self.checkraises(TypeError, 'xyz', 'decode', 42)
973 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +0000974
975
976class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +0000977 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +0000978
979 def test_bug1001011(self):
980 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +0000981 # involving a subclass.
982 # Make sure that it is of the appropriate type.
983 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +0000984 t = self.type2test
985 class subclass(t):
986 pass
987 s1 = subclass("abcd")
988 s2 = t().join([s1])
989 self.assert_(s1 is not s2)
990 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +0000991
992 s1 = t("abcd")
993 s2 = t().join([s1])
994 self.assert_(s1 is s2)
995
996 # Should also test mixed-type join.
997 if t is unicode:
998 s1 = subclass("abcd")
999 s2 = "".join([s1])
1000 self.assert_(s1 is not s2)
1001 self.assert_(type(s2) is t)
1002
1003 s1 = t("abcd")
1004 s2 = "".join([s1])
1005 self.assert_(s1 is s2)
1006
1007 elif t is str:
1008 s1 = subclass("abcd")
1009 s2 = u"".join([s1])
1010 self.assert_(s1 is not s2)
1011 self.assert_(type(s2) is unicode) # promotes!
1012
1013 s1 = t("abcd")
1014 s2 = u"".join([s1])
1015 self.assert_(s1 is not s2)
1016 self.assert_(type(s2) is unicode) # promotes!
1017
1018 else:
1019 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)