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