blob: 31da13d6504d497c8993edb1e4d92c2310510046 [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
Kristján Valur Jónsson7bca0272007-05-07 13:33:39 +00005import unittest, string, sys, struct
Walter Dörwald0fd583c2003-02-21 12:53:50 +00006from 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)
Fredrik Lundh9e9ef9f2006-05-30 17:39:58 +0000118 self.checkequal(1, 'aaa', 'count', '', 3)
119 self.checkequal(0, 'aaa', 'count', '', 10)
Fredrik Lundhb51b4702006-05-29 22:42:07 +0000120 self.checkequal(2, 'aaa', 'count', '', -1)
121 self.checkequal(4, 'aaa', 'count', '', -10)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000122
Amaury Forgeot d'Arcb50f9922008-09-26 22:46:01 +0000123 self.checkequal(1, '', 'count', '')
124 self.checkequal(0, '', 'count', '', 1, 1)
125 self.checkequal(0, '', 'count', '', sys.maxint, 0)
126
127 self.checkequal(0, '', 'count', 'xx')
128 self.checkequal(0, '', 'count', 'xx', 1, 1)
129 self.checkequal(0, '', 'count', 'xx', sys.maxint, 0)
130
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000131 self.checkraises(TypeError, 'hello', 'count')
132 self.checkraises(TypeError, 'hello', 'count', 42)
133
Raymond Hettinger57e74472005-02-20 09:54:53 +0000134 # For a variety of combinations,
135 # verify that str.count() matches an equivalent function
136 # replacing all occurrences and then differencing the string lengths
137 charset = ['', 'a', 'b']
138 digits = 7
139 base = len(charset)
140 teststrings = set()
141 for i in xrange(base ** digits):
142 entry = []
143 for j in xrange(digits):
144 i, m = divmod(i, base)
145 entry.append(charset[m])
146 teststrings.add(''.join(entry))
147 teststrings = list(teststrings)
148 for i in teststrings:
149 i = self.fixtype(i)
150 n = len(i)
151 for j in teststrings:
152 r1 = i.count(j)
153 if j:
154 r2, rem = divmod(n - len(i.replace(j, '')), len(j))
155 else:
156 r2, rem = len(i)+1, 0
157 if rem or r1 != r2:
Neal Norwitzf71ec5a2006-07-30 06:57:04 +0000158 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
159 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000160
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000161 def test_find(self):
162 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
163 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
164 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
165
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000166 self.checkequal(0, 'abc', 'find', '', 0)
167 self.checkequal(3, 'abc', 'find', '', 3)
168 self.checkequal(-1, 'abc', 'find', '', 4)
169
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000170 self.checkraises(TypeError, 'hello', 'find')
171 self.checkraises(TypeError, 'hello', 'find', 42)
172
Amaury Forgeot d'Arcb50f9922008-09-26 22:46:01 +0000173 self.checkequal(0, '', 'find', '')
174 self.checkequal(-1, '', 'find', '', 1, 1)
175 self.checkequal(-1, '', 'find', '', sys.maxint, 0)
176
177 self.checkequal(-1, '', 'find', 'xx')
178 self.checkequal(-1, '', 'find', 'xx', 1, 1)
179 self.checkequal(-1, '', 'find', 'xx', sys.maxint, 0)
180
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000181 # For a variety of combinations,
182 # verify that str.find() matches __contains__
183 # and that the found substring is really at that location
184 charset = ['', 'a', 'b', 'c']
185 digits = 5
186 base = len(charset)
187 teststrings = set()
188 for i in xrange(base ** digits):
189 entry = []
190 for j in xrange(digits):
191 i, m = divmod(i, base)
192 entry.append(charset[m])
193 teststrings.add(''.join(entry))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000194 teststrings = list(teststrings)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000195 for i in teststrings:
196 i = self.fixtype(i)
197 for j in teststrings:
198 loc = i.find(j)
199 r1 = (loc != -1)
200 r2 = j in i
201 if r1 != r2:
202 self.assertEqual(r1, r2)
203 if loc != -1:
204 self.assertEqual(i[loc:loc+len(j)], j)
205
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000206 def test_rfind(self):
207 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
208 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
209 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
210 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
211
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000212 self.checkequal(3, 'abc', 'rfind', '', 0)
213 self.checkequal(3, 'abc', 'rfind', '', 3)
214 self.checkequal(-1, 'abc', 'rfind', '', 4)
215
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000216 self.checkraises(TypeError, 'hello', 'rfind')
217 self.checkraises(TypeError, 'hello', 'rfind', 42)
218
219 def test_index(self):
220 self.checkequal(0, 'abcdefghiabc', 'index', '')
221 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
222 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
223 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
224
225 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
226 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
227 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
228 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
229
230 self.checkraises(TypeError, 'hello', 'index')
231 self.checkraises(TypeError, 'hello', 'index', 42)
232
233 def test_rindex(self):
234 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
235 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
236 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
237 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
238
239 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
240 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
241 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
242 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
243 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
244
245 self.checkraises(TypeError, 'hello', 'rindex')
246 self.checkraises(TypeError, 'hello', 'rindex', 42)
247
248 def test_lower(self):
249 self.checkequal('hello', 'HeLLo', 'lower')
250 self.checkequal('hello', 'hello', 'lower')
251 self.checkraises(TypeError, 'hello', 'lower', 42)
252
253 def test_upper(self):
254 self.checkequal('HELLO', 'HeLLo', 'upper')
255 self.checkequal('HELLO', 'HELLO', 'upper')
256 self.checkraises(TypeError, 'hello', 'upper', 42)
257
258 def test_expandtabs(self):
259 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
260 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
261 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
262 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
263 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
264 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
265 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
Neal Norwitz8355dd52007-06-11 04:32:41 +0000266 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000267
268 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
Neal Norwitz8355dd52007-06-11 04:32:41 +0000269 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
270 if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
271 self.checkraises(OverflowError,
272 '\ta\n\tb', 'expandtabs', sys.maxint)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000273
274 def test_split(self):
275 self.checkequal(['this', 'is', 'the', 'split', 'function'],
276 'this is the split function', 'split')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000277
278 # by whitespace
279 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000280 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
281 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
282 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
283 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000284 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
285 sys.maxint-1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000286 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000287 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000288 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000289
Andrew Dalke984b9712006-05-26 11:11:38 +0000290 self.checkequal([], ' ', 'split')
291 self.checkequal(['a'], ' a ', 'split')
292 self.checkequal(['a', 'b'], ' a b ', 'split')
293 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
294 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
295 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
Andrew Dalke03fb4442006-05-26 11:15:22 +0000296 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
Andrew Dalke005aee22006-05-26 12:28:15 +0000297 aaa = ' a '*20
298 self.checkequal(['a']*20, aaa, 'split')
299 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
Andrew Dalke669fa182006-05-26 13:05:55 +0000300 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
Andrew Dalke984b9712006-05-26 11:11:38 +0000301
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000302 # by a char
303 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000304 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000305 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
306 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
307 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
308 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000309 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
310 sys.maxint-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000311 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
312 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
313 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000314 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
315 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000316 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
317
Andrew Dalke005aee22006-05-26 12:28:15 +0000318 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
319 self.checkequal(['a']*15 +['a|a|a|a|a'],
320 ('a|'*20)[:-1], 'split', '|', 15)
321
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000322 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000323 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000324 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
325 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
326 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
327 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000328 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
329 sys.maxint-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000330 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
331 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000332 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000333 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
334 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
335 'split', 'test')
336 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000337 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
338 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
339 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
340 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
341 self.checkequal([''], '', 'split', 'aaa')
342 self.checkequal(['aa'], 'aa', 'split', 'aaa')
Andrew Dalke5cc60092006-05-26 12:31:00 +0000343 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
344 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000345
346 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
347 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
348 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
349 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000350
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000351 # mixed use of str and unicode
352 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
353
354 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000355 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
356
Andrew Dalke005aee22006-05-26 12:28:15 +0000357 # null case
358 self.checkraises(ValueError, 'hello', 'split', '')
359 self.checkraises(ValueError, 'hello', 'split', '', 0)
360
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000361 def test_rsplit(self):
362 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
363 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000364
365 # by whitespace
366 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000367 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
368 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
369 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
370 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000371 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
372 sys.maxint-20)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000373 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000374 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000375 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000376
Andrew Dalke669fa182006-05-26 13:05:55 +0000377 self.checkequal([], ' ', 'rsplit')
378 self.checkequal(['a'], ' a ', 'rsplit')
379 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
380 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
381 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
382 None, 1)
383 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
384 None, 2)
385 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
386 aaa = ' a '*20
387 self.checkequal(['a']*20, aaa, 'rsplit')
388 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
389 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
390
391
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000392 # by a char
393 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
394 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
395 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
396 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
397 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000398 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
399 sys.maxint-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000400 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
401 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
402 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Andrew Dalke669fa182006-05-26 13:05:55 +0000403 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
404 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
405
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000406 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
407
Andrew Dalke669fa182006-05-26 13:05:55 +0000408 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
409 self.checkequal(['a|a|a|a|a']+['a']*15,
410 ('a|'*20)[:-1], 'rsplit', '|', 15)
411
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000412 # by string
413 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
414 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
415 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
416 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
417 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000418 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
419 sys.maxint-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000420 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
421 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
422 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000423 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
424 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
425 'rsplit', 'test')
426 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
427 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
428 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
429 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
430 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
431 self.checkequal([''], '', 'rsplit', 'aaa')
432 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
433 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
434 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
435
436 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
437 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
438 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
439 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000440
441 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000442 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000443
444 # argument type
445 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000446
Andrew Dalke669fa182006-05-26 13:05:55 +0000447 # null case
448 self.checkraises(ValueError, 'hello', 'rsplit', '')
449 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
450
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000451 def test_strip(self):
452 self.checkequal('hello', ' hello ', 'strip')
453 self.checkequal('hello ', ' hello ', 'lstrip')
454 self.checkequal(' hello', ' hello ', 'rstrip')
455 self.checkequal('hello', 'hello', 'strip')
456
Neal Norwitzffe33b72003-04-10 22:35:32 +0000457 # strip/lstrip/rstrip with None arg
458 self.checkequal('hello', ' hello ', 'strip', None)
459 self.checkequal('hello ', ' hello ', 'lstrip', None)
460 self.checkequal(' hello', ' hello ', 'rstrip', None)
461 self.checkequal('hello', 'hello', 'strip', None)
462
463 # strip/lstrip/rstrip with str arg
464 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
465 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
466 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
467 self.checkequal('hello', 'hello', 'strip', 'xyz')
468
469 # strip/lstrip/rstrip with unicode arg
470 if test_support.have_unicode:
471 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
472 'strip', unicode('xyz', 'ascii'))
473 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
474 'lstrip', unicode('xyz', 'ascii'))
475 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
476 'rstrip', unicode('xyz', 'ascii'))
477 self.checkequal(unicode('hello', 'ascii'), 'hello',
478 'strip', unicode('xyz', 'ascii'))
479
480 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
481 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
482 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
483
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000484 def test_ljust(self):
485 self.checkequal('abc ', 'abc', 'ljust', 10)
486 self.checkequal('abc ', 'abc', 'ljust', 6)
487 self.checkequal('abc', 'abc', 'ljust', 3)
488 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000489 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000490 self.checkraises(TypeError, 'abc', 'ljust')
491
492 def test_rjust(self):
493 self.checkequal(' abc', 'abc', 'rjust', 10)
494 self.checkequal(' abc', 'abc', 'rjust', 6)
495 self.checkequal('abc', 'abc', 'rjust', 3)
496 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000497 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000498 self.checkraises(TypeError, 'abc', 'rjust')
499
500 def test_center(self):
501 self.checkequal(' abc ', 'abc', 'center', 10)
502 self.checkequal(' abc ', 'abc', 'center', 6)
503 self.checkequal('abc', 'abc', 'center', 3)
504 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000505 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000506 self.checkraises(TypeError, 'abc', 'center')
507
508 def test_swapcase(self):
509 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
510
511 self.checkraises(TypeError, 'hello', 'swapcase', 42)
512
513 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000514 EQ = self.checkequal
515
516 # Operations on the empty string
517 EQ("", "", "replace", "", "")
Tim Peters80a18f02006-06-01 13:56:26 +0000518 EQ("A", "", "replace", "", "A")
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000519 EQ("", "", "replace", "A", "")
520 EQ("", "", "replace", "A", "A")
521 EQ("", "", "replace", "", "", 100)
522 EQ("", "", "replace", "", "", sys.maxint)
523
524 # interleave (from=="", 'to' gets inserted everywhere)
525 EQ("A", "A", "replace", "", "")
526 EQ("*A*", "A", "replace", "", "*")
527 EQ("*1A*1", "A", "replace", "", "*1")
528 EQ("*-#A*-#", "A", "replace", "", "*-#")
529 EQ("*-A*-A*-", "AA", "replace", "", "*-")
530 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
531 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
532 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
533 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
534 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
535 EQ("*-AA", "AA", "replace", "", "*-", 1)
536 EQ("AA", "AA", "replace", "", "*-", 0)
537
538 # single character deletion (from=="A", to=="")
539 EQ("", "A", "replace", "A", "")
540 EQ("", "AAA", "replace", "A", "")
541 EQ("", "AAA", "replace", "A", "", -1)
542 EQ("", "AAA", "replace", "A", "", sys.maxint)
543 EQ("", "AAA", "replace", "A", "", 4)
544 EQ("", "AAA", "replace", "A", "", 3)
545 EQ("A", "AAA", "replace", "A", "", 2)
546 EQ("AA", "AAA", "replace", "A", "", 1)
547 EQ("AAA", "AAA", "replace", "A", "", 0)
548 EQ("", "AAAAAAAAAA", "replace", "A", "")
549 EQ("BCD", "ABACADA", "replace", "A", "")
550 EQ("BCD", "ABACADA", "replace", "A", "", -1)
551 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
552 EQ("BCD", "ABACADA", "replace", "A", "", 5)
553 EQ("BCD", "ABACADA", "replace", "A", "", 4)
554 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
555 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
556 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
557 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
558 EQ("BCD", "ABCAD", "replace", "A", "")
559 EQ("BCD", "ABCADAA", "replace", "A", "")
560 EQ("BCD", "BCD", "replace", "A", "")
561 EQ("*************", "*************", "replace", "A", "")
562 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
563
564 # substring deletion (from=="the", to=="")
565 EQ("", "the", "replace", "the", "")
566 EQ("ater", "theater", "replace", "the", "")
567 EQ("", "thethe", "replace", "the", "")
568 EQ("", "thethethethe", "replace", "the", "")
569 EQ("aaaa", "theatheatheathea", "replace", "the", "")
570 EQ("that", "that", "replace", "the", "")
571 EQ("thaet", "thaet", "replace", "the", "")
572 EQ("here and re", "here and there", "replace", "the", "")
573 EQ("here and re and re", "here and there and there",
574 "replace", "the", "", sys.maxint)
575 EQ("here and re and re", "here and there and there",
576 "replace", "the", "", -1)
577 EQ("here and re and re", "here and there and there",
578 "replace", "the", "", 3)
579 EQ("here and re and re", "here and there and there",
580 "replace", "the", "", 2)
581 EQ("here and re and there", "here and there and there",
582 "replace", "the", "", 1)
583 EQ("here and there and there", "here and there and there",
584 "replace", "the", "", 0)
585 EQ("here and re and re", "here and there and there", "replace", "the", "")
586
587 EQ("abc", "abc", "replace", "the", "")
588 EQ("abcdefg", "abcdefg", "replace", "the", "")
589
590 # substring deletion (from=="bob", to=="")
591 EQ("bob", "bbobob", "replace", "bob", "")
592 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
593 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
594 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000595
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000596 # single character replace in place (len(from)==len(to)==1)
597 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
598 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
599 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
600 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
601 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
602 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
603 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
604 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
605
606 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
607 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
608 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
609 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
610 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
611
612 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000613
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000614 # substring replace in place (len(from)==len(to) > 1)
615 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
616 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
617 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
618 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
619 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
620 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
621 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
622 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
623 EQ("cobob", "bobob", "replace", "bob", "cob")
624 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
625 EQ("bobob", "bobob", "replace", "bot", "bot")
626
627 # replace single character (len(from)==1, len(to)>1)
628 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
629 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
630 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
631 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
632 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
633 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
634 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
635
636 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
637
638 # replace substring (len(from)>1, len(to)!=len(from))
639 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
640 "replace", "spam", "ham")
641 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
642 "replace", "spam", "ham", sys.maxint)
643 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
644 "replace", "spam", "ham", -1)
645 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
646 "replace", "spam", "ham", 4)
647 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
648 "replace", "spam", "ham", 3)
649 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
650 "replace", "spam", "ham", 2)
651 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
652 "replace", "spam", "ham", 1)
653 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
654 "replace", "spam", "ham", 0)
655
656 EQ("bobob", "bobobob", "replace", "bobob", "bob")
657 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
658 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000659
Neal Norwitzf71ec5a2006-07-30 06:57:04 +0000660 ba = buffer('a')
661 bb = buffer('b')
662 EQ("bbc", "abc", "replace", ba, bb)
663 EQ("aac", "abc", "replace", bb, ba)
664
Tim Petersbeaec0c2006-05-24 20:27:18 +0000665 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000666 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
667 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
668 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
669 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
670 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
671 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
672 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
673 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
674 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
675 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
676 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
677 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
678 self.checkequal('', '', 'replace', '', '')
679 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
680 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
681 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
682 # MemoryError due to empty result (platform malloc issue when requesting
683 # 0 bytes).
684 self.checkequal('', '123', 'replace', '123', '')
685 self.checkequal('', '123123', 'replace', '123', '')
686 self.checkequal('x', '123x123', 'replace', '123', '')
687
688 self.checkraises(TypeError, 'hello', 'replace')
689 self.checkraises(TypeError, 'hello', 'replace', 42)
690 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
691 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
692
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000693 def test_replace_overflow(self):
694 # Check for overflow checking on 32 bit machines
Kristján Valur Jónsson7bca0272007-05-07 13:33:39 +0000695 if sys.maxint != 2147483647 or struct.calcsize("P") > 4:
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000696 return
697 A2_16 = "A" * (2**16)
698 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
699 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
700 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000701
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000702 def test_zfill(self):
703 self.checkequal('123', '123', 'zfill', 2)
704 self.checkequal('123', '123', 'zfill', 3)
705 self.checkequal('0123', '123', 'zfill', 4)
706 self.checkequal('+123', '+123', 'zfill', 3)
707 self.checkequal('+123', '+123', 'zfill', 4)
708 self.checkequal('+0123', '+123', 'zfill', 5)
709 self.checkequal('-123', '-123', 'zfill', 3)
710 self.checkequal('-123', '-123', 'zfill', 4)
711 self.checkequal('-0123', '-123', 'zfill', 5)
712 self.checkequal('000', '', 'zfill', 3)
713 self.checkequal('34', '34', 'zfill', 1)
714 self.checkequal('0034', '34', 'zfill', 4)
715
716 self.checkraises(TypeError, '123', 'zfill')
717
718class MixinStrUnicodeUserStringTest:
719 # additional tests that only work for
720 # stringlike objects, i.e. str, unicode, UserString
721 # (but not the string module)
722
723 def test_islower(self):
724 self.checkequal(False, '', 'islower')
725 self.checkequal(True, 'a', 'islower')
726 self.checkequal(False, 'A', 'islower')
727 self.checkequal(False, '\n', 'islower')
728 self.checkequal(True, 'abc', 'islower')
729 self.checkequal(False, 'aBc', 'islower')
730 self.checkequal(True, 'abc\n', 'islower')
731 self.checkraises(TypeError, 'abc', 'islower', 42)
732
733 def test_isupper(self):
734 self.checkequal(False, '', 'isupper')
735 self.checkequal(False, 'a', 'isupper')
736 self.checkequal(True, 'A', 'isupper')
737 self.checkequal(False, '\n', 'isupper')
738 self.checkequal(True, 'ABC', 'isupper')
739 self.checkequal(False, 'AbC', 'isupper')
740 self.checkequal(True, 'ABC\n', 'isupper')
741 self.checkraises(TypeError, 'abc', 'isupper', 42)
742
743 def test_istitle(self):
744 self.checkequal(False, '', 'istitle')
745 self.checkequal(False, 'a', 'istitle')
746 self.checkequal(True, 'A', 'istitle')
747 self.checkequal(False, '\n', 'istitle')
748 self.checkequal(True, 'A Titlecased Line', 'istitle')
749 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
750 self.checkequal(True, 'A Titlecased, Line', 'istitle')
751 self.checkequal(False, 'Not a capitalized String', 'istitle')
752 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
753 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
754 self.checkequal(False, 'NOT', 'istitle')
755 self.checkraises(TypeError, 'abc', 'istitle', 42)
756
757 def test_isspace(self):
758 self.checkequal(False, '', 'isspace')
759 self.checkequal(False, 'a', 'isspace')
760 self.checkequal(True, ' ', 'isspace')
761 self.checkequal(True, '\t', 'isspace')
762 self.checkequal(True, '\r', 'isspace')
763 self.checkequal(True, '\n', 'isspace')
764 self.checkequal(True, ' \t\r\n', 'isspace')
765 self.checkequal(False, ' \t\r\na', 'isspace')
766 self.checkraises(TypeError, 'abc', 'isspace', 42)
767
768 def test_isalpha(self):
769 self.checkequal(False, '', 'isalpha')
770 self.checkequal(True, 'a', 'isalpha')
771 self.checkequal(True, 'A', 'isalpha')
772 self.checkequal(False, '\n', 'isalpha')
773 self.checkequal(True, 'abc', 'isalpha')
774 self.checkequal(False, 'aBc123', 'isalpha')
775 self.checkequal(False, 'abc\n', 'isalpha')
776 self.checkraises(TypeError, 'abc', 'isalpha', 42)
777
778 def test_isalnum(self):
779 self.checkequal(False, '', 'isalnum')
780 self.checkequal(True, 'a', 'isalnum')
781 self.checkequal(True, 'A', 'isalnum')
782 self.checkequal(False, '\n', 'isalnum')
783 self.checkequal(True, '123abc456', 'isalnum')
784 self.checkequal(True, 'a1b3c', 'isalnum')
785 self.checkequal(False, 'aBc000 ', 'isalnum')
786 self.checkequal(False, 'abc\n', 'isalnum')
787 self.checkraises(TypeError, 'abc', 'isalnum', 42)
788
789 def test_isdigit(self):
790 self.checkequal(False, '', 'isdigit')
791 self.checkequal(False, 'a', 'isdigit')
792 self.checkequal(True, '0', 'isdigit')
793 self.checkequal(True, '0123456789', 'isdigit')
794 self.checkequal(False, '0123456789a', 'isdigit')
795
796 self.checkraises(TypeError, 'abc', 'isdigit', 42)
797
798 def test_title(self):
799 self.checkequal(' Hello ', ' hello ', 'title')
800 self.checkequal('Hello ', 'hello ', 'title')
801 self.checkequal('Hello ', 'Hello ', 'title')
802 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
803 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
804 self.checkequal('Getint', "getInt", 'title')
805 self.checkraises(TypeError, 'hello', 'title', 42)
806
807 def test_splitlines(self):
808 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
809 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
810 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
811 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
812 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
813 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
814 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
815
816 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
817
818 def test_startswith(self):
819 self.checkequal(True, 'hello', 'startswith', 'he')
820 self.checkequal(True, 'hello', 'startswith', 'hello')
821 self.checkequal(False, 'hello', 'startswith', 'hello world')
822 self.checkequal(True, 'hello', 'startswith', '')
823 self.checkequal(False, 'hello', 'startswith', 'ello')
824 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
825 self.checkequal(True, 'hello', 'startswith', 'o', 4)
826 self.checkequal(False, 'hello', 'startswith', 'o', 5)
827 self.checkequal(True, 'hello', 'startswith', '', 5)
828 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
829 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
830 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
831 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
832
833 # test negative indices
834 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
835 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
836 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
837 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
838 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
839 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
840 self.checkequal(False, 'hello', 'startswith', 'o', -2)
841 self.checkequal(True, 'hello', 'startswith', 'o', -1)
842 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
843 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
844
845 self.checkraises(TypeError, 'hello', 'startswith')
846 self.checkraises(TypeError, 'hello', 'startswith', 42)
847
Georg Brandl24250812006-06-09 18:45:48 +0000848 # test tuple arguments
849 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
850 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
851 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
852 self.checkequal(False, 'hello', 'startswith', ())
853 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
854 'rld', 'lowo'), 3)
855 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
856 'rld'), 3)
857 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
858 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
859 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
860
861 self.checkraises(TypeError, 'hello', 'startswith', (42,))
862
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000863 def test_endswith(self):
864 self.checkequal(True, 'hello', 'endswith', 'lo')
865 self.checkequal(False, 'hello', 'endswith', 'he')
866 self.checkequal(True, 'hello', 'endswith', '')
867 self.checkequal(False, 'hello', 'endswith', 'hello world')
868 self.checkequal(False, 'helloworld', 'endswith', 'worl')
869 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
870 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
871 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
872 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
873 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
874 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
875 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
876 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
877 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
878
879 # test negative indices
880 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
881 self.checkequal(False, 'hello', 'endswith', 'he', -2)
882 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
883 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
884 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
885 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
886 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
887 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
888 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
889 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
890 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
891 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
892 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
893
894 self.checkraises(TypeError, 'hello', 'endswith')
895 self.checkraises(TypeError, 'hello', 'endswith', 42)
896
Georg Brandl24250812006-06-09 18:45:48 +0000897 # test tuple arguments
898 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
899 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
900 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
901 self.checkequal(False, 'hello', 'endswith', ())
902 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
903 'rld', 'lowo'), 3)
904 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
905 'rld'), 3, -1)
906 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
907 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
908 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
909
910 self.checkraises(TypeError, 'hello', 'endswith', (42,))
911
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000912 def test___contains__(self):
913 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
914 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
915 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
916 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
917 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
918 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
919 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
920 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
921 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
922
923 def test_subscript(self):
924 self.checkequal(u'a', 'abc', '__getitem__', 0)
925 self.checkequal(u'c', 'abc', '__getitem__', -1)
926 self.checkequal(u'a', 'abc', '__getitem__', 0L)
927 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
928 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
929 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
930 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
Georg Brandl24250812006-06-09 18:45:48 +0000931 # FIXME What about negative indices? This is handled differently by [] and __getitem__(slice)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000932
933 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
934
935 def test_slice(self):
936 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
937 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
938 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
939 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
940 self.checkequal('b', 'abc', '__getslice__', 1, 2)
941 self.checkequal('', 'abc', '__getslice__', 2, 2)
942 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
943 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
944 self.checkequal('', 'abc', '__getslice__', 2, 1)
945 # FIXME What about negative indizes? This is handled differently by [] and __getslice__
946
947 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
948
949 def test_mul(self):
950 self.checkequal('', 'abc', '__mul__', -1)
951 self.checkequal('', 'abc', '__mul__', 0)
952 self.checkequal('abc', 'abc', '__mul__', 1)
953 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
954 self.checkraises(TypeError, 'abc', '__mul__')
955 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +0000956 # XXX: on a 64-bit system, this doesn't raise an overflow error,
957 # but either raises a MemoryError, or succeeds (if you have 54TiB)
958 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000959
960 def test_join(self):
961 # join now works with any sequence type
962 # moved here, because the argument order is
963 # different in string.join (see the test in
964 # test.test_string.StringTest.test_join)
965 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
966 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Georg Brandl90e27d32006-06-10 06:40:50 +0000967 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
968 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000969 self.checkequal('w x y z', ' ', 'join', Sequence())
970 self.checkequal('abc', 'a', 'join', ('abc',))
971 self.checkequal('z', 'a', 'join', UserList(['z']))
972 if test_support.have_unicode:
973 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
974 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
975 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
976 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
977 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
978 for i in [5, 25, 125]:
979 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
980 ['a' * i] * i)
981 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
982 ('a' * i,) * i)
983
984 self.checkraises(TypeError, ' ', 'join', BadSeq1())
985 self.checkequal('a b c', ' ', 'join', BadSeq2())
986
987 self.checkraises(TypeError, ' ', 'join')
988 self.checkraises(TypeError, ' ', 'join', 7)
989 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +0000990 try:
991 def f():
992 yield 4 + ""
993 self.fixtype(' ').join(f())
994 except TypeError, e:
995 if '+' not in str(e):
996 self.fail('join() ate exception message')
997 else:
998 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000999
1000 def test_formatting(self):
1001 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1002 self.checkequal('+10+', '+%d+', '__mod__', 10)
1003 self.checkequal('a', "%c", '__mod__', "a")
1004 self.checkequal('a', "%c", '__mod__', "a")
1005 self.checkequal('"', "%c", '__mod__', 34)
1006 self.checkequal('$', "%c", '__mod__', 36)
1007 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001008 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001009
1010 for ordinal in (-100, 0x200000):
1011 # unicode raises ValueError, str raises OverflowError
1012 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1013
1014 self.checkequal(' 42', '%3ld', '__mod__', 42)
1015 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001016 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001017
1018 self.checkraises(TypeError, 'abc', '__mod__')
1019 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1020 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1021 self.checkraises(TypeError, '%c', '__mod__', (None,))
1022 self.checkraises(ValueError, '%(foo', '__mod__', {})
1023 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
1024
1025 # argument names with properly nested brackets are supported
1026 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1027
1028 # 100 is a magic number in PyUnicode_Format, this forces a resize
1029 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1030
1031 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1032 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1033 self.checkraises(ValueError, '%10', '__mod__', (42,))
1034
1035 def test_floatformatting(self):
1036 # float formatting
1037 for prec in xrange(100):
1038 format = '%%.%if' % prec
1039 value = 0.01
1040 for x in xrange(60):
1041 value = value * 3.141592655 / 3.0 * 10.0
1042 # The formatfloat() code in stringobject.c and
1043 # unicodeobject.c uses a 120 byte buffer and switches from
1044 # 'f' formatting to 'g' at precision 50, so we expect
1045 # OverflowErrors for the ranges x < 50 and prec >= 67.
1046 if x < 50 and prec >= 67:
1047 self.checkraises(OverflowError, format, "__mod__", value)
1048 else:
1049 self.checkcall(format, "__mod__", value)
1050
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001051 def test_inplace_rewrites(self):
1052 # Check that strings don't copy and modify cached single-character strings
1053 self.checkequal('a', 'A', 'lower')
1054 self.checkequal(True, 'A', 'isupper')
1055 self.checkequal('A', 'a', 'upper')
1056 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001057
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001058 self.checkequal('a', 'A', 'replace', 'A', 'a')
1059 self.checkequal(True, 'A', 'isupper')
1060
1061 self.checkequal('A', 'a', 'capitalize')
1062 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001063
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001064 self.checkequal('A', 'a', 'swapcase')
1065 self.checkequal(True, 'a', 'islower')
1066
1067 self.checkequal('A', 'a', 'title')
1068 self.checkequal(True, 'a', 'islower')
1069
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001070 def test_partition(self):
1071
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001072 self.checkequal(('this is the par', 'ti', 'tion method'),
1073 'this is the partition method', 'partition', 'ti')
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001074
1075 # from raymond's original specification
1076 S = 'http://www.python.org'
1077 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1078 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1079 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1080 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1081
1082 self.checkraises(ValueError, S, 'partition', '')
1083 self.checkraises(TypeError, S, 'partition', None)
1084
Amaury Forgeot d'Arcafa0d582008-09-01 20:05:08 +00001085 # mixed use of str and unicode
1086 self.assertEqual('a/b/c'.partition(u'/'), ('a', '/', 'b/c'))
1087
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001088 def test_rpartition(self):
1089
1090 self.checkequal(('this is the rparti', 'ti', 'on method'),
1091 'this is the rpartition method', 'rpartition', 'ti')
1092
1093 # from raymond's original specification
1094 S = 'http://www.python.org'
1095 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Neal Norwitz29a5fdb2006-09-05 02:21:38 +00001096 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001097 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1098 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1099
1100 self.checkraises(ValueError, S, 'rpartition', '')
1101 self.checkraises(TypeError, S, 'rpartition', None)
1102
Amaury Forgeot d'Arcafa0d582008-09-01 20:05:08 +00001103 # mixed use of str and unicode
1104 self.assertEqual('a/b/c'.rpartition(u'/'), ('a/b', '/', 'c'))
Walter Dörwald57d88e52004-08-26 16:53:04 +00001105
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001106class MixinStrStringUserStringTest:
1107 # Additional tests for 8bit strings, i.e. str, UserString and
1108 # the string module
1109
1110 def test_maketrans(self):
1111 self.assertEqual(
1112 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
1113 string.maketrans('abc', 'xyz')
1114 )
1115 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
1116
1117 def test_translate(self):
1118 table = string.maketrans('abc', 'xyz')
1119 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
1120
1121 table = string.maketrans('a', 'A')
1122 self.checkequal('Abc', 'abc', 'translate', table)
1123 self.checkequal('xyz', 'xyz', 'translate', table)
1124 self.checkequal('yz', 'xyz', 'translate', table, 'x')
1125 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
1126 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001127
1128
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001129class MixinStrUserStringTest:
1130 # Additional tests that only work with
1131 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001132
Walter Dörwald6eea7892005-07-28 16:49:15 +00001133 if test_support.have_unicode:
1134 def test_encoding_decoding(self):
1135 codecs = [('rot13', 'uryyb jbeyq'),
1136 ('base64', 'aGVsbG8gd29ybGQ=\n'),
1137 ('hex', '68656c6c6f20776f726c64'),
1138 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
1139 for encoding, data in codecs:
1140 self.checkequal(data, 'hello world', 'encode', encoding)
1141 self.checkequal('hello world', data, 'decode', encoding)
1142 # zlib is optional, so we make the test optional too...
1143 try:
1144 import zlib
1145 except ImportError:
1146 pass
1147 else:
1148 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
1149 self.checkequal(data, 'hello world', 'encode', 'zlib')
1150 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +00001151
Walter Dörwald6eea7892005-07-28 16:49:15 +00001152 self.checkraises(TypeError, 'xyz', 'decode', 42)
1153 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +00001154
1155
1156class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001157 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001158
1159 def test_bug1001011(self):
1160 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001161 # involving a subclass.
1162 # Make sure that it is of the appropriate type.
1163 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001164 t = self.type2test
1165 class subclass(t):
1166 pass
1167 s1 = subclass("abcd")
1168 s2 = t().join([s1])
1169 self.assert_(s1 is not s2)
1170 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001171
1172 s1 = t("abcd")
1173 s2 = t().join([s1])
1174 self.assert_(s1 is s2)
1175
1176 # Should also test mixed-type join.
1177 if t is unicode:
1178 s1 = subclass("abcd")
1179 s2 = "".join([s1])
1180 self.assert_(s1 is not s2)
1181 self.assert_(type(s2) is t)
1182
1183 s1 = t("abcd")
1184 s2 = "".join([s1])
1185 self.assert_(s1 is s2)
1186
1187 elif t is str:
1188 s1 = subclass("abcd")
1189 s2 = u"".join([s1])
1190 self.assert_(s1 is not s2)
1191 self.assert_(type(s2) is unicode) # promotes!
1192
1193 s1 = t("abcd")
1194 s2 = u"".join([s1])
1195 self.assert_(s1 is not s2)
1196 self.assert_(type(s2) is unicode) # promotes!
1197
1198 else:
1199 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)