blob: 5d4f9eb6aa3270ba07d1c1dab540b29233a6a7d0 [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ónsson170eee92007-05-03 20:09:56 +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'Arcfc5ea392008-09-26 22:34:08 +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
Facundo Batista57d56692007-11-16 18:04:14 +0000170 # to check the ability to pass None as defaults
171 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
172 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
173 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
174 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
175 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
176
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000177 self.checkraises(TypeError, 'hello', 'find')
178 self.checkraises(TypeError, 'hello', 'find', 42)
179
Amaury Forgeot d'Arcfc5ea392008-09-26 22:34:08 +0000180 self.checkequal(0, '', 'find', '')
181 self.checkequal(-1, '', 'find', '', 1, 1)
182 self.checkequal(-1, '', 'find', '', sys.maxint, 0)
183
184 self.checkequal(-1, '', 'find', 'xx')
185 self.checkequal(-1, '', 'find', 'xx', 1, 1)
186 self.checkequal(-1, '', 'find', 'xx', sys.maxint, 0)
187
Antoine Pitrou83f86e82010-01-02 21:47:10 +0000188 # issue 7458
189 self.checkequal(-1, 'ab', 'find', 'xxx', sys.maxsize + 1, 0)
190
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000191 # For a variety of combinations,
192 # verify that str.find() matches __contains__
193 # and that the found substring is really at that location
194 charset = ['', 'a', 'b', 'c']
195 digits = 5
196 base = len(charset)
197 teststrings = set()
198 for i in xrange(base ** digits):
199 entry = []
200 for j in xrange(digits):
201 i, m = divmod(i, base)
202 entry.append(charset[m])
203 teststrings.add(''.join(entry))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000204 teststrings = list(teststrings)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000205 for i in teststrings:
206 i = self.fixtype(i)
207 for j in teststrings:
208 loc = i.find(j)
209 r1 = (loc != -1)
210 r2 = j in i
211 if r1 != r2:
212 self.assertEqual(r1, r2)
213 if loc != -1:
214 self.assertEqual(i[loc:loc+len(j)], j)
215
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000216 def test_rfind(self):
217 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
218 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
219 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
220 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
221
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000222 self.checkequal(3, 'abc', 'rfind', '', 0)
223 self.checkequal(3, 'abc', 'rfind', '', 3)
224 self.checkequal(-1, 'abc', 'rfind', '', 4)
225
Facundo Batista57d56692007-11-16 18:04:14 +0000226 # to check the ability to pass None as defaults
227 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
228 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
229 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
230 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
231 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
232
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000233 self.checkraises(TypeError, 'hello', 'rfind')
234 self.checkraises(TypeError, 'hello', 'rfind', 42)
235
Antoine Pitrou5b7139a2010-01-02 21:12:58 +0000236 # For a variety of combinations,
237 # verify that str.rfind() matches __contains__
238 # and that the found substring is really at that location
239 charset = ['', 'a', 'b', 'c']
240 digits = 5
241 base = len(charset)
242 teststrings = set()
243 for i in xrange(base ** digits):
244 entry = []
245 for j in xrange(digits):
246 i, m = divmod(i, base)
247 entry.append(charset[m])
248 teststrings.add(''.join(entry))
249 teststrings = list(teststrings)
250 for i in teststrings:
251 i = self.fixtype(i)
252 for j in teststrings:
253 loc = i.rfind(j)
254 r1 = (loc != -1)
255 r2 = j in i
256 if r1 != r2:
257 self.assertEqual(r1, r2)
258 if loc != -1:
259 self.assertEqual(i[loc:loc+len(j)], j)
260
Antoine Pitrou83f86e82010-01-02 21:47:10 +0000261 # issue 7458
262 self.checkequal(-1, 'ab', 'rfind', 'xxx', sys.maxsize + 1, 0)
263
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000264 def test_index(self):
265 self.checkequal(0, 'abcdefghiabc', 'index', '')
266 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
267 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
268 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
269
270 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
271 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
272 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
273 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
274
Facundo Batista57d56692007-11-16 18:04:14 +0000275 # to check the ability to pass None as defaults
276 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
277 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
278 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
279 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
280 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
281
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000282 self.checkraises(TypeError, 'hello', 'index')
283 self.checkraises(TypeError, 'hello', 'index', 42)
284
285 def test_rindex(self):
286 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
287 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
288 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
289 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
290
291 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
292 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
293 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
294 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
295 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
296
Facundo Batista57d56692007-11-16 18:04:14 +0000297 # to check the ability to pass None as defaults
298 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
299 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
300 self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
301 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
302 self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
303
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000304 self.checkraises(TypeError, 'hello', 'rindex')
305 self.checkraises(TypeError, 'hello', 'rindex', 42)
306
307 def test_lower(self):
308 self.checkequal('hello', 'HeLLo', 'lower')
309 self.checkequal('hello', 'hello', 'lower')
310 self.checkraises(TypeError, 'hello', 'lower', 42)
311
312 def test_upper(self):
313 self.checkequal('HELLO', 'HeLLo', 'upper')
314 self.checkequal('HELLO', 'HELLO', 'upper')
315 self.checkraises(TypeError, 'hello', 'upper', 42)
316
317 def test_expandtabs(self):
318 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
319 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
320 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
321 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
322 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
323 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
324 self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
Neal Norwitz5c9a81a2007-06-11 02:16:10 +0000325 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000326
327 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
Neal Norwitz5c9a81a2007-06-11 02:16:10 +0000328 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
329 if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
330 self.checkraises(OverflowError,
331 '\ta\n\tb', 'expandtabs', sys.maxint)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000332
333 def test_split(self):
334 self.checkequal(['this', 'is', 'the', 'split', 'function'],
335 'this is the split function', 'split')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000336
337 # by whitespace
338 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000339 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
340 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
341 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
342 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000343 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
344 sys.maxint-1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000345 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000346 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000347 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000348
Andrew Dalke984b9712006-05-26 11:11:38 +0000349 self.checkequal([], ' ', 'split')
350 self.checkequal(['a'], ' a ', 'split')
351 self.checkequal(['a', 'b'], ' a b ', 'split')
352 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
353 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
354 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
Andrew Dalke03fb4442006-05-26 11:15:22 +0000355 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
Andrew Dalke005aee22006-05-26 12:28:15 +0000356 aaa = ' a '*20
357 self.checkequal(['a']*20, aaa, 'split')
358 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
Andrew Dalke669fa182006-05-26 13:05:55 +0000359 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
Andrew Dalke984b9712006-05-26 11:11:38 +0000360
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000361 # by a char
362 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000363 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000364 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
365 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
366 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
367 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000368 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
369 sys.maxint-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000370 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
371 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
372 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000373 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
374 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000375 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
376
Andrew Dalke005aee22006-05-26 12:28:15 +0000377 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
378 self.checkequal(['a']*15 +['a|a|a|a|a'],
379 ('a|'*20)[:-1], 'split', '|', 15)
380
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000381 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000382 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000383 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
384 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
385 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
386 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000387 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
388 sys.maxint-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000389 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
390 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000391 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000392 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
393 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
394 'split', 'test')
395 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000396 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
397 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
398 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
399 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
400 self.checkequal([''], '', 'split', 'aaa')
401 self.checkequal(['aa'], 'aa', 'split', 'aaa')
Andrew Dalke5cc60092006-05-26 12:31:00 +0000402 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
403 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000404
405 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
406 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
407 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
408 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000409
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000410 # mixed use of str and unicode
411 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
412
413 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000414 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
415
Andrew Dalke005aee22006-05-26 12:28:15 +0000416 # null case
417 self.checkraises(ValueError, 'hello', 'split', '')
418 self.checkraises(ValueError, 'hello', 'split', '', 0)
419
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000420 def test_rsplit(self):
421 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
422 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000423
424 # by whitespace
425 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000426 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
427 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
428 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
429 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000430 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
431 sys.maxint-20)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000432 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000433 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000434 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000435
Andrew Dalke669fa182006-05-26 13:05:55 +0000436 self.checkequal([], ' ', 'rsplit')
437 self.checkequal(['a'], ' a ', 'rsplit')
438 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
439 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
440 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
441 None, 1)
442 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
443 None, 2)
444 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
445 aaa = ' a '*20
446 self.checkequal(['a']*20, aaa, 'rsplit')
447 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
448 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
449
450
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000451 # by a char
452 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
453 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
454 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
455 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
456 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000457 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
458 sys.maxint-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000459 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
460 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
461 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Andrew Dalke669fa182006-05-26 13:05:55 +0000462 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
463 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
464
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000465 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
466
Andrew Dalke669fa182006-05-26 13:05:55 +0000467 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
468 self.checkequal(['a|a|a|a|a']+['a']*15,
469 ('a|'*20)[:-1], 'rsplit', '|', 15)
470
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000471 # by string
472 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
473 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
474 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
475 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
476 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000477 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
478 sys.maxint-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000479 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
480 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
481 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000482 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
483 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
484 'rsplit', 'test')
485 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
486 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
487 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
488 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
489 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
490 self.checkequal([''], '', 'rsplit', 'aaa')
491 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
492 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
493 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
494
495 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
496 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
497 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
498 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000499
500 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000501 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000502
503 # argument type
504 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000505
Andrew Dalke669fa182006-05-26 13:05:55 +0000506 # null case
507 self.checkraises(ValueError, 'hello', 'rsplit', '')
508 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
509
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000510 def test_strip(self):
511 self.checkequal('hello', ' hello ', 'strip')
512 self.checkequal('hello ', ' hello ', 'lstrip')
513 self.checkequal(' hello', ' hello ', 'rstrip')
514 self.checkequal('hello', 'hello', 'strip')
515
Neal Norwitzffe33b72003-04-10 22:35:32 +0000516 # strip/lstrip/rstrip with None arg
517 self.checkequal('hello', ' hello ', 'strip', None)
518 self.checkequal('hello ', ' hello ', 'lstrip', None)
519 self.checkequal(' hello', ' hello ', 'rstrip', None)
520 self.checkequal('hello', 'hello', 'strip', None)
521
522 # strip/lstrip/rstrip with str arg
523 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
524 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
525 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
526 self.checkequal('hello', 'hello', 'strip', 'xyz')
527
528 # strip/lstrip/rstrip with unicode arg
529 if test_support.have_unicode:
530 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
531 'strip', unicode('xyz', 'ascii'))
532 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
533 'lstrip', unicode('xyz', 'ascii'))
534 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
535 'rstrip', unicode('xyz', 'ascii'))
Christian Heimes1a6387e2008-03-26 12:49:49 +0000536 # XXX
537 #self.checkequal(unicode('hello', 'ascii'), 'hello',
538 # 'strip', unicode('xyz', 'ascii'))
Neal Norwitzffe33b72003-04-10 22:35:32 +0000539
540 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
541 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
542 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
543
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000544 def test_ljust(self):
545 self.checkequal('abc ', 'abc', 'ljust', 10)
546 self.checkequal('abc ', 'abc', 'ljust', 6)
547 self.checkequal('abc', 'abc', 'ljust', 3)
548 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000549 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000550 self.checkraises(TypeError, 'abc', 'ljust')
551
552 def test_rjust(self):
553 self.checkequal(' abc', 'abc', 'rjust', 10)
554 self.checkequal(' abc', 'abc', 'rjust', 6)
555 self.checkequal('abc', 'abc', 'rjust', 3)
556 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000557 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000558 self.checkraises(TypeError, 'abc', 'rjust')
559
560 def test_center(self):
561 self.checkequal(' abc ', 'abc', 'center', 10)
562 self.checkequal(' abc ', 'abc', 'center', 6)
563 self.checkequal('abc', 'abc', 'center', 3)
564 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000565 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000566 self.checkraises(TypeError, 'abc', 'center')
567
568 def test_swapcase(self):
569 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
570
571 self.checkraises(TypeError, 'hello', 'swapcase', 42)
572
573 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000574 EQ = self.checkequal
575
576 # Operations on the empty string
577 EQ("", "", "replace", "", "")
Tim Peters80a18f02006-06-01 13:56:26 +0000578 EQ("A", "", "replace", "", "A")
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000579 EQ("", "", "replace", "A", "")
580 EQ("", "", "replace", "A", "A")
581 EQ("", "", "replace", "", "", 100)
582 EQ("", "", "replace", "", "", sys.maxint)
583
584 # interleave (from=="", 'to' gets inserted everywhere)
585 EQ("A", "A", "replace", "", "")
586 EQ("*A*", "A", "replace", "", "*")
587 EQ("*1A*1", "A", "replace", "", "*1")
588 EQ("*-#A*-#", "A", "replace", "", "*-#")
589 EQ("*-A*-A*-", "AA", "replace", "", "*-")
590 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
591 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
592 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
593 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
594 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
595 EQ("*-AA", "AA", "replace", "", "*-", 1)
596 EQ("AA", "AA", "replace", "", "*-", 0)
597
598 # single character deletion (from=="A", to=="")
599 EQ("", "A", "replace", "A", "")
600 EQ("", "AAA", "replace", "A", "")
601 EQ("", "AAA", "replace", "A", "", -1)
602 EQ("", "AAA", "replace", "A", "", sys.maxint)
603 EQ("", "AAA", "replace", "A", "", 4)
604 EQ("", "AAA", "replace", "A", "", 3)
605 EQ("A", "AAA", "replace", "A", "", 2)
606 EQ("AA", "AAA", "replace", "A", "", 1)
607 EQ("AAA", "AAA", "replace", "A", "", 0)
608 EQ("", "AAAAAAAAAA", "replace", "A", "")
609 EQ("BCD", "ABACADA", "replace", "A", "")
610 EQ("BCD", "ABACADA", "replace", "A", "", -1)
611 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
612 EQ("BCD", "ABACADA", "replace", "A", "", 5)
613 EQ("BCD", "ABACADA", "replace", "A", "", 4)
614 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
615 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
616 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
617 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
618 EQ("BCD", "ABCAD", "replace", "A", "")
619 EQ("BCD", "ABCADAA", "replace", "A", "")
620 EQ("BCD", "BCD", "replace", "A", "")
621 EQ("*************", "*************", "replace", "A", "")
622 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
623
624 # substring deletion (from=="the", to=="")
625 EQ("", "the", "replace", "the", "")
626 EQ("ater", "theater", "replace", "the", "")
627 EQ("", "thethe", "replace", "the", "")
628 EQ("", "thethethethe", "replace", "the", "")
629 EQ("aaaa", "theatheatheathea", "replace", "the", "")
630 EQ("that", "that", "replace", "the", "")
631 EQ("thaet", "thaet", "replace", "the", "")
632 EQ("here and re", "here and there", "replace", "the", "")
633 EQ("here and re and re", "here and there and there",
634 "replace", "the", "", sys.maxint)
635 EQ("here and re and re", "here and there and there",
636 "replace", "the", "", -1)
637 EQ("here and re and re", "here and there and there",
638 "replace", "the", "", 3)
639 EQ("here and re and re", "here and there and there",
640 "replace", "the", "", 2)
641 EQ("here and re and there", "here and there and there",
642 "replace", "the", "", 1)
643 EQ("here and there and there", "here and there and there",
644 "replace", "the", "", 0)
645 EQ("here and re and re", "here and there and there", "replace", "the", "")
646
647 EQ("abc", "abc", "replace", "the", "")
648 EQ("abcdefg", "abcdefg", "replace", "the", "")
649
650 # substring deletion (from=="bob", to=="")
651 EQ("bob", "bbobob", "replace", "bob", "")
652 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
653 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
654 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000655
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000656 # single character replace in place (len(from)==len(to)==1)
657 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
658 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
659 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
660 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
661 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
662 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
663 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
664 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
665
666 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
667 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
668 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
669 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
670 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
671
672 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000673
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000674 # substring replace in place (len(from)==len(to) > 1)
675 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
676 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
677 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
678 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
679 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
680 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
681 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
682 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
683 EQ("cobob", "bobob", "replace", "bob", "cob")
684 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
685 EQ("bobob", "bobob", "replace", "bot", "bot")
686
687 # replace single character (len(from)==1, len(to)>1)
688 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
689 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
690 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
691 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
692 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
693 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
694 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
695
696 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
697
698 # replace substring (len(from)>1, len(to)!=len(from))
699 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
700 "replace", "spam", "ham")
701 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
702 "replace", "spam", "ham", sys.maxint)
703 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
704 "replace", "spam", "ham", -1)
705 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
706 "replace", "spam", "ham", 4)
707 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
708 "replace", "spam", "ham", 3)
709 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
710 "replace", "spam", "ham", 2)
711 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
712 "replace", "spam", "ham", 1)
713 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
714 "replace", "spam", "ham", 0)
715
716 EQ("bobob", "bobobob", "replace", "bobob", "bob")
717 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
718 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000719
Antoine Pitrou5b7139a2010-01-02 21:12:58 +0000720 # Silence Py3k warning
721 with test_support.check_warnings():
722 ba = buffer('a')
723 bb = buffer('b')
Neal Norwitzf71ec5a2006-07-30 06:57:04 +0000724 EQ("bbc", "abc", "replace", ba, bb)
725 EQ("aac", "abc", "replace", bb, ba)
726
Tim Petersbeaec0c2006-05-24 20:27:18 +0000727 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000728 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
729 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
730 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
731 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
732 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
733 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
734 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
735 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
736 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
737 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
738 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
739 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
740 self.checkequal('', '', 'replace', '', '')
741 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
742 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
743 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
744 # MemoryError due to empty result (platform malloc issue when requesting
745 # 0 bytes).
746 self.checkequal('', '123', 'replace', '123', '')
747 self.checkequal('', '123123', 'replace', '123', '')
748 self.checkequal('x', '123x123', 'replace', '123', '')
749
750 self.checkraises(TypeError, 'hello', 'replace')
751 self.checkraises(TypeError, 'hello', 'replace', 42)
752 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
753 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
754
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000755 def test_replace_overflow(self):
756 # Check for overflow checking on 32 bit machines
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000757 if sys.maxint != 2147483647 or struct.calcsize("P") > 4:
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000758 return
759 A2_16 = "A" * (2**16)
760 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
761 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
762 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000763
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000764 def test_zfill(self):
765 self.checkequal('123', '123', 'zfill', 2)
766 self.checkequal('123', '123', 'zfill', 3)
767 self.checkequal('0123', '123', 'zfill', 4)
768 self.checkequal('+123', '+123', 'zfill', 3)
769 self.checkequal('+123', '+123', 'zfill', 4)
770 self.checkequal('+0123', '+123', 'zfill', 5)
771 self.checkequal('-123', '-123', 'zfill', 3)
772 self.checkequal('-123', '-123', 'zfill', 4)
773 self.checkequal('-0123', '-123', 'zfill', 5)
774 self.checkequal('000', '', 'zfill', 3)
775 self.checkequal('34', '34', 'zfill', 1)
776 self.checkequal('0034', '34', 'zfill', 4)
777
778 self.checkraises(TypeError, '123', 'zfill')
779
Christian Heimes1a6387e2008-03-26 12:49:49 +0000780# XXX alias for py3k forward compatibility
781BaseTest = CommonTest
782
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000783class MixinStrUnicodeUserStringTest:
784 # additional tests that only work for
785 # stringlike objects, i.e. str, unicode, UserString
786 # (but not the string module)
787
788 def test_islower(self):
789 self.checkequal(False, '', 'islower')
790 self.checkequal(True, 'a', 'islower')
791 self.checkequal(False, 'A', 'islower')
792 self.checkequal(False, '\n', 'islower')
793 self.checkequal(True, 'abc', 'islower')
794 self.checkequal(False, 'aBc', 'islower')
795 self.checkequal(True, 'abc\n', 'islower')
796 self.checkraises(TypeError, 'abc', 'islower', 42)
797
798 def test_isupper(self):
799 self.checkequal(False, '', 'isupper')
800 self.checkequal(False, 'a', 'isupper')
801 self.checkequal(True, 'A', 'isupper')
802 self.checkequal(False, '\n', 'isupper')
803 self.checkequal(True, 'ABC', 'isupper')
804 self.checkequal(False, 'AbC', 'isupper')
805 self.checkequal(True, 'ABC\n', 'isupper')
806 self.checkraises(TypeError, 'abc', 'isupper', 42)
807
808 def test_istitle(self):
809 self.checkequal(False, '', 'istitle')
810 self.checkequal(False, 'a', 'istitle')
811 self.checkequal(True, 'A', 'istitle')
812 self.checkequal(False, '\n', 'istitle')
813 self.checkequal(True, 'A Titlecased Line', 'istitle')
814 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
815 self.checkequal(True, 'A Titlecased, Line', 'istitle')
816 self.checkequal(False, 'Not a capitalized String', 'istitle')
817 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
818 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
819 self.checkequal(False, 'NOT', 'istitle')
820 self.checkraises(TypeError, 'abc', 'istitle', 42)
821
822 def test_isspace(self):
823 self.checkequal(False, '', 'isspace')
824 self.checkequal(False, 'a', 'isspace')
825 self.checkequal(True, ' ', 'isspace')
826 self.checkequal(True, '\t', 'isspace')
827 self.checkequal(True, '\r', 'isspace')
828 self.checkequal(True, '\n', 'isspace')
829 self.checkequal(True, ' \t\r\n', 'isspace')
830 self.checkequal(False, ' \t\r\na', 'isspace')
831 self.checkraises(TypeError, 'abc', 'isspace', 42)
832
833 def test_isalpha(self):
834 self.checkequal(False, '', 'isalpha')
835 self.checkequal(True, 'a', 'isalpha')
836 self.checkequal(True, 'A', 'isalpha')
837 self.checkequal(False, '\n', 'isalpha')
838 self.checkequal(True, 'abc', 'isalpha')
839 self.checkequal(False, 'aBc123', 'isalpha')
840 self.checkequal(False, 'abc\n', 'isalpha')
841 self.checkraises(TypeError, 'abc', 'isalpha', 42)
842
843 def test_isalnum(self):
844 self.checkequal(False, '', 'isalnum')
845 self.checkequal(True, 'a', 'isalnum')
846 self.checkequal(True, 'A', 'isalnum')
847 self.checkequal(False, '\n', 'isalnum')
848 self.checkequal(True, '123abc456', 'isalnum')
849 self.checkequal(True, 'a1b3c', 'isalnum')
850 self.checkequal(False, 'aBc000 ', 'isalnum')
851 self.checkequal(False, 'abc\n', 'isalnum')
852 self.checkraises(TypeError, 'abc', 'isalnum', 42)
853
854 def test_isdigit(self):
855 self.checkequal(False, '', 'isdigit')
856 self.checkequal(False, 'a', 'isdigit')
857 self.checkequal(True, '0', 'isdigit')
858 self.checkequal(True, '0123456789', 'isdigit')
859 self.checkequal(False, '0123456789a', 'isdigit')
860
861 self.checkraises(TypeError, 'abc', 'isdigit', 42)
862
863 def test_title(self):
864 self.checkequal(' Hello ', ' hello ', 'title')
865 self.checkequal('Hello ', 'hello ', 'title')
866 self.checkequal('Hello ', 'Hello ', 'title')
867 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
868 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
869 self.checkequal('Getint', "getInt", 'title')
870 self.checkraises(TypeError, 'hello', 'title', 42)
871
872 def test_splitlines(self):
873 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
874 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
875 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
876 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
877 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
878 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
879 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
880
881 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
882
883 def test_startswith(self):
884 self.checkequal(True, 'hello', 'startswith', 'he')
885 self.checkequal(True, 'hello', 'startswith', 'hello')
886 self.checkequal(False, 'hello', 'startswith', 'hello world')
887 self.checkequal(True, 'hello', 'startswith', '')
888 self.checkequal(False, 'hello', 'startswith', 'ello')
889 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
890 self.checkequal(True, 'hello', 'startswith', 'o', 4)
891 self.checkequal(False, 'hello', 'startswith', 'o', 5)
892 self.checkequal(True, 'hello', 'startswith', '', 5)
893 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
894 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
895 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
896 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
897
898 # test negative indices
899 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
900 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
901 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
902 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
903 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
904 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
905 self.checkequal(False, 'hello', 'startswith', 'o', -2)
906 self.checkequal(True, 'hello', 'startswith', 'o', -1)
907 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
908 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
909
910 self.checkraises(TypeError, 'hello', 'startswith')
911 self.checkraises(TypeError, 'hello', 'startswith', 42)
912
Georg Brandl24250812006-06-09 18:45:48 +0000913 # test tuple arguments
914 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
915 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
916 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
917 self.checkequal(False, 'hello', 'startswith', ())
918 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
919 'rld', 'lowo'), 3)
920 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
921 'rld'), 3)
922 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
923 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
924 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
925
926 self.checkraises(TypeError, 'hello', 'startswith', (42,))
927
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000928 def test_endswith(self):
929 self.checkequal(True, 'hello', 'endswith', 'lo')
930 self.checkequal(False, 'hello', 'endswith', 'he')
931 self.checkequal(True, 'hello', 'endswith', '')
932 self.checkequal(False, 'hello', 'endswith', 'hello world')
933 self.checkequal(False, 'helloworld', 'endswith', 'worl')
934 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
935 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
936 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
937 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
938 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
939 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
940 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
941 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
942 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
943
944 # test negative indices
945 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
946 self.checkequal(False, 'hello', 'endswith', 'he', -2)
947 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
948 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
949 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
950 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
951 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
952 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
953 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
954 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
955 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
956 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
957 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
958
959 self.checkraises(TypeError, 'hello', 'endswith')
960 self.checkraises(TypeError, 'hello', 'endswith', 42)
961
Georg Brandl24250812006-06-09 18:45:48 +0000962 # test tuple arguments
963 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
964 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
965 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
966 self.checkequal(False, 'hello', 'endswith', ())
967 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
968 'rld', 'lowo'), 3)
969 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
970 'rld'), 3, -1)
971 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
972 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
973 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
974
975 self.checkraises(TypeError, 'hello', 'endswith', (42,))
976
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000977 def test___contains__(self):
978 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
979 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
980 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
981 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
982 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
983 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
984 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
985 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
986 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
987
988 def test_subscript(self):
989 self.checkequal(u'a', 'abc', '__getitem__', 0)
990 self.checkequal(u'c', 'abc', '__getitem__', -1)
991 self.checkequal(u'a', 'abc', '__getitem__', 0L)
992 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
993 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
994 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
995 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000996
997 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
998
999 def test_slice(self):
1000 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
1001 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
1002 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
1003 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
1004 self.checkequal('b', 'abc', '__getslice__', 1, 2)
1005 self.checkequal('', 'abc', '__getslice__', 2, 2)
1006 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
1007 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
1008 self.checkequal('', 'abc', '__getslice__', 2, 1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001009
1010 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
1011
Thomas Wouters3ccec682007-08-28 15:28:19 +00001012 def test_extended_getslice(self):
1013 # Test extended slicing by comparing with list slicing.
1014 s = string.ascii_letters + string.digits
1015 indices = (0, None, 1, 3, 41, -1, -2, -37)
1016 for start in indices:
1017 for stop in indices:
1018 # Skip step 0 (invalid)
1019 for step in indices[1:]:
1020 L = list(s)[start:stop:step]
1021 self.checkequal(u"".join(L), s, '__getitem__',
1022 slice(start, stop, step))
1023
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001024 def test_mul(self):
1025 self.checkequal('', 'abc', '__mul__', -1)
1026 self.checkequal('', 'abc', '__mul__', 0)
1027 self.checkequal('abc', 'abc', '__mul__', 1)
1028 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
1029 self.checkraises(TypeError, 'abc', '__mul__')
1030 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +00001031 # XXX: on a 64-bit system, this doesn't raise an overflow error,
1032 # but either raises a MemoryError, or succeeds (if you have 54TiB)
1033 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001034
1035 def test_join(self):
1036 # join now works with any sequence type
1037 # moved here, because the argument order is
1038 # different in string.join (see the test in
1039 # test.test_string.StringTest.test_join)
1040 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
1041 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Georg Brandl90e27d32006-06-10 06:40:50 +00001042 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
1043 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001044 self.checkequal('w x y z', ' ', 'join', Sequence())
1045 self.checkequal('abc', 'a', 'join', ('abc',))
1046 self.checkequal('z', 'a', 'join', UserList(['z']))
1047 if test_support.have_unicode:
1048 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
1049 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
1050 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
1051 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
1052 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
1053 for i in [5, 25, 125]:
1054 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1055 ['a' * i] * i)
1056 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1057 ('a' * i,) * i)
1058
1059 self.checkraises(TypeError, ' ', 'join', BadSeq1())
1060 self.checkequal('a b c', ' ', 'join', BadSeq2())
1061
1062 self.checkraises(TypeError, ' ', 'join')
1063 self.checkraises(TypeError, ' ', 'join', 7)
1064 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001065 try:
1066 def f():
1067 yield 4 + ""
1068 self.fixtype(' ').join(f())
1069 except TypeError, e:
1070 if '+' not in str(e):
1071 self.fail('join() ate exception message')
1072 else:
1073 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001074
1075 def test_formatting(self):
1076 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1077 self.checkequal('+10+', '+%d+', '__mod__', 10)
1078 self.checkequal('a', "%c", '__mod__', "a")
1079 self.checkequal('a', "%c", '__mod__', "a")
1080 self.checkequal('"', "%c", '__mod__', 34)
1081 self.checkequal('$', "%c", '__mod__', 36)
1082 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001083 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001084
1085 for ordinal in (-100, 0x200000):
1086 # unicode raises ValueError, str raises OverflowError
1087 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1088
Facundo Batistac11cecf2008-02-24 03:17:21 +00001089 longvalue = sys.maxint + 10L
1090 slongvalue = str(longvalue)
1091 if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001092 self.checkequal(' 42', '%3ld', '__mod__', 42)
Facundo Batistac11cecf2008-02-24 03:17:21 +00001093 self.checkequal('42', '%d', '__mod__', 42L)
1094 self.checkequal('42', '%d', '__mod__', 42.0)
1095 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1096 self.checkcall('%d', '__mod__', float(longvalue))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001097 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001098 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001099
1100 self.checkraises(TypeError, 'abc', '__mod__')
1101 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1102 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1103 self.checkraises(TypeError, '%c', '__mod__', (None,))
1104 self.checkraises(ValueError, '%(foo', '__mod__', {})
1105 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
Facundo Batistac11cecf2008-02-24 03:17:21 +00001106 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
1107 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001108
1109 # argument names with properly nested brackets are supported
1110 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1111
1112 # 100 is a magic number in PyUnicode_Format, this forces a resize
1113 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1114
1115 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1116 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1117 self.checkraises(ValueError, '%10', '__mod__', (42,))
1118
1119 def test_floatformatting(self):
1120 # float formatting
1121 for prec in xrange(100):
1122 format = '%%.%if' % prec
1123 value = 0.01
1124 for x in xrange(60):
1125 value = value * 3.141592655 / 3.0 * 10.0
Mark Dickinson18cfada2009-11-23 18:46:41 +00001126 self.checkcall(format, "__mod__", value)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001127
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001128 def test_inplace_rewrites(self):
1129 # Check that strings don't copy and modify cached single-character strings
1130 self.checkequal('a', 'A', 'lower')
1131 self.checkequal(True, 'A', 'isupper')
1132 self.checkequal('A', 'a', 'upper')
1133 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001134
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001135 self.checkequal('a', 'A', 'replace', 'A', 'a')
1136 self.checkequal(True, 'A', 'isupper')
1137
1138 self.checkequal('A', 'a', 'capitalize')
1139 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001140
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001141 self.checkequal('A', 'a', 'swapcase')
1142 self.checkequal(True, 'a', 'islower')
1143
1144 self.checkequal('A', 'a', 'title')
1145 self.checkequal(True, 'a', 'islower')
1146
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001147 def test_partition(self):
1148
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001149 self.checkequal(('this is the par', 'ti', 'tion method'),
1150 'this is the partition method', 'partition', 'ti')
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001151
1152 # from raymond's original specification
1153 S = 'http://www.python.org'
1154 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1155 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1156 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1157 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1158
1159 self.checkraises(ValueError, S, 'partition', '')
1160 self.checkraises(TypeError, S, 'partition', None)
1161
Amaury Forgeot d'Arc3571fbf2008-09-01 19:52:00 +00001162 # mixed use of str and unicode
1163 self.assertEqual('a/b/c'.partition(u'/'), ('a', '/', 'b/c'))
1164
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001165 def test_rpartition(self):
1166
1167 self.checkequal(('this is the rparti', 'ti', 'on method'),
1168 'this is the rpartition method', 'rpartition', 'ti')
1169
1170 # from raymond's original specification
1171 S = 'http://www.python.org'
1172 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Raymond Hettingera0c95fa2006-09-04 15:32:48 +00001173 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001174 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1175 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1176
1177 self.checkraises(ValueError, S, 'rpartition', '')
1178 self.checkraises(TypeError, S, 'rpartition', None)
1179
Amaury Forgeot d'Arc3571fbf2008-09-01 19:52:00 +00001180 # mixed use of str and unicode
1181 self.assertEqual('a/b/c'.rpartition(u'/'), ('a/b', '/', 'c'))
Walter Dörwald57d88e52004-08-26 16:53:04 +00001182
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001183class MixinStrStringUserStringTest:
1184 # Additional tests for 8bit strings, i.e. str, UserString and
1185 # the string module
1186
1187 def test_maketrans(self):
1188 self.assertEqual(
1189 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
1190 string.maketrans('abc', 'xyz')
1191 )
1192 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
1193
1194 def test_translate(self):
1195 table = string.maketrans('abc', 'xyz')
1196 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
1197
1198 table = string.maketrans('a', 'A')
1199 self.checkequal('Abc', 'abc', 'translate', table)
1200 self.checkequal('xyz', 'xyz', 'translate', table)
1201 self.checkequal('yz', 'xyz', 'translate', table, 'x')
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001202 self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
Raymond Hettinger4db5fe92007-04-12 04:10:00 +00001203 self.checkequal('zyzzx', 'zyzzx', 'translate', None, '')
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001204 self.checkequal('zyzzx', 'zyzzx', 'translate', None)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001205 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
1206 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001207
1208
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001209class MixinStrUserStringTest:
1210 # Additional tests that only work with
1211 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001212
Walter Dörwald6eea7892005-07-28 16:49:15 +00001213 if test_support.have_unicode:
1214 def test_encoding_decoding(self):
1215 codecs = [('rot13', 'uryyb jbeyq'),
1216 ('base64', 'aGVsbG8gd29ybGQ=\n'),
1217 ('hex', '68656c6c6f20776f726c64'),
1218 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
1219 for encoding, data in codecs:
1220 self.checkequal(data, 'hello world', 'encode', encoding)
1221 self.checkequal('hello world', data, 'decode', encoding)
1222 # zlib is optional, so we make the test optional too...
1223 try:
1224 import zlib
1225 except ImportError:
1226 pass
1227 else:
1228 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
1229 self.checkequal(data, 'hello world', 'encode', 'zlib')
1230 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +00001231
Walter Dörwald6eea7892005-07-28 16:49:15 +00001232 self.checkraises(TypeError, 'xyz', 'decode', 42)
1233 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +00001234
1235
1236class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001237 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001238
1239 def test_bug1001011(self):
1240 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001241 # involving a subclass.
1242 # Make sure that it is of the appropriate type.
1243 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001244 t = self.type2test
1245 class subclass(t):
1246 pass
1247 s1 = subclass("abcd")
1248 s2 = t().join([s1])
1249 self.assert_(s1 is not s2)
1250 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001251
1252 s1 = t("abcd")
1253 s2 = t().join([s1])
1254 self.assert_(s1 is s2)
1255
1256 # Should also test mixed-type join.
1257 if t is unicode:
1258 s1 = subclass("abcd")
1259 s2 = "".join([s1])
1260 self.assert_(s1 is not s2)
1261 self.assert_(type(s2) is t)
1262
1263 s1 = t("abcd")
1264 s2 = "".join([s1])
1265 self.assert_(s1 is s2)
1266
1267 elif t is str:
1268 s1 = subclass("abcd")
1269 s2 = u"".join([s1])
1270 self.assert_(s1 is not s2)
1271 self.assert_(type(s2) is unicode) # promotes!
1272
1273 s1 = t("abcd")
1274 s2 = u"".join([s1])
1275 self.assert_(s1 is not s2)
1276 self.assert_(type(s2) is unicode) # promotes!
1277
1278 else:
1279 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)