blob: c2e0875b768b446a64461cf35486f2c963f0f4f3 [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')
Fredrik Lundhb51b4702006-05-29 22:42:07 +0000109 self.checkequal(2, 'aaa', 'count', 'a', 1)
110 self.checkequal(0, 'aaa', 'count', 'a', 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000111 self.checkequal(1, 'aaa', 'count', 'a', -1)
112 self.checkequal(3, 'aaa', 'count', 'a', -10)
Fredrik Lundhb51b4702006-05-29 22:42:07 +0000113 self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
114 self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000115 self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
116 self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
Fredrik Lundhb51b4702006-05-29 22:42:07 +0000117 self.checkequal(3, 'aaa', 'count', '', 1)
118 self.checkequal(1, 'aaa', 'count', '', 10)
119 self.checkequal(2, 'aaa', 'count', '', -1)
120 self.checkequal(4, 'aaa', 'count', '', -10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000121
122 self.checkraises(TypeError, 'hello', 'count')
123 self.checkraises(TypeError, 'hello', 'count', 42)
124
Raymond Hettinger57e74472005-02-20 09:54:53 +0000125 # For a variety of combinations,
126 # verify that str.count() matches an equivalent function
127 # replacing all occurrences and then differencing the string lengths
128 charset = ['', 'a', 'b']
129 digits = 7
130 base = len(charset)
131 teststrings = set()
132 for i in xrange(base ** digits):
133 entry = []
134 for j in xrange(digits):
135 i, m = divmod(i, base)
136 entry.append(charset[m])
137 teststrings.add(''.join(entry))
138 teststrings = list(teststrings)
139 for i in teststrings:
140 i = self.fixtype(i)
141 n = len(i)
142 for j in teststrings:
143 r1 = i.count(j)
144 if j:
145 r2, rem = divmod(n - len(i.replace(j, '')), len(j))
146 else:
147 r2, rem = len(i)+1, 0
148 if rem or r1 != r2:
149 self.assertEqual(rem, 0)
150 self.assertEqual(r1, r2)
151
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000152 def test_find(self):
153 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
154 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
155 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
156
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000157 self.checkequal(0, 'abc', 'find', '', 0)
158 self.checkequal(3, 'abc', 'find', '', 3)
159 self.checkequal(-1, 'abc', 'find', '', 4)
160
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000161 self.checkraises(TypeError, 'hello', 'find')
162 self.checkraises(TypeError, 'hello', 'find', 42)
163
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000164 # For a variety of combinations,
165 # verify that str.find() matches __contains__
166 # and that the found substring is really at that location
167 charset = ['', 'a', 'b', 'c']
168 digits = 5
169 base = len(charset)
170 teststrings = set()
171 for i in xrange(base ** digits):
172 entry = []
173 for j in xrange(digits):
174 i, m = divmod(i, base)
175 entry.append(charset[m])
176 teststrings.add(''.join(entry))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000177 teststrings = list(teststrings)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000178 for i in teststrings:
179 i = self.fixtype(i)
180 for j in teststrings:
181 loc = i.find(j)
182 r1 = (loc != -1)
183 r2 = j in i
184 if r1 != r2:
185 self.assertEqual(r1, r2)
186 if loc != -1:
187 self.assertEqual(i[loc:loc+len(j)], j)
188
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000189 def test_rfind(self):
190 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
191 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
192 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
193 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
194
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000195 self.checkequal(3, 'abc', 'rfind', '', 0)
196 self.checkequal(3, 'abc', 'rfind', '', 3)
197 self.checkequal(-1, 'abc', 'rfind', '', 4)
198
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000199 self.checkraises(TypeError, 'hello', 'rfind')
200 self.checkraises(TypeError, 'hello', 'rfind', 42)
201
202 def test_index(self):
203 self.checkequal(0, 'abcdefghiabc', 'index', '')
204 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
205 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
206 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
207
208 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
209 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
210 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
211 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
212
213 self.checkraises(TypeError, 'hello', 'index')
214 self.checkraises(TypeError, 'hello', 'index', 42)
215
216 def test_rindex(self):
217 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
218 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
219 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
220 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
221
222 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
223 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
224 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
225 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
226 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
227
228 self.checkraises(TypeError, 'hello', 'rindex')
229 self.checkraises(TypeError, 'hello', 'rindex', 42)
230
231 def test_lower(self):
232 self.checkequal('hello', 'HeLLo', 'lower')
233 self.checkequal('hello', 'hello', 'lower')
234 self.checkraises(TypeError, 'hello', 'lower', 42)
235
236 def test_upper(self):
237 self.checkequal('HELLO', 'HeLLo', 'upper')
238 self.checkequal('HELLO', 'HELLO', 'upper')
239 self.checkraises(TypeError, 'hello', 'upper', 42)
240
241 def test_expandtabs(self):
242 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
243 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
244 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
245 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
246 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
247 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
248 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
249
250 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
251
252 def test_split(self):
253 self.checkequal(['this', 'is', 'the', 'split', 'function'],
254 'this is the split function', 'split')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000255
256 # by whitespace
257 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000258 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
259 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
260 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
261 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000262 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
263 sys.maxint-1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000264 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000265 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000266 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000267
Andrew Dalke984b9712006-05-26 11:11:38 +0000268 self.checkequal([], ' ', 'split')
269 self.checkequal(['a'], ' a ', 'split')
270 self.checkequal(['a', 'b'], ' a b ', 'split')
271 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
272 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
273 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
Andrew Dalke03fb4442006-05-26 11:15:22 +0000274 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
Andrew Dalke005aee22006-05-26 12:28:15 +0000275 aaa = ' a '*20
276 self.checkequal(['a']*20, aaa, 'split')
277 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
Andrew Dalke669fa182006-05-26 13:05:55 +0000278 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
Andrew Dalke984b9712006-05-26 11:11:38 +0000279
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000280 # by a char
281 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000282 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000283 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
284 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
285 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
286 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000287 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
288 sys.maxint-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000289 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
290 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
291 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000292 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
293 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000294 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
295
Andrew Dalke005aee22006-05-26 12:28:15 +0000296 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
297 self.checkequal(['a']*15 +['a|a|a|a|a'],
298 ('a|'*20)[:-1], 'split', '|', 15)
299
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000300 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000301 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000302 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
303 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
304 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
305 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000306 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
307 sys.maxint-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000308 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
309 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000310 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000311 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
312 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
313 'split', 'test')
314 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000315 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
316 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
317 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
318 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
319 self.checkequal([''], '', 'split', 'aaa')
320 self.checkequal(['aa'], 'aa', 'split', 'aaa')
Andrew Dalke5cc60092006-05-26 12:31:00 +0000321 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
322 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000323
324 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
325 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
326 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
327 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000328
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000329 # mixed use of str and unicode
330 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
331
332 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000333 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
334
Andrew Dalke005aee22006-05-26 12:28:15 +0000335 # null case
336 self.checkraises(ValueError, 'hello', 'split', '')
337 self.checkraises(ValueError, 'hello', 'split', '', 0)
338
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000339 def test_rsplit(self):
340 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
341 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000342
343 # by whitespace
344 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000345 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
346 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
347 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
348 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000349 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
350 sys.maxint-20)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000351 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000352 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000353 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000354
Andrew Dalke669fa182006-05-26 13:05:55 +0000355 self.checkequal([], ' ', 'rsplit')
356 self.checkequal(['a'], ' a ', 'rsplit')
357 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
358 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
359 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
360 None, 1)
361 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
362 None, 2)
363 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
364 aaa = ' a '*20
365 self.checkequal(['a']*20, aaa, 'rsplit')
366 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
367 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
368
369
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000370 # by a char
371 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
372 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
373 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
374 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
375 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000376 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
377 sys.maxint-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000378 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
379 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
380 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Andrew Dalke669fa182006-05-26 13:05:55 +0000381 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
382 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
383
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000384 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
385
Andrew Dalke669fa182006-05-26 13:05:55 +0000386 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
387 self.checkequal(['a|a|a|a|a']+['a']*15,
388 ('a|'*20)[:-1], 'rsplit', '|', 15)
389
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000390 # by string
391 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
392 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
393 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
394 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
395 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000396 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
397 sys.maxint-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000398 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
399 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
400 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000401 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
402 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
403 'rsplit', 'test')
404 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
405 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
406 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
407 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
408 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
409 self.checkequal([''], '', 'rsplit', 'aaa')
410 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
411 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
412 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
413
414 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
415 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
416 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
417 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000418
419 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000420 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000421
422 # argument type
423 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000424
Andrew Dalke669fa182006-05-26 13:05:55 +0000425 # null case
426 self.checkraises(ValueError, 'hello', 'rsplit', '')
427 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
428
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000429 def test_strip(self):
430 self.checkequal('hello', ' hello ', 'strip')
431 self.checkequal('hello ', ' hello ', 'lstrip')
432 self.checkequal(' hello', ' hello ', 'rstrip')
433 self.checkequal('hello', 'hello', 'strip')
434
Neal Norwitzffe33b72003-04-10 22:35:32 +0000435 # strip/lstrip/rstrip with None arg
436 self.checkequal('hello', ' hello ', 'strip', None)
437 self.checkequal('hello ', ' hello ', 'lstrip', None)
438 self.checkequal(' hello', ' hello ', 'rstrip', None)
439 self.checkequal('hello', 'hello', 'strip', None)
440
441 # strip/lstrip/rstrip with str arg
442 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
443 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
444 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
445 self.checkequal('hello', 'hello', 'strip', 'xyz')
446
447 # strip/lstrip/rstrip with unicode arg
448 if test_support.have_unicode:
449 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
450 'strip', unicode('xyz', 'ascii'))
451 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
452 'lstrip', unicode('xyz', 'ascii'))
453 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
454 'rstrip', unicode('xyz', 'ascii'))
455 self.checkequal(unicode('hello', 'ascii'), 'hello',
456 'strip', unicode('xyz', 'ascii'))
457
458 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
459 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
460 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
461
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000462 def test_ljust(self):
463 self.checkequal('abc ', 'abc', 'ljust', 10)
464 self.checkequal('abc ', 'abc', 'ljust', 6)
465 self.checkequal('abc', 'abc', 'ljust', 3)
466 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000467 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000468 self.checkraises(TypeError, 'abc', 'ljust')
469
470 def test_rjust(self):
471 self.checkequal(' abc', 'abc', 'rjust', 10)
472 self.checkequal(' abc', 'abc', 'rjust', 6)
473 self.checkequal('abc', 'abc', 'rjust', 3)
474 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000475 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000476 self.checkraises(TypeError, 'abc', 'rjust')
477
478 def test_center(self):
479 self.checkequal(' abc ', 'abc', 'center', 10)
480 self.checkequal(' abc ', 'abc', 'center', 6)
481 self.checkequal('abc', 'abc', 'center', 3)
482 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000483 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000484 self.checkraises(TypeError, 'abc', 'center')
485
486 def test_swapcase(self):
487 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
488
489 self.checkraises(TypeError, 'hello', 'swapcase', 42)
490
491 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000492 EQ = self.checkequal
493
494 # Operations on the empty string
495 EQ("", "", "replace", "", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000496
497 #EQ("A", "", "replace", "", "A")
498 # That was the correct result; this is the result we actually get
Tim Petersf4049082006-05-24 21:00:45 +0000499 # now (for str, but not for unicode):
500 #EQ("", "", "replace", "", "A")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000501
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000502 EQ("", "", "replace", "A", "")
503 EQ("", "", "replace", "A", "A")
504 EQ("", "", "replace", "", "", 100)
505 EQ("", "", "replace", "", "", sys.maxint)
506
507 # interleave (from=="", 'to' gets inserted everywhere)
508 EQ("A", "A", "replace", "", "")
509 EQ("*A*", "A", "replace", "", "*")
510 EQ("*1A*1", "A", "replace", "", "*1")
511 EQ("*-#A*-#", "A", "replace", "", "*-#")
512 EQ("*-A*-A*-", "AA", "replace", "", "*-")
513 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
514 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
515 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
516 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
517 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
518 EQ("*-AA", "AA", "replace", "", "*-", 1)
519 EQ("AA", "AA", "replace", "", "*-", 0)
520
521 # single character deletion (from=="A", to=="")
522 EQ("", "A", "replace", "A", "")
523 EQ("", "AAA", "replace", "A", "")
524 EQ("", "AAA", "replace", "A", "", -1)
525 EQ("", "AAA", "replace", "A", "", sys.maxint)
526 EQ("", "AAA", "replace", "A", "", 4)
527 EQ("", "AAA", "replace", "A", "", 3)
528 EQ("A", "AAA", "replace", "A", "", 2)
529 EQ("AA", "AAA", "replace", "A", "", 1)
530 EQ("AAA", "AAA", "replace", "A", "", 0)
531 EQ("", "AAAAAAAAAA", "replace", "A", "")
532 EQ("BCD", "ABACADA", "replace", "A", "")
533 EQ("BCD", "ABACADA", "replace", "A", "", -1)
534 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
535 EQ("BCD", "ABACADA", "replace", "A", "", 5)
536 EQ("BCD", "ABACADA", "replace", "A", "", 4)
537 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
538 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
539 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
540 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
541 EQ("BCD", "ABCAD", "replace", "A", "")
542 EQ("BCD", "ABCADAA", "replace", "A", "")
543 EQ("BCD", "BCD", "replace", "A", "")
544 EQ("*************", "*************", "replace", "A", "")
545 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
546
547 # substring deletion (from=="the", to=="")
548 EQ("", "the", "replace", "the", "")
549 EQ("ater", "theater", "replace", "the", "")
550 EQ("", "thethe", "replace", "the", "")
551 EQ("", "thethethethe", "replace", "the", "")
552 EQ("aaaa", "theatheatheathea", "replace", "the", "")
553 EQ("that", "that", "replace", "the", "")
554 EQ("thaet", "thaet", "replace", "the", "")
555 EQ("here and re", "here and there", "replace", "the", "")
556 EQ("here and re and re", "here and there and there",
557 "replace", "the", "", sys.maxint)
558 EQ("here and re and re", "here and there and there",
559 "replace", "the", "", -1)
560 EQ("here and re and re", "here and there and there",
561 "replace", "the", "", 3)
562 EQ("here and re and re", "here and there and there",
563 "replace", "the", "", 2)
564 EQ("here and re and there", "here and there and there",
565 "replace", "the", "", 1)
566 EQ("here and there and there", "here and there and there",
567 "replace", "the", "", 0)
568 EQ("here and re and re", "here and there and there", "replace", "the", "")
569
570 EQ("abc", "abc", "replace", "the", "")
571 EQ("abcdefg", "abcdefg", "replace", "the", "")
572
573 # substring deletion (from=="bob", to=="")
574 EQ("bob", "bbobob", "replace", "bob", "")
575 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
576 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
577 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000578
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000579 # single character replace in place (len(from)==len(to)==1)
580 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
581 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
582 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
583 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
584 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
585 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
586 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
587 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
588
589 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
590 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
591 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
592 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
593 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
594
595 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000596
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000597 # substring replace in place (len(from)==len(to) > 1)
598 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
599 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
600 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
601 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
602 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
603 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
604 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
605 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
606 EQ("cobob", "bobob", "replace", "bob", "cob")
607 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
608 EQ("bobob", "bobob", "replace", "bot", "bot")
609
610 # replace single character (len(from)==1, len(to)>1)
611 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
612 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
613 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
614 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
615 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
616 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
617 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
618
619 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
620
621 # replace substring (len(from)>1, len(to)!=len(from))
622 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
623 "replace", "spam", "ham")
624 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
625 "replace", "spam", "ham", sys.maxint)
626 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
627 "replace", "spam", "ham", -1)
628 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
629 "replace", "spam", "ham", 4)
630 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
631 "replace", "spam", "ham", 3)
632 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
633 "replace", "spam", "ham", 2)
634 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
635 "replace", "spam", "ham", 1)
636 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
637 "replace", "spam", "ham", 0)
638
639 EQ("bobob", "bobobob", "replace", "bobob", "bob")
640 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
641 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000642
643 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000644 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
645 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
646 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
647 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
648 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
649 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
650 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
651 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
652 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
653 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
654 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
655 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
656 self.checkequal('', '', 'replace', '', '')
657 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
658 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
659 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
660 # MemoryError due to empty result (platform malloc issue when requesting
661 # 0 bytes).
662 self.checkequal('', '123', 'replace', '123', '')
663 self.checkequal('', '123123', 'replace', '123', '')
664 self.checkequal('x', '123x123', 'replace', '123', '')
665
666 self.checkraises(TypeError, 'hello', 'replace')
667 self.checkraises(TypeError, 'hello', 'replace', 42)
668 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
669 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
670
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000671 def test_replace_overflow(self):
672 # Check for overflow checking on 32 bit machines
673 if sys.maxint != 2147483647:
674 return
675 A2_16 = "A" * (2**16)
676 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
677 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
678 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000679
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000680 def test_zfill(self):
681 self.checkequal('123', '123', 'zfill', 2)
682 self.checkequal('123', '123', 'zfill', 3)
683 self.checkequal('0123', '123', 'zfill', 4)
684 self.checkequal('+123', '+123', 'zfill', 3)
685 self.checkequal('+123', '+123', 'zfill', 4)
686 self.checkequal('+0123', '+123', 'zfill', 5)
687 self.checkequal('-123', '-123', 'zfill', 3)
688 self.checkequal('-123', '-123', 'zfill', 4)
689 self.checkequal('-0123', '-123', 'zfill', 5)
690 self.checkequal('000', '', 'zfill', 3)
691 self.checkequal('34', '34', 'zfill', 1)
692 self.checkequal('0034', '34', 'zfill', 4)
693
694 self.checkraises(TypeError, '123', 'zfill')
695
696class MixinStrUnicodeUserStringTest:
697 # additional tests that only work for
698 # stringlike objects, i.e. str, unicode, UserString
699 # (but not the string module)
700
701 def test_islower(self):
702 self.checkequal(False, '', 'islower')
703 self.checkequal(True, 'a', 'islower')
704 self.checkequal(False, 'A', 'islower')
705 self.checkequal(False, '\n', 'islower')
706 self.checkequal(True, 'abc', 'islower')
707 self.checkequal(False, 'aBc', 'islower')
708 self.checkequal(True, 'abc\n', 'islower')
709 self.checkraises(TypeError, 'abc', 'islower', 42)
710
711 def test_isupper(self):
712 self.checkequal(False, '', 'isupper')
713 self.checkequal(False, 'a', 'isupper')
714 self.checkequal(True, 'A', 'isupper')
715 self.checkequal(False, '\n', 'isupper')
716 self.checkequal(True, 'ABC', 'isupper')
717 self.checkequal(False, 'AbC', 'isupper')
718 self.checkequal(True, 'ABC\n', 'isupper')
719 self.checkraises(TypeError, 'abc', 'isupper', 42)
720
721 def test_istitle(self):
722 self.checkequal(False, '', 'istitle')
723 self.checkequal(False, 'a', 'istitle')
724 self.checkequal(True, 'A', 'istitle')
725 self.checkequal(False, '\n', 'istitle')
726 self.checkequal(True, 'A Titlecased Line', 'istitle')
727 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
728 self.checkequal(True, 'A Titlecased, Line', 'istitle')
729 self.checkequal(False, 'Not a capitalized String', 'istitle')
730 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
731 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
732 self.checkequal(False, 'NOT', 'istitle')
733 self.checkraises(TypeError, 'abc', 'istitle', 42)
734
735 def test_isspace(self):
736 self.checkequal(False, '', 'isspace')
737 self.checkequal(False, 'a', 'isspace')
738 self.checkequal(True, ' ', 'isspace')
739 self.checkequal(True, '\t', 'isspace')
740 self.checkequal(True, '\r', 'isspace')
741 self.checkequal(True, '\n', 'isspace')
742 self.checkequal(True, ' \t\r\n', 'isspace')
743 self.checkequal(False, ' \t\r\na', 'isspace')
744 self.checkraises(TypeError, 'abc', 'isspace', 42)
745
746 def test_isalpha(self):
747 self.checkequal(False, '', 'isalpha')
748 self.checkequal(True, 'a', 'isalpha')
749 self.checkequal(True, 'A', 'isalpha')
750 self.checkequal(False, '\n', 'isalpha')
751 self.checkequal(True, 'abc', 'isalpha')
752 self.checkequal(False, 'aBc123', 'isalpha')
753 self.checkequal(False, 'abc\n', 'isalpha')
754 self.checkraises(TypeError, 'abc', 'isalpha', 42)
755
756 def test_isalnum(self):
757 self.checkequal(False, '', 'isalnum')
758 self.checkequal(True, 'a', 'isalnum')
759 self.checkequal(True, 'A', 'isalnum')
760 self.checkequal(False, '\n', 'isalnum')
761 self.checkequal(True, '123abc456', 'isalnum')
762 self.checkequal(True, 'a1b3c', 'isalnum')
763 self.checkequal(False, 'aBc000 ', 'isalnum')
764 self.checkequal(False, 'abc\n', 'isalnum')
765 self.checkraises(TypeError, 'abc', 'isalnum', 42)
766
767 def test_isdigit(self):
768 self.checkequal(False, '', 'isdigit')
769 self.checkequal(False, 'a', 'isdigit')
770 self.checkequal(True, '0', 'isdigit')
771 self.checkequal(True, '0123456789', 'isdigit')
772 self.checkequal(False, '0123456789a', 'isdigit')
773
774 self.checkraises(TypeError, 'abc', 'isdigit', 42)
775
776 def test_title(self):
777 self.checkequal(' Hello ', ' hello ', 'title')
778 self.checkequal('Hello ', 'hello ', 'title')
779 self.checkequal('Hello ', 'Hello ', 'title')
780 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
781 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
782 self.checkequal('Getint', "getInt", 'title')
783 self.checkraises(TypeError, 'hello', 'title', 42)
784
785 def test_splitlines(self):
786 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
787 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
788 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
789 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
790 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
791 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
792 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
793
794 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
795
796 def test_startswith(self):
797 self.checkequal(True, 'hello', 'startswith', 'he')
798 self.checkequal(True, 'hello', 'startswith', 'hello')
799 self.checkequal(False, 'hello', 'startswith', 'hello world')
800 self.checkequal(True, 'hello', 'startswith', '')
801 self.checkequal(False, 'hello', 'startswith', 'ello')
802 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
803 self.checkequal(True, 'hello', 'startswith', 'o', 4)
804 self.checkequal(False, 'hello', 'startswith', 'o', 5)
805 self.checkequal(True, 'hello', 'startswith', '', 5)
806 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
807 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
808 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
809 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
810
811 # test negative indices
812 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
813 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
814 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
815 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
816 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
817 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
818 self.checkequal(False, 'hello', 'startswith', 'o', -2)
819 self.checkequal(True, 'hello', 'startswith', 'o', -1)
820 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
821 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
822
823 self.checkraises(TypeError, 'hello', 'startswith')
824 self.checkraises(TypeError, 'hello', 'startswith', 42)
825
826 def test_endswith(self):
827 self.checkequal(True, 'hello', 'endswith', 'lo')
828 self.checkequal(False, 'hello', 'endswith', 'he')
829 self.checkequal(True, 'hello', 'endswith', '')
830 self.checkequal(False, 'hello', 'endswith', 'hello world')
831 self.checkequal(False, 'helloworld', 'endswith', 'worl')
832 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
833 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
834 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
835 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
836 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
837 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
838 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
839 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
840 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
841
842 # test negative indices
843 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
844 self.checkequal(False, 'hello', 'endswith', 'he', -2)
845 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
846 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
847 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
848 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
849 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
850 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
851 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
852 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
853 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
854 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
855 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
856
857 self.checkraises(TypeError, 'hello', 'endswith')
858 self.checkraises(TypeError, 'hello', 'endswith', 42)
859
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000860 def test___contains__(self):
861 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
862 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
863 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
864 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
865 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
866 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
867 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
868 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
869 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
870
871 def test_subscript(self):
872 self.checkequal(u'a', 'abc', '__getitem__', 0)
873 self.checkequal(u'c', 'abc', '__getitem__', -1)
874 self.checkequal(u'a', 'abc', '__getitem__', 0L)
875 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
876 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
877 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
878 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
879 # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice)
880
881 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
882
883 def test_slice(self):
884 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
885 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
886 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
887 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
888 self.checkequal('b', 'abc', '__getslice__', 1, 2)
889 self.checkequal('', 'abc', '__getslice__', 2, 2)
890 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
891 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
892 self.checkequal('', 'abc', '__getslice__', 2, 1)
893 # FIXME What about negative indizes? This is handled differently by [] and __getslice__
894
895 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
896
897 def test_mul(self):
898 self.checkequal('', 'abc', '__mul__', -1)
899 self.checkequal('', 'abc', '__mul__', 0)
900 self.checkequal('abc', 'abc', '__mul__', 1)
901 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
902 self.checkraises(TypeError, 'abc', '__mul__')
903 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +0000904 # XXX: on a 64-bit system, this doesn't raise an overflow error,
905 # but either raises a MemoryError, or succeeds (if you have 54TiB)
906 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000907
908 def test_join(self):
909 # join now works with any sequence type
910 # moved here, because the argument order is
911 # different in string.join (see the test in
912 # test.test_string.StringTest.test_join)
913 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
914 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
915 self.checkequal('w x y z', ' ', 'join', Sequence())
916 self.checkequal('abc', 'a', 'join', ('abc',))
917 self.checkequal('z', 'a', 'join', UserList(['z']))
918 if test_support.have_unicode:
919 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
920 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
921 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
922 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
923 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
924 for i in [5, 25, 125]:
925 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
926 ['a' * i] * i)
927 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
928 ('a' * i,) * i)
929
930 self.checkraises(TypeError, ' ', 'join', BadSeq1())
931 self.checkequal('a b c', ' ', 'join', BadSeq2())
932
933 self.checkraises(TypeError, ' ', 'join')
934 self.checkraises(TypeError, ' ', 'join', 7)
935 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +0000936 try:
937 def f():
938 yield 4 + ""
939 self.fixtype(' ').join(f())
940 except TypeError, e:
941 if '+' not in str(e):
942 self.fail('join() ate exception message')
943 else:
944 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000945
946 def test_formatting(self):
947 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
948 self.checkequal('+10+', '+%d+', '__mod__', 10)
949 self.checkequal('a', "%c", '__mod__', "a")
950 self.checkequal('a', "%c", '__mod__', "a")
951 self.checkequal('"', "%c", '__mod__', 34)
952 self.checkequal('$', "%c", '__mod__', 36)
953 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +0000954 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000955
956 for ordinal in (-100, 0x200000):
957 # unicode raises ValueError, str raises OverflowError
958 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
959
960 self.checkequal(' 42', '%3ld', '__mod__', 42)
961 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +0000962 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000963
964 self.checkraises(TypeError, 'abc', '__mod__')
965 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
966 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
967 self.checkraises(TypeError, '%c', '__mod__', (None,))
968 self.checkraises(ValueError, '%(foo', '__mod__', {})
969 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
970
971 # argument names with properly nested brackets are supported
972 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
973
974 # 100 is a magic number in PyUnicode_Format, this forces a resize
975 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
976
977 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
978 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
979 self.checkraises(ValueError, '%10', '__mod__', (42,))
980
981 def test_floatformatting(self):
982 # float formatting
983 for prec in xrange(100):
984 format = '%%.%if' % prec
985 value = 0.01
986 for x in xrange(60):
987 value = value * 3.141592655 / 3.0 * 10.0
988 # The formatfloat() code in stringobject.c and
989 # unicodeobject.c uses a 120 byte buffer and switches from
990 # 'f' formatting to 'g' at precision 50, so we expect
991 # OverflowErrors for the ranges x < 50 and prec >= 67.
992 if x < 50 and prec >= 67:
993 self.checkraises(OverflowError, format, "__mod__", value)
994 else:
995 self.checkcall(format, "__mod__", value)
996
Andrew Dalke2bddcbf2006-05-25 16:30:52 +0000997 def test_inplace_rewrites(self):
998 # Check that strings don't copy and modify cached single-character strings
999 self.checkequal('a', 'A', 'lower')
1000 self.checkequal(True, 'A', 'isupper')
1001 self.checkequal('A', 'a', 'upper')
1002 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001003
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001004 self.checkequal('a', 'A', 'replace', 'A', 'a')
1005 self.checkequal(True, 'A', 'isupper')
1006
1007 self.checkequal('A', 'a', 'capitalize')
1008 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001009
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001010 self.checkequal('A', 'a', 'swapcase')
1011 self.checkequal(True, 'a', 'islower')
1012
1013 self.checkequal('A', 'a', 'title')
1014 self.checkequal(True, 'a', 'islower')
1015
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001016 def test_partition(self):
1017
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001018 self.checkequal(('this is the par', 'ti', 'tion method'),
1019 'this is the partition method', 'partition', 'ti')
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001020
1021 # from raymond's original specification
1022 S = 'http://www.python.org'
1023 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1024 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1025 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1026 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1027
1028 self.checkraises(ValueError, S, 'partition', '')
1029 self.checkraises(TypeError, S, 'partition', None)
1030
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001031 def test_rpartition(self):
1032
1033 self.checkequal(('this is the rparti', 'ti', 'on method'),
1034 'this is the rpartition method', 'rpartition', 'ti')
1035
1036 # from raymond's original specification
1037 S = 'http://www.python.org'
1038 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
1039 self.checkequal(('http://www.python.org', '', ''), S, 'rpartition', '?')
1040 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1041 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1042
1043 self.checkraises(ValueError, S, 'rpartition', '')
1044 self.checkraises(TypeError, S, 'rpartition', None)
1045
Walter Dörwald57d88e52004-08-26 16:53:04 +00001046
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001047class MixinStrStringUserStringTest:
1048 # Additional tests for 8bit strings, i.e. str, UserString and
1049 # the string module
1050
1051 def test_maketrans(self):
1052 self.assertEqual(
1053 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
1054 string.maketrans('abc', 'xyz')
1055 )
1056 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
1057
1058 def test_translate(self):
1059 table = string.maketrans('abc', 'xyz')
1060 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
1061
1062 table = string.maketrans('a', 'A')
1063 self.checkequal('Abc', 'abc', 'translate', table)
1064 self.checkequal('xyz', 'xyz', 'translate', table)
1065 self.checkequal('yz', 'xyz', 'translate', table, 'x')
1066 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
1067 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001068
1069
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001070class MixinStrUserStringTest:
1071 # Additional tests that only work with
1072 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001073
Walter Dörwald6eea7892005-07-28 16:49:15 +00001074 if test_support.have_unicode:
1075 def test_encoding_decoding(self):
1076 codecs = [('rot13', 'uryyb jbeyq'),
1077 ('base64', 'aGVsbG8gd29ybGQ=\n'),
1078 ('hex', '68656c6c6f20776f726c64'),
1079 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
1080 for encoding, data in codecs:
1081 self.checkequal(data, 'hello world', 'encode', encoding)
1082 self.checkequal('hello world', data, 'decode', encoding)
1083 # zlib is optional, so we make the test optional too...
1084 try:
1085 import zlib
1086 except ImportError:
1087 pass
1088 else:
1089 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
1090 self.checkequal(data, 'hello world', 'encode', 'zlib')
1091 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +00001092
Walter Dörwald6eea7892005-07-28 16:49:15 +00001093 self.checkraises(TypeError, 'xyz', 'decode', 42)
1094 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +00001095
1096
1097class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001098 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001099
1100 def test_bug1001011(self):
1101 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001102 # involving a subclass.
1103 # Make sure that it is of the appropriate type.
1104 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001105 t = self.type2test
1106 class subclass(t):
1107 pass
1108 s1 = subclass("abcd")
1109 s2 = t().join([s1])
1110 self.assert_(s1 is not s2)
1111 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001112
1113 s1 = t("abcd")
1114 s2 = t().join([s1])
1115 self.assert_(s1 is s2)
1116
1117 # Should also test mixed-type join.
1118 if t is unicode:
1119 s1 = subclass("abcd")
1120 s2 = "".join([s1])
1121 self.assert_(s1 is not s2)
1122 self.assert_(type(s2) is t)
1123
1124 s1 = t("abcd")
1125 s2 = "".join([s1])
1126 self.assert_(s1 is s2)
1127
1128 elif t is str:
1129 s1 = subclass("abcd")
1130 s2 = u"".join([s1])
1131 self.assert_(s1 is not s2)
1132 self.assert_(type(s2) is unicode) # promotes!
1133
1134 s1 = t("abcd")
1135 s2 = u"".join([s1])
1136 self.assert_(s1 is not s2)
1137 self.assert_(type(s2) is unicode) # promotes!
1138
1139 else:
1140 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)