blob: 3590b8e5b9ad427c1226ef03e214b1c8619511a7 [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
123 self.checkraises(TypeError, 'hello', 'count')
124 self.checkraises(TypeError, 'hello', 'count', 42)
125
Raymond Hettinger57e74472005-02-20 09:54:53 +0000126 # For a variety of combinations,
127 # verify that str.count() matches an equivalent function
128 # replacing all occurrences and then differencing the string lengths
129 charset = ['', 'a', 'b']
130 digits = 7
131 base = len(charset)
132 teststrings = set()
133 for i in xrange(base ** digits):
134 entry = []
135 for j in xrange(digits):
136 i, m = divmod(i, base)
137 entry.append(charset[m])
138 teststrings.add(''.join(entry))
139 teststrings = list(teststrings)
140 for i in teststrings:
141 i = self.fixtype(i)
142 n = len(i)
143 for j in teststrings:
144 r1 = i.count(j)
145 if j:
146 r2, rem = divmod(n - len(i.replace(j, '')), len(j))
147 else:
148 r2, rem = len(i)+1, 0
149 if rem or r1 != r2:
Neal Norwitzf71ec5a2006-07-30 06:57:04 +0000150 self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
151 self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000152
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000153 def test_find(self):
154 self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
155 self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
156 self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
157
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000158 self.checkequal(0, 'abc', 'find', '', 0)
159 self.checkequal(3, 'abc', 'find', '', 3)
160 self.checkequal(-1, 'abc', 'find', '', 4)
161
Facundo Batista57d56692007-11-16 18:04:14 +0000162 # to check the ability to pass None as defaults
163 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a')
164 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4)
165 self.checkequal(-1, 'rrarrrrrrrrra', 'find', 'a', 4, 6)
166 self.checkequal(12, 'rrarrrrrrrrra', 'find', 'a', 4, None)
167 self.checkequal( 2, 'rrarrrrrrrrra', 'find', 'a', None, 6)
168
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000169 self.checkraises(TypeError, 'hello', 'find')
170 self.checkraises(TypeError, 'hello', 'find', 42)
171
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000172 # For a variety of combinations,
173 # verify that str.find() matches __contains__
174 # and that the found substring is really at that location
175 charset = ['', 'a', 'b', 'c']
176 digits = 5
177 base = len(charset)
178 teststrings = set()
179 for i in xrange(base ** digits):
180 entry = []
181 for j in xrange(digits):
182 i, m = divmod(i, base)
183 entry.append(charset[m])
184 teststrings.add(''.join(entry))
Raymond Hettinger57e74472005-02-20 09:54:53 +0000185 teststrings = list(teststrings)
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +0000186 for i in teststrings:
187 i = self.fixtype(i)
188 for j in teststrings:
189 loc = i.find(j)
190 r1 = (loc != -1)
191 r2 = j in i
192 if r1 != r2:
193 self.assertEqual(r1, r2)
194 if loc != -1:
195 self.assertEqual(i[loc:loc+len(j)], j)
196
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000197 def test_rfind(self):
198 self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc')
199 self.checkequal(12, 'abcdefghiabc', 'rfind', '')
200 self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
201 self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
202
Fredrik Lundh93eff6f2006-05-30 17:11:48 +0000203 self.checkequal(3, 'abc', 'rfind', '', 0)
204 self.checkequal(3, 'abc', 'rfind', '', 3)
205 self.checkequal(-1, 'abc', 'rfind', '', 4)
206
Facundo Batista57d56692007-11-16 18:04:14 +0000207 # to check the ability to pass None as defaults
208 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a')
209 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4)
210 self.checkequal(-1, 'rrarrrrrrrrra', 'rfind', 'a', 4, 6)
211 self.checkequal(12, 'rrarrrrrrrrra', 'rfind', 'a', 4, None)
212 self.checkequal( 2, 'rrarrrrrrrrra', 'rfind', 'a', None, 6)
213
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000214 self.checkraises(TypeError, 'hello', 'rfind')
215 self.checkraises(TypeError, 'hello', 'rfind', 42)
216
217 def test_index(self):
218 self.checkequal(0, 'abcdefghiabc', 'index', '')
219 self.checkequal(3, 'abcdefghiabc', 'index', 'def')
220 self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
221 self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
222
223 self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
224 self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
225 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
226 self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
227
Facundo Batista57d56692007-11-16 18:04:14 +0000228 # to check the ability to pass None as defaults
229 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a')
230 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4)
231 self.checkraises(ValueError, 'rrarrrrrrrrra', 'index', 'a', 4, 6)
232 self.checkequal(12, 'rrarrrrrrrrra', 'index', 'a', 4, None)
233 self.checkequal( 2, 'rrarrrrrrrrra', 'index', 'a', None, 6)
234
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000235 self.checkraises(TypeError, 'hello', 'index')
236 self.checkraises(TypeError, 'hello', 'index', 42)
237
238 def test_rindex(self):
239 self.checkequal(12, 'abcdefghiabc', 'rindex', '')
240 self.checkequal(3, 'abcdefghiabc', 'rindex', 'def')
241 self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc')
242 self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
243
244 self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
245 self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
246 self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
247 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
248 self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
249
Facundo Batista57d56692007-11-16 18:04:14 +0000250 # to check the ability to pass None as defaults
251 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a')
252 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4)
253 self.checkraises(ValueError, 'rrarrrrrrrrra', 'rindex', 'a', 4, 6)
254 self.checkequal(12, 'rrarrrrrrrrra', 'rindex', 'a', 4, None)
255 self.checkequal( 2, 'rrarrrrrrrrra', 'rindex', 'a', None, 6)
256
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000257 self.checkraises(TypeError, 'hello', 'rindex')
258 self.checkraises(TypeError, 'hello', 'rindex', 42)
259
260 def test_lower(self):
261 self.checkequal('hello', 'HeLLo', 'lower')
262 self.checkequal('hello', 'hello', 'lower')
263 self.checkraises(TypeError, 'hello', 'lower', 42)
264
265 def test_upper(self):
266 self.checkequal('HELLO', 'HeLLo', 'upper')
267 self.checkequal('HELLO', 'HELLO', 'upper')
268 self.checkraises(TypeError, 'hello', 'upper', 42)
269
270 def test_expandtabs(self):
271 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
272 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
273 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
274 self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
275 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
276 self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
277 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 +0000278 self.checkequal(' a\n b', ' \ta\n\tb', 'expandtabs', 1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000279
280 self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
Neal Norwitz5c9a81a2007-06-11 02:16:10 +0000281 # This test is only valid when sizeof(int) == sizeof(void*) == 4.
282 if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
283 self.checkraises(OverflowError,
284 '\ta\n\tb', 'expandtabs', sys.maxint)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000285
286 def test_split(self):
287 self.checkequal(['this', 'is', 'the', 'split', 'function'],
288 'this is the split function', 'split')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000289
290 # by whitespace
291 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000292 self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
293 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
294 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
295 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000296 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
297 sys.maxint-1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000298 self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000299 self.checkequal(['a b c d'], ' a b c d', 'split', None, 0)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000300 self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000301
Andrew Dalke984b9712006-05-26 11:11:38 +0000302 self.checkequal([], ' ', 'split')
303 self.checkequal(['a'], ' a ', 'split')
304 self.checkequal(['a', 'b'], ' a b ', 'split')
305 self.checkequal(['a', 'b '], ' a b ', 'split', None, 1)
306 self.checkequal(['a', 'b c '], ' a b c ', 'split', None, 1)
307 self.checkequal(['a', 'b', 'c '], ' a b c ', 'split', None, 2)
Andrew Dalke03fb4442006-05-26 11:15:22 +0000308 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
Andrew Dalke005aee22006-05-26 12:28:15 +0000309 aaa = ' a '*20
310 self.checkequal(['a']*20, aaa, 'split')
311 self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
Andrew Dalke669fa182006-05-26 13:05:55 +0000312 self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
Andrew Dalke984b9712006-05-26 11:11:38 +0000313
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000314 # by a char
315 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000316 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000317 self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
318 self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
319 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
320 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000321 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
322 sys.maxint-2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000323 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
324 self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
325 self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
Andrew Dalke005aee22006-05-26 12:28:15 +0000326 self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
327 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000328 self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
329
Andrew Dalke005aee22006-05-26 12:28:15 +0000330 self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
331 self.checkequal(['a']*15 +['a|a|a|a|a'],
332 ('a|'*20)[:-1], 'split', '|', 15)
333
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000334 # by string
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000335 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000336 self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
337 self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
338 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
339 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
Andrew Dalke005aee22006-05-26 12:28:15 +0000340 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
341 sys.maxint-10)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000342 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
343 self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000344 self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000345 self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
346 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
347 'split', 'test')
348 self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000349 self.checkequal(['', ''], 'aaa', 'split', 'aaa')
350 self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
351 self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
352 self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
353 self.checkequal([''], '', 'split', 'aaa')
354 self.checkequal(['aa'], 'aa', 'split', 'aaa')
Andrew Dalke5cc60092006-05-26 12:31:00 +0000355 self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
356 self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
Andrew Dalke005aee22006-05-26 12:28:15 +0000357
358 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
359 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
360 self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
361 'split', 'BLAH', 18)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000362
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000363 # mixed use of str and unicode
364 self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
365
366 # argument type
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000367 self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
368
Andrew Dalke005aee22006-05-26 12:28:15 +0000369 # null case
370 self.checkraises(ValueError, 'hello', 'split', '')
371 self.checkraises(ValueError, 'hello', 'split', '', 0)
372
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000373 def test_rsplit(self):
374 self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
375 'this is the rsplit function', 'rsplit')
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000376
377 # by whitespace
378 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000379 self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
380 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
381 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
382 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000383 self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
384 sys.maxint-20)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000385 self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
Andrew Dalke725fe402006-05-26 16:22:52 +0000386 self.checkequal(['a b c d'], 'a b c d ', 'rsplit', None, 0)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000387 self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000388
Andrew Dalke669fa182006-05-26 13:05:55 +0000389 self.checkequal([], ' ', 'rsplit')
390 self.checkequal(['a'], ' a ', 'rsplit')
391 self.checkequal(['a', 'b'], ' a b ', 'rsplit')
392 self.checkequal([' a', 'b'], ' a b ', 'rsplit', None, 1)
393 self.checkequal([' a b','c'], ' a b c ', 'rsplit',
394 None, 1)
395 self.checkequal([' a', 'b', 'c'], ' a b c ', 'rsplit',
396 None, 2)
397 self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
398 aaa = ' a '*20
399 self.checkequal(['a']*20, aaa, 'rsplit')
400 self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
401 self.checkequal([' a a'] + ['a']*18, aaa, 'rsplit', None, 18)
402
403
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000404 # by a char
405 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
406 self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
407 self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
408 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
409 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000410 self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
411 sys.maxint-100)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000412 self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
413 self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
414 self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
Andrew Dalke669fa182006-05-26 13:05:55 +0000415 self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
416 self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
417
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000418 self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
419
Andrew Dalke669fa182006-05-26 13:05:55 +0000420 self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
421 self.checkequal(['a|a|a|a|a']+['a']*15,
422 ('a|'*20)[:-1], 'rsplit', '|', 15)
423
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000424 # by string
425 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
426 self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
427 self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
428 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
429 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
Andrew Dalke669fa182006-05-26 13:05:55 +0000430 self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
431 sys.maxint-5)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000432 self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
433 self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
434 self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
Andrew Dalke669fa182006-05-26 13:05:55 +0000435 self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
436 self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
437 'rsplit', 'test')
438 self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
439 self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
440 self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
441 self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
442 self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
443 self.checkequal([''], '', 'rsplit', 'aaa')
444 self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
445 self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
446 self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
447
448 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
449 self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
450 self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
451 'rsplit', 'BLAH', 18)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000452
453 # mixed use of str and unicode
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000454 self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +0000455
456 # argument type
457 self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +0000458
Andrew Dalke669fa182006-05-26 13:05:55 +0000459 # null case
460 self.checkraises(ValueError, 'hello', 'rsplit', '')
461 self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
462
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000463 def test_strip(self):
464 self.checkequal('hello', ' hello ', 'strip')
465 self.checkequal('hello ', ' hello ', 'lstrip')
466 self.checkequal(' hello', ' hello ', 'rstrip')
467 self.checkequal('hello', 'hello', 'strip')
468
Neal Norwitzffe33b72003-04-10 22:35:32 +0000469 # strip/lstrip/rstrip with None arg
470 self.checkequal('hello', ' hello ', 'strip', None)
471 self.checkequal('hello ', ' hello ', 'lstrip', None)
472 self.checkequal(' hello', ' hello ', 'rstrip', None)
473 self.checkequal('hello', 'hello', 'strip', None)
474
475 # strip/lstrip/rstrip with str arg
476 self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
477 self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
478 self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
479 self.checkequal('hello', 'hello', 'strip', 'xyz')
480
481 # strip/lstrip/rstrip with unicode arg
482 if test_support.have_unicode:
483 self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
484 'strip', unicode('xyz', 'ascii'))
485 self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
486 'lstrip', unicode('xyz', 'ascii'))
487 self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
488 'rstrip', unicode('xyz', 'ascii'))
Christian Heimes1a6387e2008-03-26 12:49:49 +0000489 # XXX
490 #self.checkequal(unicode('hello', 'ascii'), 'hello',
491 # 'strip', unicode('xyz', 'ascii'))
Neal Norwitzffe33b72003-04-10 22:35:32 +0000492
493 self.checkraises(TypeError, 'hello', 'strip', 42, 42)
494 self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
495 self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
496
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000497 def test_ljust(self):
498 self.checkequal('abc ', 'abc', 'ljust', 10)
499 self.checkequal('abc ', 'abc', 'ljust', 6)
500 self.checkequal('abc', 'abc', 'ljust', 3)
501 self.checkequal('abc', 'abc', 'ljust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000502 self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000503 self.checkraises(TypeError, 'abc', 'ljust')
504
505 def test_rjust(self):
506 self.checkequal(' abc', 'abc', 'rjust', 10)
507 self.checkequal(' abc', 'abc', 'rjust', 6)
508 self.checkequal('abc', 'abc', 'rjust', 3)
509 self.checkequal('abc', 'abc', 'rjust', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000510 self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000511 self.checkraises(TypeError, 'abc', 'rjust')
512
513 def test_center(self):
514 self.checkequal(' abc ', 'abc', 'center', 10)
515 self.checkequal(' abc ', 'abc', 'center', 6)
516 self.checkequal('abc', 'abc', 'center', 3)
517 self.checkequal('abc', 'abc', 'center', 2)
Raymond Hettinger4f8f9762003-11-26 08:21:35 +0000518 self.checkequal('***abc****', 'abc', 'center', 10, '*')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000519 self.checkraises(TypeError, 'abc', 'center')
520
521 def test_swapcase(self):
522 self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
523
524 self.checkraises(TypeError, 'hello', 'swapcase', 42)
525
526 def test_replace(self):
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000527 EQ = self.checkequal
528
529 # Operations on the empty string
530 EQ("", "", "replace", "", "")
Tim Peters80a18f02006-06-01 13:56:26 +0000531 EQ("A", "", "replace", "", "A")
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000532 EQ("", "", "replace", "A", "")
533 EQ("", "", "replace", "A", "A")
534 EQ("", "", "replace", "", "", 100)
535 EQ("", "", "replace", "", "", sys.maxint)
536
537 # interleave (from=="", 'to' gets inserted everywhere)
538 EQ("A", "A", "replace", "", "")
539 EQ("*A*", "A", "replace", "", "*")
540 EQ("*1A*1", "A", "replace", "", "*1")
541 EQ("*-#A*-#", "A", "replace", "", "*-#")
542 EQ("*-A*-A*-", "AA", "replace", "", "*-")
543 EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
544 EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
545 EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
546 EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
547 EQ("*-A*-A", "AA", "replace", "", "*-", 2)
548 EQ("*-AA", "AA", "replace", "", "*-", 1)
549 EQ("AA", "AA", "replace", "", "*-", 0)
550
551 # single character deletion (from=="A", to=="")
552 EQ("", "A", "replace", "A", "")
553 EQ("", "AAA", "replace", "A", "")
554 EQ("", "AAA", "replace", "A", "", -1)
555 EQ("", "AAA", "replace", "A", "", sys.maxint)
556 EQ("", "AAA", "replace", "A", "", 4)
557 EQ("", "AAA", "replace", "A", "", 3)
558 EQ("A", "AAA", "replace", "A", "", 2)
559 EQ("AA", "AAA", "replace", "A", "", 1)
560 EQ("AAA", "AAA", "replace", "A", "", 0)
561 EQ("", "AAAAAAAAAA", "replace", "A", "")
562 EQ("BCD", "ABACADA", "replace", "A", "")
563 EQ("BCD", "ABACADA", "replace", "A", "", -1)
564 EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
565 EQ("BCD", "ABACADA", "replace", "A", "", 5)
566 EQ("BCD", "ABACADA", "replace", "A", "", 4)
567 EQ("BCDA", "ABACADA", "replace", "A", "", 3)
568 EQ("BCADA", "ABACADA", "replace", "A", "", 2)
569 EQ("BACADA", "ABACADA", "replace", "A", "", 1)
570 EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
571 EQ("BCD", "ABCAD", "replace", "A", "")
572 EQ("BCD", "ABCADAA", "replace", "A", "")
573 EQ("BCD", "BCD", "replace", "A", "")
574 EQ("*************", "*************", "replace", "A", "")
575 EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
576
577 # substring deletion (from=="the", to=="")
578 EQ("", "the", "replace", "the", "")
579 EQ("ater", "theater", "replace", "the", "")
580 EQ("", "thethe", "replace", "the", "")
581 EQ("", "thethethethe", "replace", "the", "")
582 EQ("aaaa", "theatheatheathea", "replace", "the", "")
583 EQ("that", "that", "replace", "the", "")
584 EQ("thaet", "thaet", "replace", "the", "")
585 EQ("here and re", "here and there", "replace", "the", "")
586 EQ("here and re and re", "here and there and there",
587 "replace", "the", "", sys.maxint)
588 EQ("here and re and re", "here and there and there",
589 "replace", "the", "", -1)
590 EQ("here and re and re", "here and there and there",
591 "replace", "the", "", 3)
592 EQ("here and re and re", "here and there and there",
593 "replace", "the", "", 2)
594 EQ("here and re and there", "here and there and there",
595 "replace", "the", "", 1)
596 EQ("here and there and there", "here and there and there",
597 "replace", "the", "", 0)
598 EQ("here and re and re", "here and there and there", "replace", "the", "")
599
600 EQ("abc", "abc", "replace", "the", "")
601 EQ("abcdefg", "abcdefg", "replace", "the", "")
602
603 # substring deletion (from=="bob", to=="")
604 EQ("bob", "bbobob", "replace", "bob", "")
605 EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
606 EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
607 EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000608
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000609 # single character replace in place (len(from)==len(to)==1)
610 EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
611 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
612 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
613 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
614 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
615 EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
616 EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
617 EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
618
619 EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
620 EQ("who goes there?", "Who goes there?", "replace", "W", "w")
621 EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
622 EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
623 EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
624
625 EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000626
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000627 # substring replace in place (len(from)==len(to) > 1)
628 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
629 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
630 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
631 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
632 EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
633 EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
634 EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
635 EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
636 EQ("cobob", "bobob", "replace", "bob", "cob")
637 EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
638 EQ("bobob", "bobob", "replace", "bot", "bot")
639
640 # replace single character (len(from)==1, len(to)>1)
641 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
642 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
643 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
644 EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
645 EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
646 EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
647 EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
648
649 EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
650
651 # replace substring (len(from)>1, len(to)!=len(from))
652 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
653 "replace", "spam", "ham")
654 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
655 "replace", "spam", "ham", sys.maxint)
656 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
657 "replace", "spam", "ham", -1)
658 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
659 "replace", "spam", "ham", 4)
660 EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
661 "replace", "spam", "ham", 3)
662 EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
663 "replace", "spam", "ham", 2)
664 EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
665 "replace", "spam", "ham", 1)
666 EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
667 "replace", "spam", "ham", 0)
668
669 EQ("bobob", "bobobob", "replace", "bobob", "bob")
670 EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
671 EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
Tim Petersbeaec0c2006-05-24 20:27:18 +0000672
Neal Norwitzf71ec5a2006-07-30 06:57:04 +0000673 ba = buffer('a')
674 bb = buffer('b')
675 EQ("bbc", "abc", "replace", ba, bb)
676 EQ("aac", "abc", "replace", bb, ba)
677
Tim Petersbeaec0c2006-05-24 20:27:18 +0000678 #
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000679 self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
680 self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
681 self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2)
682 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3)
683 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4)
684 self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
685 self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@')
686 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
687 self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
688 self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
689 self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
690 self.checkequal('abc', 'abc', 'replace', '', '-', 0)
691 self.checkequal('', '', 'replace', '', '')
692 self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
693 self.checkequal('abc', 'abc', 'replace', 'xy', '--')
694 # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
695 # MemoryError due to empty result (platform malloc issue when requesting
696 # 0 bytes).
697 self.checkequal('', '123', 'replace', '123', '')
698 self.checkequal('', '123123', 'replace', '123', '')
699 self.checkequal('x', '123x123', 'replace', '123', '')
700
701 self.checkraises(TypeError, 'hello', 'replace')
702 self.checkraises(TypeError, 'hello', 'replace', 42)
703 self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
704 self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
705
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000706 def test_replace_overflow(self):
707 # Check for overflow checking on 32 bit machines
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000708 if sys.maxint != 2147483647 or struct.calcsize("P") > 4:
Fredrik Lundh0c71f882006-05-25 16:46:54 +0000709 return
710 A2_16 = "A" * (2**16)
711 self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
712 self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
713 self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
Andrew Dalkee5488ec2006-05-24 18:55:37 +0000714
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000715 def test_zfill(self):
716 self.checkequal('123', '123', 'zfill', 2)
717 self.checkequal('123', '123', 'zfill', 3)
718 self.checkequal('0123', '123', 'zfill', 4)
719 self.checkequal('+123', '+123', 'zfill', 3)
720 self.checkequal('+123', '+123', 'zfill', 4)
721 self.checkequal('+0123', '+123', 'zfill', 5)
722 self.checkequal('-123', '-123', 'zfill', 3)
723 self.checkequal('-123', '-123', 'zfill', 4)
724 self.checkequal('-0123', '-123', 'zfill', 5)
725 self.checkequal('000', '', 'zfill', 3)
726 self.checkequal('34', '34', 'zfill', 1)
727 self.checkequal('0034', '34', 'zfill', 4)
728
729 self.checkraises(TypeError, '123', 'zfill')
730
Christian Heimes1a6387e2008-03-26 12:49:49 +0000731# XXX alias for py3k forward compatibility
732BaseTest = CommonTest
733
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000734class MixinStrUnicodeUserStringTest:
735 # additional tests that only work for
736 # stringlike objects, i.e. str, unicode, UserString
737 # (but not the string module)
738
739 def test_islower(self):
740 self.checkequal(False, '', 'islower')
741 self.checkequal(True, 'a', 'islower')
742 self.checkequal(False, 'A', 'islower')
743 self.checkequal(False, '\n', 'islower')
744 self.checkequal(True, 'abc', 'islower')
745 self.checkequal(False, 'aBc', 'islower')
746 self.checkequal(True, 'abc\n', 'islower')
747 self.checkraises(TypeError, 'abc', 'islower', 42)
748
749 def test_isupper(self):
750 self.checkequal(False, '', 'isupper')
751 self.checkequal(False, 'a', 'isupper')
752 self.checkequal(True, 'A', 'isupper')
753 self.checkequal(False, '\n', 'isupper')
754 self.checkequal(True, 'ABC', 'isupper')
755 self.checkequal(False, 'AbC', 'isupper')
756 self.checkequal(True, 'ABC\n', 'isupper')
757 self.checkraises(TypeError, 'abc', 'isupper', 42)
758
759 def test_istitle(self):
760 self.checkequal(False, '', 'istitle')
761 self.checkequal(False, 'a', 'istitle')
762 self.checkequal(True, 'A', 'istitle')
763 self.checkequal(False, '\n', 'istitle')
764 self.checkequal(True, 'A Titlecased Line', 'istitle')
765 self.checkequal(True, 'A\nTitlecased Line', 'istitle')
766 self.checkequal(True, 'A Titlecased, Line', 'istitle')
767 self.checkequal(False, 'Not a capitalized String', 'istitle')
768 self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
769 self.checkequal(False, 'Not--a Titlecase String', 'istitle')
770 self.checkequal(False, 'NOT', 'istitle')
771 self.checkraises(TypeError, 'abc', 'istitle', 42)
772
773 def test_isspace(self):
774 self.checkequal(False, '', 'isspace')
775 self.checkequal(False, 'a', 'isspace')
776 self.checkequal(True, ' ', 'isspace')
777 self.checkequal(True, '\t', 'isspace')
778 self.checkequal(True, '\r', 'isspace')
779 self.checkequal(True, '\n', 'isspace')
780 self.checkequal(True, ' \t\r\n', 'isspace')
781 self.checkequal(False, ' \t\r\na', 'isspace')
782 self.checkraises(TypeError, 'abc', 'isspace', 42)
783
784 def test_isalpha(self):
785 self.checkequal(False, '', 'isalpha')
786 self.checkequal(True, 'a', 'isalpha')
787 self.checkequal(True, 'A', 'isalpha')
788 self.checkequal(False, '\n', 'isalpha')
789 self.checkequal(True, 'abc', 'isalpha')
790 self.checkequal(False, 'aBc123', 'isalpha')
791 self.checkequal(False, 'abc\n', 'isalpha')
792 self.checkraises(TypeError, 'abc', 'isalpha', 42)
793
794 def test_isalnum(self):
795 self.checkequal(False, '', 'isalnum')
796 self.checkequal(True, 'a', 'isalnum')
797 self.checkequal(True, 'A', 'isalnum')
798 self.checkequal(False, '\n', 'isalnum')
799 self.checkequal(True, '123abc456', 'isalnum')
800 self.checkequal(True, 'a1b3c', 'isalnum')
801 self.checkequal(False, 'aBc000 ', 'isalnum')
802 self.checkequal(False, 'abc\n', 'isalnum')
803 self.checkraises(TypeError, 'abc', 'isalnum', 42)
804
805 def test_isdigit(self):
806 self.checkequal(False, '', 'isdigit')
807 self.checkequal(False, 'a', 'isdigit')
808 self.checkequal(True, '0', 'isdigit')
809 self.checkequal(True, '0123456789', 'isdigit')
810 self.checkequal(False, '0123456789a', 'isdigit')
811
812 self.checkraises(TypeError, 'abc', 'isdigit', 42)
813
814 def test_title(self):
815 self.checkequal(' Hello ', ' hello ', 'title')
816 self.checkequal('Hello ', 'hello ', 'title')
817 self.checkequal('Hello ', 'Hello ', 'title')
818 self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
819 self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
820 self.checkequal('Getint', "getInt", 'title')
821 self.checkraises(TypeError, 'hello', 'title', 42)
822
823 def test_splitlines(self):
824 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
825 self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
826 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
827 self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
828 self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
829 self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
830 self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
831
832 self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
833
834 def test_startswith(self):
835 self.checkequal(True, 'hello', 'startswith', 'he')
836 self.checkequal(True, 'hello', 'startswith', 'hello')
837 self.checkequal(False, 'hello', 'startswith', 'hello world')
838 self.checkequal(True, 'hello', 'startswith', '')
839 self.checkequal(False, 'hello', 'startswith', 'ello')
840 self.checkequal(True, 'hello', 'startswith', 'ello', 1)
841 self.checkequal(True, 'hello', 'startswith', 'o', 4)
842 self.checkequal(False, 'hello', 'startswith', 'o', 5)
843 self.checkequal(True, 'hello', 'startswith', '', 5)
844 self.checkequal(False, 'hello', 'startswith', 'lo', 6)
845 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
846 self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
847 self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
848
849 # test negative indices
850 self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
851 self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
852 self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
853 self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
854 self.checkequal(False, 'hello', 'startswith', 'ello', -5)
855 self.checkequal(True, 'hello', 'startswith', 'ello', -4)
856 self.checkequal(False, 'hello', 'startswith', 'o', -2)
857 self.checkequal(True, 'hello', 'startswith', 'o', -1)
858 self.checkequal(True, 'hello', 'startswith', '', -3, -3)
859 self.checkequal(False, 'hello', 'startswith', 'lo', -9)
860
861 self.checkraises(TypeError, 'hello', 'startswith')
862 self.checkraises(TypeError, 'hello', 'startswith', 42)
863
Georg Brandl24250812006-06-09 18:45:48 +0000864 # test tuple arguments
865 self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
866 self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
867 self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
868 self.checkequal(False, 'hello', 'startswith', ())
869 self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
870 'rld', 'lowo'), 3)
871 self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
872 'rld'), 3)
873 self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
874 self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
875 self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
876
877 self.checkraises(TypeError, 'hello', 'startswith', (42,))
878
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000879 def test_endswith(self):
880 self.checkequal(True, 'hello', 'endswith', 'lo')
881 self.checkequal(False, 'hello', 'endswith', 'he')
882 self.checkequal(True, 'hello', 'endswith', '')
883 self.checkequal(False, 'hello', 'endswith', 'hello world')
884 self.checkequal(False, 'helloworld', 'endswith', 'worl')
885 self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
886 self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
887 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
888 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
889 self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
890 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
891 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
892 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
893 self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
894
895 # test negative indices
896 self.checkequal(True, 'hello', 'endswith', 'lo', -2)
897 self.checkequal(False, 'hello', 'endswith', 'he', -2)
898 self.checkequal(True, 'hello', 'endswith', '', -3, -3)
899 self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
900 self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
901 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
902 self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
903 self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
904 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
905 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
906 self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
907 self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
908 self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
909
910 self.checkraises(TypeError, 'hello', 'endswith')
911 self.checkraises(TypeError, 'hello', 'endswith', 42)
912
Georg Brandl24250812006-06-09 18:45:48 +0000913 # test tuple arguments
914 self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
915 self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
916 self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
917 self.checkequal(False, 'hello', 'endswith', ())
918 self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
919 'rld', 'lowo'), 3)
920 self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
921 'rld'), 3, -1)
922 self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
923 self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
924 self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
925
926 self.checkraises(TypeError, 'hello', 'endswith', (42,))
927
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000928 def test___contains__(self):
929 self.checkequal(True, '', '__contains__', '') # vereq('' in '', True)
930 self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True)
931 self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False)
932 self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True)
933 self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True)
934 self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True)
935 self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True)
936 self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False)
937 self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False)
938
939 def test_subscript(self):
940 self.checkequal(u'a', 'abc', '__getitem__', 0)
941 self.checkequal(u'c', 'abc', '__getitem__', -1)
942 self.checkequal(u'a', 'abc', '__getitem__', 0L)
943 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
944 self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
945 self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
946 self.checkequal(u'', 'abc', '__getitem__', slice(0, 0))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000947
948 self.checkraises(TypeError, 'abc', '__getitem__', 'def')
949
950 def test_slice(self):
951 self.checkequal('abc', 'abc', '__getslice__', 0, 1000)
952 self.checkequal('abc', 'abc', '__getslice__', 0, 3)
953 self.checkequal('ab', 'abc', '__getslice__', 0, 2)
954 self.checkequal('bc', 'abc', '__getslice__', 1, 3)
955 self.checkequal('b', 'abc', '__getslice__', 1, 2)
956 self.checkequal('', 'abc', '__getslice__', 2, 2)
957 self.checkequal('', 'abc', '__getslice__', 1000, 1000)
958 self.checkequal('', 'abc', '__getslice__', 2000, 1000)
959 self.checkequal('', 'abc', '__getslice__', 2, 1)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000960
961 self.checkraises(TypeError, 'abc', '__getslice__', 'def')
962
Thomas Wouters3ccec682007-08-28 15:28:19 +0000963 def test_extended_getslice(self):
964 # Test extended slicing by comparing with list slicing.
965 s = string.ascii_letters + string.digits
966 indices = (0, None, 1, 3, 41, -1, -2, -37)
967 for start in indices:
968 for stop in indices:
969 # Skip step 0 (invalid)
970 for step in indices[1:]:
971 L = list(s)[start:stop:step]
972 self.checkequal(u"".join(L), s, '__getitem__',
973 slice(start, stop, step))
974
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000975 def test_mul(self):
976 self.checkequal('', 'abc', '__mul__', -1)
977 self.checkequal('', 'abc', '__mul__', 0)
978 self.checkequal('abc', 'abc', '__mul__', 1)
979 self.checkequal('abcabcabc', 'abc', '__mul__', 3)
980 self.checkraises(TypeError, 'abc', '__mul__')
981 self.checkraises(TypeError, 'abc', '__mul__', '')
Martin v. Löwis18e16552006-02-15 17:27:45 +0000982 # XXX: on a 64-bit system, this doesn't raise an overflow error,
983 # but either raises a MemoryError, or succeeds (if you have 54TiB)
984 #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000985
986 def test_join(self):
987 # join now works with any sequence type
988 # moved here, because the argument order is
989 # different in string.join (see the test in
990 # test.test_string.StringTest.test_join)
991 self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
992 self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
Georg Brandl90e27d32006-06-10 06:40:50 +0000993 self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
994 self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000995 self.checkequal('w x y z', ' ', 'join', Sequence())
996 self.checkequal('abc', 'a', 'join', ('abc',))
997 self.checkequal('z', 'a', 'join', UserList(['z']))
998 if test_support.have_unicode:
999 self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
1000 self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
1001 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
1002 self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
1003 self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
1004 for i in [5, 25, 125]:
1005 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1006 ['a' * i] * i)
1007 self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
1008 ('a' * i,) * i)
1009
1010 self.checkraises(TypeError, ' ', 'join', BadSeq1())
1011 self.checkequal('a b c', ' ', 'join', BadSeq2())
1012
1013 self.checkraises(TypeError, ' ', 'join')
1014 self.checkraises(TypeError, ' ', 'join', 7)
1015 self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
Michael W. Hudsonb2308bb2005-10-21 11:45:01 +00001016 try:
1017 def f():
1018 yield 4 + ""
1019 self.fixtype(' ').join(f())
1020 except TypeError, e:
1021 if '+' not in str(e):
1022 self.fail('join() ate exception message')
1023 else:
1024 self.fail('exception not raised')
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001025
1026 def test_formatting(self):
1027 self.checkequal('+hello+', '+%s+', '__mod__', 'hello')
1028 self.checkequal('+10+', '+%d+', '__mod__', 10)
1029 self.checkequal('a', "%c", '__mod__', "a")
1030 self.checkequal('a', "%c", '__mod__', "a")
1031 self.checkequal('"', "%c", '__mod__', 34)
1032 self.checkequal('$', "%c", '__mod__', 36)
1033 self.checkequal('10', "%d", '__mod__', 10)
Walter Dörwald43440a62003-03-31 18:07:50 +00001034 self.checkequal('\x7f', "%c", '__mod__', 0x7f)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001035
1036 for ordinal in (-100, 0x200000):
1037 # unicode raises ValueError, str raises OverflowError
1038 self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal)
1039
Facundo Batistac11cecf2008-02-24 03:17:21 +00001040 longvalue = sys.maxint + 10L
1041 slongvalue = str(longvalue)
1042 if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001043 self.checkequal(' 42', '%3ld', '__mod__', 42)
Facundo Batistac11cecf2008-02-24 03:17:21 +00001044 self.checkequal('42', '%d', '__mod__', 42L)
1045 self.checkequal('42', '%d', '__mod__', 42.0)
1046 self.checkequal(slongvalue, '%d', '__mod__', longvalue)
1047 self.checkcall('%d', '__mod__', float(longvalue))
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001048 self.checkequal('0042.00', '%07.2f', '__mod__', 42)
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00001049 self.checkequal('0042.00', '%07.2F', '__mod__', 42)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001050
1051 self.checkraises(TypeError, 'abc', '__mod__')
1052 self.checkraises(TypeError, '%(foo)s', '__mod__', 42)
1053 self.checkraises(TypeError, '%s%s', '__mod__', (42,))
1054 self.checkraises(TypeError, '%c', '__mod__', (None,))
1055 self.checkraises(ValueError, '%(foo', '__mod__', {})
1056 self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
Facundo Batistac11cecf2008-02-24 03:17:21 +00001057 self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
1058 self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001059
1060 # argument names with properly nested brackets are supported
1061 self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})
1062
1063 # 100 is a magic number in PyUnicode_Format, this forces a resize
1064 self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a')
1065
1066 self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar'))
1067 self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.))
1068 self.checkraises(ValueError, '%10', '__mod__', (42,))
1069
1070 def test_floatformatting(self):
1071 # float formatting
1072 for prec in xrange(100):
1073 format = '%%.%if' % prec
1074 value = 0.01
1075 for x in xrange(60):
1076 value = value * 3.141592655 / 3.0 * 10.0
1077 # The formatfloat() code in stringobject.c and
1078 # unicodeobject.c uses a 120 byte buffer and switches from
1079 # 'f' formatting to 'g' at precision 50, so we expect
1080 # OverflowErrors for the ranges x < 50 and prec >= 67.
1081 if x < 50 and prec >= 67:
1082 self.checkraises(OverflowError, format, "__mod__", value)
1083 else:
1084 self.checkcall(format, "__mod__", value)
1085
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001086 def test_inplace_rewrites(self):
1087 # Check that strings don't copy and modify cached single-character strings
1088 self.checkequal('a', 'A', 'lower')
1089 self.checkequal(True, 'A', 'isupper')
1090 self.checkequal('A', 'a', 'upper')
1091 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001092
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001093 self.checkequal('a', 'A', 'replace', 'A', 'a')
1094 self.checkequal(True, 'A', 'isupper')
1095
1096 self.checkequal('A', 'a', 'capitalize')
1097 self.checkequal(True, 'a', 'islower')
Tim Petersd95d5932006-05-25 21:52:19 +00001098
Andrew Dalke2bddcbf2006-05-25 16:30:52 +00001099 self.checkequal('A', 'a', 'swapcase')
1100 self.checkequal(True, 'a', 'islower')
1101
1102 self.checkequal('A', 'a', 'title')
1103 self.checkequal(True, 'a', 'islower')
1104
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001105 def test_partition(self):
1106
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001107 self.checkequal(('this is the par', 'ti', 'tion method'),
1108 'this is the partition method', 'partition', 'ti')
Fredrik Lundh06a69dd2006-05-26 08:54:28 +00001109
1110 # from raymond's original specification
1111 S = 'http://www.python.org'
1112 self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
1113 self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
1114 self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
1115 self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
1116
1117 self.checkraises(ValueError, S, 'partition', '')
1118 self.checkraises(TypeError, S, 'partition', None)
1119
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001120 def test_rpartition(self):
1121
1122 self.checkequal(('this is the rparti', 'ti', 'on method'),
1123 'this is the rpartition method', 'rpartition', 'ti')
1124
1125 # from raymond's original specification
1126 S = 'http://www.python.org'
1127 self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
Raymond Hettingera0c95fa2006-09-04 15:32:48 +00001128 self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
Fredrik Lundh9c0e9c02006-05-26 18:24:15 +00001129 self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
1130 self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
1131
1132 self.checkraises(ValueError, S, 'rpartition', '')
1133 self.checkraises(TypeError, S, 'rpartition', None)
1134
Walter Dörwald57d88e52004-08-26 16:53:04 +00001135
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001136class MixinStrStringUserStringTest:
1137 # Additional tests for 8bit strings, i.e. str, UserString and
1138 # the string module
1139
1140 def test_maketrans(self):
1141 self.assertEqual(
1142 ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
1143 string.maketrans('abc', 'xyz')
1144 )
1145 self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
1146
1147 def test_translate(self):
1148 table = string.maketrans('abc', 'xyz')
1149 self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
1150
1151 table = string.maketrans('a', 'A')
1152 self.checkequal('Abc', 'abc', 'translate', table)
1153 self.checkequal('xyz', 'xyz', 'translate', table)
1154 self.checkequal('yz', 'xyz', 'translate', table, 'x')
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001155 self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
Raymond Hettinger4db5fe92007-04-12 04:10:00 +00001156 self.checkequal('zyzzx', 'zyzzx', 'translate', None, '')
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001157 self.checkequal('zyzzx', 'zyzzx', 'translate', None)
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001158 self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
1159 self.checkraises(ValueError, 'xyz', 'translate', 'too short')
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001160
1161
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001162class MixinStrUserStringTest:
1163 # Additional tests that only work with
1164 # 8bit compatible object, i.e. str and UserString
Jeremy Hyltonf82b04e2000-07-10 17:08:42 +00001165
Walter Dörwald6eea7892005-07-28 16:49:15 +00001166 if test_support.have_unicode:
1167 def test_encoding_decoding(self):
1168 codecs = [('rot13', 'uryyb jbeyq'),
1169 ('base64', 'aGVsbG8gd29ybGQ=\n'),
1170 ('hex', '68656c6c6f20776f726c64'),
1171 ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
1172 for encoding, data in codecs:
1173 self.checkequal(data, 'hello world', 'encode', encoding)
1174 self.checkequal('hello world', data, 'decode', encoding)
1175 # zlib is optional, so we make the test optional too...
1176 try:
1177 import zlib
1178 except ImportError:
1179 pass
1180 else:
1181 data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
1182 self.checkequal(data, 'hello world', 'encode', 'zlib')
1183 self.checkequal('hello world', data, 'decode', 'zlib')
Walter Dörwald97951de2003-03-26 14:31:25 +00001184
Walter Dörwald6eea7892005-07-28 16:49:15 +00001185 self.checkraises(TypeError, 'xyz', 'decode', 42)
1186 self.checkraises(TypeError, 'xyz', 'encode', 42)
Walter Dörwald57d88e52004-08-26 16:53:04 +00001187
1188
1189class MixinStrUnicodeTest:
Tim Peters108f1372004-08-27 05:36:07 +00001190 # Additional tests that only work with str and unicode.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001191
1192 def test_bug1001011(self):
1193 # Make sure join returns a NEW object for single item sequences
Tim Peters108f1372004-08-27 05:36:07 +00001194 # involving a subclass.
1195 # Make sure that it is of the appropriate type.
1196 # Check the optimisation still occurs for standard objects.
Walter Dörwald57d88e52004-08-26 16:53:04 +00001197 t = self.type2test
1198 class subclass(t):
1199 pass
1200 s1 = subclass("abcd")
1201 s2 = t().join([s1])
1202 self.assert_(s1 is not s2)
1203 self.assert_(type(s2) is t)
Tim Peters108f1372004-08-27 05:36:07 +00001204
1205 s1 = t("abcd")
1206 s2 = t().join([s1])
1207 self.assert_(s1 is s2)
1208
1209 # Should also test mixed-type join.
1210 if t is unicode:
1211 s1 = subclass("abcd")
1212 s2 = "".join([s1])
1213 self.assert_(s1 is not s2)
1214 self.assert_(type(s2) is t)
1215
1216 s1 = t("abcd")
1217 s2 = "".join([s1])
1218 self.assert_(s1 is s2)
1219
1220 elif t is str:
1221 s1 = subclass("abcd")
1222 s2 = u"".join([s1])
1223 self.assert_(s1 is not s2)
1224 self.assert_(type(s2) is unicode) # promotes!
1225
1226 s1 = t("abcd")
1227 s2 = u"".join([s1])
1228 self.assert_(s1 is not s2)
1229 self.assert_(type(s2) is unicode) # promotes!
1230
1231 else:
1232 self.fail("unexpected type for MixinStrUnicodeTest %r" % t)