blob: 489af20a16d53ffdb2511a99faed98e41e386d3c [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)
Andrew Dalke725fe402006-05-26 16:22:52 +0000249 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000250 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000251
Andrew Dalke984b9712006-05-26 11:11:38 +0000252 self.checkequal([], ' ', 'split')
253 self.checkequal(['a'], ' a ', 'split')
254 self.checkequal(['a', 'b'], ' a b ', 'split')
255 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
256 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
257 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
Andrew Dalke03fb4442006-05-26 11:15:22 +0000258 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
Andrew Dalke005aee22006-05-26 12:28:15 +0000259 aaa = ' a '*20
260 self.checkequal(['a']*20, aaa, 'split')
261 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
Andrew Dalke669fa182006-05-26 13:05:55 +0000262 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
Andrew Dalke984b9712006-05-26 11:11:38 +0000263
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000264 # by a char
265 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000266 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000267 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
268 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
269 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
270 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000271 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
272 sys.maxint-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000273 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)
275 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000276 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
277 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000278 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
279
Andrew Dalke005aee22006-05-26 12:28:15 +0000280 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
281 self.checkequal(['a']*15 +['a|a|a|a|a'],
282 ('a|'*20)[:-1], 'split', '|', 15)
283
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000284 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000285 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000286 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
287 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
288 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
289 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000290 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
291 sys.maxint-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000292 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
293 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000294 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000295 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
296 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
297 'split', 'test')
298 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000299 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
300 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
301 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
302 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
303 self.checkequal([''], '', 'split', 'aaa')
304 self.checkequal(['aa'], 'aa', 'split', 'aaa')
Andrew Dalke5cc60092006-05-26 12:31:00 +0000305 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
306 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000307
308 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
309 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
310 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
311 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000312
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000313 # mixed use of str and unicode
314 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
315
316 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000317 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
318
Andrew Dalke005aee22006-05-26 12:28:15 +0000319 # null case
320 self.checkraises(ValueError, 'hello', 'split', '')
321 self.checkraises(ValueError, 'hello', 'split', '', 0)
322
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000323 def test_rsplit(self):
324 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
325 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000326
327 # by whitespace
328 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000329 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
330 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
331 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
332 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000333 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
334 sys.maxint-20)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000335 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000336 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000337 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000338
Andrew Dalke669fa182006-05-26 13:05:55 +0000339 self.checkequal([], ' ', 'rsplit')
340 self.checkequal(['a'], ' a ', 'rsplit')
341 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
342 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
343 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
344 None, 1)
345 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
346 None, 2)
347 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
348 aaa = ' a '*20
349 self.checkequal(['a']*20, aaa, 'rsplit')
350 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
351 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
352
353
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000354 # by a char
355 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
356 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
357 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
358 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
359 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000360 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
361 sys.maxint-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000362 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
363 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
364 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Andrew Dalke669fa182006-05-26 13:05:55 +0000365 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
366 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
367
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000368 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
369
Andrew Dalke669fa182006-05-26 13:05:55 +0000370 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
371 self.checkequal(['a|a|a|a|a']+['a']*15,
372 ('a|'*20)[:-1], 'rsplit', '|', 15)
373
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000374 # by string
375 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
376 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
377 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
378 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
379 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000380 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
381 sys.maxint-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000382 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
383 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
384 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000385 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
386 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
387 'rsplit', 'test')
388 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
389 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
390 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
391 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
392 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
393 self.checkequal([''], '', 'rsplit', 'aaa')
394 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
395 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
396 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
397
398 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
399 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
400 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
401 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000402
403 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000404 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000405
406 # argument type
407 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000408
Andrew Dalke669fa182006-05-26 13:05:55 +0000409 # null case
410 self.checkraises(ValueError, 'hello', 'rsplit', '')
411 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
412
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000413 def test_strip(self):
414 self.checkequal('hello', ' hello ', 'strip')
415 self.checkequal('hello ', ' hello ', 'lstrip')
416 self.checkequal(' hello', ' hello ', 'rstrip')
417 self.checkequal('hello', 'hello', 'strip')
418
Neal Norwitzffe33b72003-04-10 22:35:32 +0000419 # strip/lstrip/rstrip with None arg
420 self.checkequal('hello', ' hello ', 'strip', None)
421 self.checkequal('hello ', ' hello ', 'lstrip', None)
422 self.checkequal(' hello', ' hello ', 'rstrip', None)
423 self.checkequal('hello', 'hello', 'strip', None)
424
425 # strip/lstrip/rstrip with str arg
426 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
427 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
428 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
429 self.checkequal('hello', 'hello', 'strip', 'xyz')
430
431 # strip/lstrip/rstrip with unicode arg
432 if test_support.have_unicode:
433 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
434 'strip', unicode('xyz', 'ascii'))
435 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
436 'lstrip', unicode('xyz', 'ascii'))
437 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
438 'rstrip', unicode('xyz', 'ascii'))
439 self.checkequal(unicode('hello', 'ascii'), 'hello',
440 'strip', unicode('xyz', 'ascii'))
441
442 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
443 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
444 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
445
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000446 def test_ljust(self):
447 self.checkequal('abc ', 'abc', 'ljust', 10)
448 self.checkequal('abc ', 'abc', 'ljust', 6)
449 self.checkequal('abc', 'abc', 'ljust', 3)
450 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000451 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000452 self.checkraises(TypeError, 'abc', 'ljust')
453
454 def test_rjust(self):
455 self.checkequal(' abc', 'abc', 'rjust', 10)
456 self.checkequal(' abc', 'abc', 'rjust', 6)
457 self.checkequal('abc', 'abc', 'rjust', 3)
458 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000459 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000460 self.checkraises(TypeError, 'abc', 'rjust')
461
462 def test_center(self):
463 self.checkequal(' abc ', 'abc', 'center', 10)
464 self.checkequal(' abc ', 'abc', 'center', 6)
465 self.checkequal('abc', 'abc', 'center', 3)
466 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000467 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000468 self.checkraises(TypeError, 'abc', 'center')
469
470 def test_swapcase(self):
471 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
472
473 self.checkraises(TypeError, 'hello', 'swapcase', 42)
474
475 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000476 EQ = self.checkequal
477
478 # Operations on the empty string
479 EQ("", "", "replace", "", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000480
481 #EQ("A", "", "replace", "", "A")
482 # That was the correct result; this is the result we actually get
Tim Petersf4049082006-05-24 21:00:45 +0000483 # now (for str, but not for unicode):
484 #EQ("", "", "replace", "", "A")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000485
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000486 EQ("", "", "replace", "A", "")
487 EQ("", "", "replace", "A", "A")
488 EQ("", "", "replace", "", "", 100)
489 EQ("", "", "replace", "", "", sys.maxint)
490
491 # interleave (from=="", 'to' gets inserted everywhere)
492 EQ("A", "A", "replace", "", "")
493 EQ("*A*", "A", "replace", "", "*")
494 EQ("*1A*1", "A", "replace", "", "*1")
495 EQ("*-#A*-#", "A", "replace", "", "*-#")
496 EQ("*-A*-A*-", "AA", "replace", "", "*-")
497 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
498 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
499 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
500 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
501 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
502 EQ("*-AA", "AA", "replace", "", "*-", 1)
503 EQ("AA", "AA", "replace", "", "*-", 0)
504
505 # single character deletion (from=="A", to=="")
506 EQ("", "A", "replace", "A", "")
507 EQ("", "AAA", "replace", "A", "")
508 EQ("", "AAA", "replace", "A", "", -1)
509 EQ("", "AAA", "replace", "A", "", sys.maxint)
510 EQ("", "AAA", "replace", "A", "", 4)
511 EQ("", "AAA", "replace", "A", "", 3)
512 EQ("A", "AAA", "replace", "A", "", 2)
513 EQ("AA", "AAA", "replace", "A", "", 1)
514 EQ("AAA", "AAA", "replace", "A", "", 0)
515 EQ("", "AAAAAAAAAA", "replace", "A", "")
516 EQ("BCD", "ABACADA", "replace", "A", "")
517 EQ("BCD", "ABACADA", "replace", "A", "", -1)
518 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
519 EQ("BCD", "ABACADA", "replace", "A", "", 5)
520 EQ("BCD", "ABACADA", "replace", "A", "", 4)
521 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
522 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
523 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
524 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
525 EQ("BCD", "ABCAD", "replace", "A", "")
526 EQ("BCD", "ABCADAA", "replace", "A", "")
527 EQ("BCD", "BCD", "replace", "A", "")
528 EQ("*************", "*************", "replace", "A", "")
529 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
530
531 # substring deletion (from=="the", to=="")
532 EQ("", "the", "replace", "the", "")
533 EQ("ater", "theater", "replace", "the", "")
534 EQ("", "thethe", "replace", "the", "")
535 EQ("", "thethethethe", "replace", "the", "")
536 EQ("aaaa", "theatheatheathea", "replace", "the", "")
537 EQ("that", "that", "replace", "the", "")
538 EQ("thaet", "thaet", "replace", "the", "")
539 EQ("here and re", "here and there", "replace", "the", "")
540 EQ("here and re and re", "here and there and there",
541 "replace", "the", "", sys.maxint)
542 EQ("here and re and re", "here and there and there",
543 "replace", "the", "", -1)
544 EQ("here and re and re", "here and there and there",
545 "replace", "the", "", 3)
546 EQ("here and re and re", "here and there and there",
547 "replace", "the", "", 2)
548 EQ("here and re and there", "here and there and there",
549 "replace", "the", "", 1)
550 EQ("here and there and there", "here and there and there",
551 "replace", "the", "", 0)
552 EQ("here and re and re", "here and there and there", "replace", "the", "")
553
554 EQ("abc", "abc", "replace", "the", "")
555 EQ("abcdefg", "abcdefg", "replace", "the", "")
556
557 # substring deletion (from=="bob", to=="")
558 EQ("bob", "bbobob", "replace", "bob", "")
559 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
560 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
561 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000562
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000563 # single character replace in place (len(from)==len(to)==1)
564 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
565 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
566 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
567 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
568 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
569 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
570 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
571 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
572
573 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
574 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
575 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
576 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
577 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
578
579 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000580
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000581 # substring replace in place (len(from)==len(to) > 1)
582 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
583 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
584 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
585 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
586 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
587 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
588 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
589 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
590 EQ("cobob", "bobob", "replace", "bob", "cob")
591 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
592 EQ("bobob", "bobob", "replace", "bot", "bot")
593
594 # replace single character (len(from)==1, len(to)>1)
595 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
596 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
597 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
598 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
599 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
600 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
601 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
602
603 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
604
605 # replace substring (len(from)>1, len(to)!=len(from))
606 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
607 "replace", "spam", "ham")
608 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
609 "replace", "spam", "ham", sys.maxint)
610 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
611 "replace", "spam", "ham", -1)
612 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
613 "replace", "spam", "ham", 4)
614 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
615 "replace", "spam", "ham", 3)
616 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
617 "replace", "spam", "ham", 2)
618 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
619 "replace", "spam", "ham", 1)
620 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
621 "replace", "spam", "ham", 0)
622
623 EQ("bobob", "bobobob", "replace", "bobob", "bob")
624 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
625 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000626
627 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000628 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
629 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
630 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
631 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
632 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
633 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
634 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
635 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
636 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
637 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
638 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
639 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
640 self.checkequal('', '', 'replace', '', '')
641 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
642 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
643 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
644 # MemoryError due to empty result (platform malloc issue when requesting
645 # 0 bytes).
646 self.checkequal('', '123', 'replace', '123', '')
647 self.checkequal('', '123123', 'replace', '123', '')
648 self.checkequal('x', '123x123', 'replace', '123', '')
649
650 self.checkraises(TypeError, 'hello', 'replace')
651 self.checkraises(TypeError, 'hello', 'replace', 42)
652 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
653 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
654
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000655 def test_replace_overflow(self):
656 # Check for overflow checking on 32 bit machines
657 if sys.maxint != 2147483647:
658 return
659 A2_16 = "A" * (2**16)
660 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
661 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
662 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000663
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000664 def test_zfill(self):
665 self.checkequal('123', '123', 'zfill', 2)
666 self.checkequal('123', '123', 'zfill', 3)
667 self.checkequal('0123', '123', 'zfill', 4)
668 self.checkequal('+123', '+123', 'zfill', 3)
669 self.checkequal('+123', '+123', 'zfill', 4)
670 self.checkequal('+0123', '+123', 'zfill', 5)
671 self.checkequal('-123', '-123', 'zfill', 3)
672 self.checkequal('-123', '-123', 'zfill', 4)
673 self.checkequal('-0123', '-123', 'zfill', 5)
674 self.checkequal('000', '', 'zfill', 3)
675 self.checkequal('34', '34', 'zfill', 1)
676 self.checkequal('0034', '34', 'zfill', 4)
677
678 self.checkraises(TypeError, '123', 'zfill')
679
680class MixinStrUnicodeUserStringTest:
681 # additional tests that only work for
682 # stringlike objects, i.e. str, unicode, UserString
683 # (but not the string module)
684
685 def test_islower(self):
686 self.checkequal(False, '', 'islower')
687 self.checkequal(True, 'a', 'islower')
688 self.checkequal(False, 'A', 'islower')
689 self.checkequal(False, '\n', 'islower')
690 self.checkequal(True, 'abc', 'islower')
691 self.checkequal(False, 'aBc', 'islower')
692 self.checkequal(True, 'abc\n', 'islower')
693 self.checkraises(TypeError, 'abc', 'islower', 42)
694
695 def test_isupper(self):
696 self.checkequal(False, '', 'isupper')
697 self.checkequal(False, 'a', 'isupper')
698 self.checkequal(True, 'A', 'isupper')
699 self.checkequal(False, '\n', 'isupper')
700 self.checkequal(True, 'ABC', 'isupper')
701 self.checkequal(False, 'AbC', 'isupper')
702 self.checkequal(True, 'ABC\n', 'isupper')
703 self.checkraises(TypeError, 'abc', 'isupper', 42)
704
705 def test_istitle(self):
706 self.checkequal(False, '', 'istitle')
707 self.checkequal(False, 'a', 'istitle')
708 self.checkequal(True, 'A', 'istitle')
709 self.checkequal(False, '\n', 'istitle')
710 self.checkequal(True, 'A Titlecased Line', 'istitle')
711 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
712 self.checkequal(True, 'A Titlecased, Line', 'istitle')
713 self.checkequal(False, 'Not a capitalized String', 'istitle')
714 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
715 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
716 self.checkequal(False, 'NOT', 'istitle')
717 self.checkraises(TypeError, 'abc', 'istitle', 42)
718
719 def test_isspace(self):
720 self.checkequal(False, '', 'isspace')
721 self.checkequal(False, 'a', 'isspace')
722 self.checkequal(True, ' ', 'isspace')
723 self.checkequal(True, '\t', 'isspace')
724 self.checkequal(True, '\r', 'isspace')
725 self.checkequal(True, '\n', 'isspace')
726 self.checkequal(True, ' \t\r\n', 'isspace')
727 self.checkequal(False, ' \t\r\na', 'isspace')
728 self.checkraises(TypeError, 'abc', 'isspace', 42)
729
730 def test_isalpha(self):
731 self.checkequal(False, '', 'isalpha')
732 self.checkequal(True, 'a', 'isalpha')
733 self.checkequal(True, 'A', 'isalpha')
734 self.checkequal(False, '\n', 'isalpha')
735 self.checkequal(True, 'abc', 'isalpha')
736 self.checkequal(False, 'aBc123', 'isalpha')
737 self.checkequal(False, 'abc\n', 'isalpha')
738 self.checkraises(TypeError, 'abc', 'isalpha', 42)
739
740 def test_isalnum(self):
741 self.checkequal(False, '', 'isalnum')
742 self.checkequal(True, 'a', 'isalnum')
743 self.checkequal(True, 'A', 'isalnum')
744 self.checkequal(False, '\n', 'isalnum')
745 self.checkequal(True, '123abc456', 'isalnum')
746 self.checkequal(True, 'a1b3c', 'isalnum')
747 self.checkequal(False, 'aBc000 ', 'isalnum')
748 self.checkequal(False, 'abc\n', 'isalnum')
749 self.checkraises(TypeError, 'abc', 'isalnum', 42)
750
751 def test_isdigit(self):
752 self.checkequal(False, '', 'isdigit')
753 self.checkequal(False, 'a', 'isdigit')
754 self.checkequal(True, '0', 'isdigit')
755 self.checkequal(True, '0123456789', 'isdigit')
756 self.checkequal(False, '0123456789a', 'isdigit')
757
758 self.checkraises(TypeError, 'abc', 'isdigit', 42)
759
760 def test_title(self):
761 self.checkequal(' Hello ', ' hello ', 'title')
762 self.checkequal('Hello ', 'hello ', 'title')
763 self.checkequal('Hello ', 'Hello ', 'title')
764 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
765 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
766 self.checkequal('Getint', "getInt", 'title')
767 self.checkraises(TypeError, 'hello', 'title', 42)
768
769 def test_splitlines(self):
770 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
771 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
772 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
773 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
774 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
775 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
776 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
777
778 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
779
780 def test_startswith(self):
781 self.checkequal(True, 'hello', 'startswith', 'he')
782 self.checkequal(True, 'hello', 'startswith', 'hello')
783 self.checkequal(False, 'hello', 'startswith', 'hello world')
784 self.checkequal(True, 'hello', 'startswith', '')
785 self.checkequal(False, 'hello', 'startswith', 'ello')
786 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
787 self.checkequal(True, 'hello', 'startswith', 'o', 4)
788 self.checkequal(False, 'hello', 'startswith', 'o', 5)
789 self.checkequal(True, 'hello', 'startswith', '', 5)
790 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
791 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
792 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
793 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
794
795 # test negative indices
796 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
797 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
798 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
799 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
800 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
801 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
802 self.checkequal(False, 'hello', 'startswith', 'o', -2)
803 self.checkequal(True, 'hello', 'startswith', 'o', -1)
804 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
805 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
806
807 self.checkraises(TypeError, 'hello', 'startswith')
808 self.checkraises(TypeError, 'hello', 'startswith', 42)
809
810 def test_endswith(self):
811 self.checkequal(True, 'hello', 'endswith', 'lo')
812 self.checkequal(False, 'hello', 'endswith', 'he')
813 self.checkequal(True, 'hello', 'endswith', '')
814 self.checkequal(False, 'hello', 'endswith', 'hello world')
815 self.checkequal(False, 'helloworld', 'endswith', 'worl')
816 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
817 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
818 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
819 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
820 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
821 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
822 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
823 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
824 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
825
826 # test negative indices
827 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
828 self.checkequal(False, 'hello', 'endswith', 'he', -2)
829 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
830 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
831 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
832 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
833 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
834 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
835 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
836 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
837 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
838 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
839 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
840
841 self.checkraises(TypeError, 'hello', 'endswith')
842 self.checkraises(TypeError, 'hello', 'endswith', 42)
843
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000844 def test___contains__(self):
845 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
846 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
847 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
848 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
849 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
850 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
851 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
852 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
853 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
854
855 def test_subscript(self):
856 self.checkequal(u'a', 'abc', '__getitem__', 0)
857 self.checkequal(u'c', 'abc', '__getitem__', -1)
858 self.checkequal(u'a', 'abc', '__getitem__', 0L)
859 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
860 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
861 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
862 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
863 # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice)
864
865 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
866
867 def test_slice(self):
868 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
869 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
870 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
871 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
872 self.checkequal('b', 'abc', '__getslice__', 1, 2)
873 self.checkequal('', 'abc', '__getslice__', 2, 2)
874 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
875 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
876 self.checkequal('', 'abc', '__getslice__', 2, 1)
877 # FIXME What about negative indizes? This is handled differently by [] and __getslice__
878
879 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
880
881 def test_mul(self):
882 self.checkequal('', 'abc', '__mul__', -1)
883 self.checkequal('', 'abc', '__mul__', 0)
884 self.checkequal('abc', 'abc', '__mul__', 1)
885 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
886 self.checkraises(TypeError, 'abc', '__mul__')
887 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +0000888 # XXX: on a 64-bit system, this doesn't raise an overflow error,
889 # but either raises a MemoryError, or succeeds (if you have 54TiB)
890 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000891
892 def test_join(self):
893 # join now works with any sequence type
894 # moved here, because the argument order is
895 # different in string.join (see the test in
896 # test.test_string.StringTest.test_join)
897 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
898 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
899 self.checkequal('w x y z', ' ', 'join', Sequence())
900 self.checkequal('abc', 'a', 'join', ('abc',))
901 self.checkequal('z', 'a', 'join', UserList(['z']))
902 if test_support.have_unicode:
903 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
904 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
905 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
906 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
907 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
908 for i in [5, 25, 125]:
909 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
910 ['a' * i] * i)
911 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
912 ('a' * i,) * i)
913
914 self.checkraises(TypeError, ' ', 'join', BadSeq1())
915 self.checkequal('a b c', ' ', 'join', BadSeq2())
916
917 self.checkraises(TypeError, ' ', 'join')
918 self.checkraises(TypeError, ' ', 'join', 7)
919 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +0000920 try:
921 def f():
922 yield 4 + ""
923 self.fixtype(' ').join(f())
924 except TypeError, e:
925 if '+' not in str(e):
926 self.fail('join() ate exception message')
927 else:
928 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000929
930 def test_formatting(self):
931 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
932 self.checkequal('+10+', '+%d+', '__mod__', 10)
933 self.checkequal('a', "%c", '__mod__', "a")
934 self.checkequal('a', "%c", '__mod__', "a")
935 self.checkequal('"', "%c", '__mod__', 34)
936 self.checkequal('$', "%c", '__mod__', 36)
937 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +0000938 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000939
940 for ordinal in (-100, 0x200000):
941 # unicode raises ValueError, str raises OverflowError
942 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
943
944 self.checkequal(' 42', '%3ld', '__mod__', 42)
945 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +0000946 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000947
948 self.checkraises(TypeError, 'abc', '__mod__')
949 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
950 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
951 self.checkraises(TypeError, '%c', '__mod__', (None,))
952 self.checkraises(ValueError, '%(foo', '__mod__', {})
953 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
954
955 # argument names with properly nested brackets are supported
956 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
957
958 # 100 is a magic number in PyUnicode_Format, this forces a resize
959 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
960
961 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
962 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
963 self.checkraises(ValueError, '%10', '__mod__', (42,))
964
965 def test_floatformatting(self):
966 # float formatting
967 for prec in xrange(100):
968 format = '%%.%if' % prec
969 value = 0.01
970 for x in xrange(60):
971 value = value * 3.141592655 / 3.0 * 10.0
972 # The formatfloat() code in stringobject.c and
973 # unicodeobject.c uses a 120 byte buffer and switches from
974 # 'f' formatting to 'g' at precision 50, so we expect
975 # OverflowErrors for the ranges x < 50 and prec >= 67.
976 if x < 50 and prec >= 67:
977 self.checkraises(OverflowError, format, "__mod__", value)
978 else:
979 self.checkcall(format, "__mod__", value)
980
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000981 def test_inplace_rewrites(self):
982 # Check that strings don't copy and modify cached single-character strings
983 self.checkequal('a', 'A', 'lower')
984 self.checkequal(True, 'A', 'isupper')
985 self.checkequal('A', 'a', 'upper')
986 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +0000987
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000988 self.checkequal('a', 'A', 'replace', 'A', 'a')
989 self.checkequal(True, 'A', 'isupper')
990
991 self.checkequal('A', 'a', 'capitalize')
992 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +0000993
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000994 self.checkequal('A', 'a', 'swapcase')
995 self.checkequal(True, 'a', 'islower')
996
997 self.checkequal('A', 'a', 'title')
998 self.checkequal(True, 'a', 'islower')
999
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001000 def test_partition(self):
1001
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001002 self.checkequal(('this is the par', 'ti', 'tion method'),
1003 'this is the partition method', 'partition', 'ti')
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001004
1005 # from raymond's original specification
1006 S = 'http://www.python.org'
1007 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1008 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1009 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1010 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1011
1012 self.checkraises(ValueError, S, 'partition', '')
1013 self.checkraises(TypeError, S, 'partition', None)
1014
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001015 def test_rpartition(self):
1016
1017 self.checkequal(('this is the rparti', 'ti', 'on method'),
1018 'this is the rpartition method', 'rpartition', 'ti')
1019
1020 # from raymond's original specification
1021 S = 'http://www.python.org'
1022 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
1023 self.checkequal(('http://www.python.org', '', ''), S, 'rpartition', '?')
1024 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1025 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1026
1027 self.checkraises(ValueError, S, 'rpartition', '')
1028 self.checkraises(TypeError, S, 'rpartition', None)
1029
Walter Dörwald57d88e52004-08-26 16:53:04 +00001030
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001031class MixinStrStringUserStringTest:
1032 # Additional tests for 8bit strings, i.e. str, UserString and
1033 # the string module
1034
1035 def test_maketrans(self):
1036 self.assertEqual(
1037 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
1038 string.maketrans('abc', 'xyz')
1039 )
1040 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
1041
1042 def test_translate(self):
1043 table = string.maketrans('abc', 'xyz')
1044 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
1045
1046 table = string.maketrans('a', 'A')
1047 self.checkequal('Abc', 'abc', 'translate', table)
1048 self.checkequal('xyz', 'xyz', 'translate', table)
1049 self.checkequal('yz', 'xyz', 'translate', table, 'x')
1050 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
1051 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001052
1053
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001054class MixinStrUserStringTest:
1055 # Additional tests that only work with
1056 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001057
Walter Dörwald6eea7892005-07-28 16:49:15 +00001058 if test_support.have_unicode:
1059 def test_encoding_decoding(self):
1060 codecs = [('rot13', 'uryyb jbeyq'),
1061 ('base64', 'aGVsbG8gd29ybGQ=\n'),
1062 ('hex', '68656c6c6f20776f726c64'),
1063 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
1064 for encoding, data in codecs:
1065 self.checkequal(data, 'hello world', 'encode', encoding)
1066 self.checkequal('hello world', data, 'decode', encoding)
1067 # zlib is optional, so we make the test optional too...
1068 try:
1069 import zlib
1070 except ImportError:
1071 pass
1072 else:
1073 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
1074 self.checkequal(data, 'hello world', 'encode', 'zlib')
1075 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +00001076
Walter Dörwald6eea7892005-07-28 16:49:15 +00001077 self.checkraises(TypeError, 'xyz', 'decode', 42)
1078 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +00001079
1080
1081class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001082 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001083
1084 def test_bug1001011(self):
1085 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001086 # involving a subclass.
1087 # Make sure that it is of the appropriate type.
1088 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001089 t = self.type2test
1090 class subclass(t):
1091 pass
1092 s1 = subclass("abcd")
1093 s2 = t().join([s1])
1094 self.assert_(s1 is not s2)
1095 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001096
1097 s1 = t("abcd")
1098 s2 = t().join([s1])
1099 self.assert_(s1 is s2)
1100
1101 # Should also test mixed-type join.
1102 if t is unicode:
1103 s1 = subclass("abcd")
1104 s2 = "".join([s1])
1105 self.assert_(s1 is not s2)
1106 self.assert_(type(s2) is t)
1107
1108 s1 = t("abcd")
1109 s2 = "".join([s1])
1110 self.assert_(s1 is s2)
1111
1112 elif t is str:
1113 s1 = subclass("abcd")
1114 s2 = u"".join([s1])
1115 self.assert_(s1 is not s2)
1116 self.assert_(type(s2) is unicode) # promotes!
1117
1118 s1 = t("abcd")
1119 s2 = u"".join([s1])
1120 self.assert_(s1 is not s2)
1121 self.assert_(type(s2) is unicode) # promotes!
1122
1123 else:
1124 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)