Debian Codegraph @

pypy/objspace/std/test/apptest_unicode.py

raw symbols SCIP
1 import pytest
2
3 def test_addition():
4 import operator
5 assert 'a' + 'b' == 'ab'
6 raises(TypeError, operator.add, b'a', 'b')
7
8 def test_getitem():
9 assert u'abc'[2] == 'c'
10 raises(IndexError, u'abc'.__getitem__, 15)
11 assert u'g\u0105\u015b\u0107'[2] == u'\u015b'
12
13 def test_join():
14 def check(a, b):
15 assert a == b
16 assert type(a) == type(b)
17 check(', '.join(['a']), 'a')
18 check(', '.join(['a', 'b']), 'a, b')
19 raises(TypeError, ','.join, [b'a'])
20 check(','.join(iter([])), '')
21 with raises(TypeError) as exc:
22 ''.join(['a', 2, 3])
23 assert 'sequence item 1' in str(exc.value)
24 with raises(TypeError) as exc:
25 ''.join(iter(['a', 2, 3]))
26 assert 'sequence item 1' in str(exc.value)
27 # unicode lists
28 check(''.join(['\u1234']), '\u1234')
29 check(''.join(['\u1234', '\u2345']), '\u1234\u2345')
30 check('\u1234'.join(['\u2345', '\u3456']), '\u2345\u1234\u3456')
31 check('x\u1234y'.join(['a', 'b', 'c']), 'ax\u1234ybx\u1234yc')
32 # also checking passing a single unicode instead of a list
33 check(''.join('\u1234'), '\u1234')
34 check(''.join('\u1234\u2345'), '\u1234\u2345')
35 check('\u1234'.join('\u2345\u3456'), '\u2345\u1234\u3456')
36
37 def test_contains():
38 assert '' in 'abc'
39 assert 'a' in 'abc'
40 assert 'bc' in 'abc'
41 assert '\xe2' in 'g\xe2teau'
42
43 def test_splitlines():
44 assert ''.splitlines() == []
45 assert ''.splitlines(1) == []
46 assert '\n'.splitlines() == ['']
47 assert 'a'.splitlines() == ['a']
48 assert 'one\ntwo'.splitlines() == ['one', 'two']
49 assert '\ntwo\nthree'.splitlines() == ['', 'two', 'three']
50 assert '\n\n'.splitlines() == ['', '']
51 assert 'a\nb\nc'.splitlines(1) == ['a\n', 'b\n', 'c']
52 assert '\na\nb\n'.splitlines(1) == ['\n', 'a\n', 'b\n']
53 assert ((u'a' + b'\xc2\x85'.decode('utf8') + u'b\n').splitlines() ==
54 ['a', 'b'])
55
56 def test_zfill():
57 assert '123'.zfill(2) == '123'
58 assert '123'.zfill(3) == '123'
59 assert '123'.zfill(4) == '0123'
60 assert '123'.zfill(6) == '000123'
61 assert '+123'.zfill(2) == '+123'
62 assert '+123'.zfill(3) == '+123'
63 assert '+123'.zfill(4) == '+123'
64 assert '+123'.zfill(5) == '+0123'
65 assert '+123'.zfill(6) == '+00123'
66 assert '-123'.zfill(3) == '-123'
67 assert '-123'.zfill(4) == '-123'
68 assert '-123'.zfill(5) == '-0123'
69 assert ''.zfill(3) == '000'
70 assert '34'.zfill(1) == '34'
71 assert '34'.zfill(4) == '0034'
72
73 def test_split():
74 assert "".split() == []
75 assert "".split('x') == ['']
76 assert " ".split() == []
77 assert "a".split() == ['a']
78 assert "a".split("a", 1) == ['', '']
79 assert " ".split(" ", 1) == ['', '']
80 assert "aa".split("a", 2) == ['', '', '']
81 assert " a ".split() == ['a']
82 assert "a b c".split() == ['a','b','c']
83 assert 'this is the split function'.split() == ['this', 'is', 'the', 'split', 'function']
84 assert 'a|b|c|d'.split('|') == ['a', 'b', 'c', 'd']
85 assert 'a|b|c|d'.split('|', 2) == ['a', 'b', 'c|d']
86 assert 'a b c d'.split(None, 1) == ['a', 'b c d']
87 assert 'a b c d'.split(None, 2) == ['a', 'b', 'c d']
88 assert 'a b c d'.split(None, 3) == ['a', 'b', 'c', 'd']
89 assert 'a b c d'.split(None, 4) == ['a', 'b', 'c', 'd']
90 assert 'a b c d'.split(None, 0) == ['a b c d']
91 assert 'a b c d'.split(None, 2) == ['a', 'b', 'c d']
92 assert 'a b c d '.split() == ['a', 'b', 'c', 'd']
93 assert 'a//b//c//d'.split('//') == ['a', 'b', 'c', 'd']
94 assert 'endcase test'.split('test') == ['endcase ', '']
95 raises(ValueError, 'abc'.split, '')
96 raises(ValueError, 'abc'.split, '')
97 raises(ValueError, 'abc'.split, '')
98 assert ' a b c d'.split(None, 0) == ['a b c d']
99 assert u'a\nb\u1680c'.split() == [u'a', u'b', u'c']
100
101 def test_split_nonascii():
102 assert "\u2029".split() == []
103 assert "ä".split() == ['ä']
104 assert "ä".split("ä", 1) == ['', '']
105 assert "\u2029".split("\u2029", 1) == ['', '']
106 assert "ää".split("ä", 2) == ['', '', '']
107 assert "\u2029äöú\u2029".split() == ['äöú']
108 assert "a b c".split() == ['a','b','c']
109 assert 'thús ús the splút fúnction'.split() == ['thús', 'ús', 'the', 'splút', 'fúnction']
110 assert 'äö|ö|ß|ë'.split('|') == ['äö', 'ö', 'ß', 'ë']
111 assert 'äö|ö|ß|ë'.split('|', 2) == ['äö', 'ö', 'ß|ë']
112 assert 'a\u2029b\u2029c\u2029d'.split(None, 1) == ['a', 'b\u2029c\u2029d']
113 assert 'a\u2029b\u2029c\u2029d'.split(None, 2) == ['a', 'b', 'c\u2029d']
114 assert 'a\u2029b\u2029c\u2029d'.split(None, 3) == ['a', 'b', 'c', 'd']
115 assert 'a\u2029b\u2029c\u2029d'.split(None, 4) == ['a', 'b', 'c', 'd']
116 assert 'a\u2029b\u2029c\u2029d'.split(None, 0) == ['a\u2029b\u2029c\u2029d']
117 assert 'a\u2029 b \u2029c \u2029d'.split(None, 2) == ['a', 'b', 'c \u2029d']
118 assert ' ä ú c d'.split(None, 0) == ['ä ú c d']
119 assert u'a\nb\u1680c'.split() == [u'a', u'b', u'c']
120
121 def test_split_nonascii_mongolian_vowel_separator_bug():
122 s = u'\u180eä\u180e'
123 assert s.split() == [s]
124 assert s.rsplit() == [s]
125 assert s.rsplit(maxsplit=1) == [s]
126
127
128 def test_rsplit():
129 assert u"".rsplit() == []
130 assert u" ".rsplit() == []
131 assert u"a".rsplit() == [u'a']
132 assert u"a".rsplit(u"a", 1) == [u'', u'']
133 assert u" ".rsplit(u" ", 1) == [u'', u'']
134 assert u"aa".rsplit(u"a", 2) == [u'', u'', u'']
135 assert u" a ".rsplit() == [u'a']
136 assert u"a b c".rsplit() == [u'a',u'b',u'c']
137 assert u'this is the rsplit function'.rsplit() == [u'this', u'is', u'the', u'rsplit', u'function']
138 assert u'a|b|c|d'.rsplit(u'|') == [u'a', u'b', u'c', u'd']
139 assert u'a|b|c|d'.rsplit('|') == [u'a', u'b', u'c', u'd']
140 assert 'a|b|c|d'.rsplit(u'|') == [u'a', u'b', u'c', u'd']
141 assert u'a|b|c|d'.rsplit(u'|', 2) == [u'a|b', u'c', u'd']
142 assert u'a b c d'.rsplit(None, 1) == [u'a b c', u'd']
143 assert u'a b c d'.rsplit(None, 2) == [u'a b', u'c', u'd']
144 assert u'a b c d'.rsplit(None, 3) == [u'a', u'b', u'c', u'd']
145 assert u'a b c d'.rsplit(None, 4) == [u'a', u'b', u'c', u'd']
146 assert u'a b c d'.rsplit(None, 0) == [u'a b c d']
147 assert u'a b c d'.rsplit(None, 2) == [u'a b', u'c', u'd']
148 assert u'a b c d '.rsplit() == [u'a', u'b', u'c', u'd']
149 assert u'a//b//c//d'.rsplit(u'//') == [u'a', u'b', u'c', u'd']
150 assert u'endcase test'.rsplit(u'test') == [u'endcase ', u'']
151 raises(ValueError, u'abc'.rsplit, u'')
152 raises(ValueError, u'abc'.rsplit, '')
153 raises(ValueError, 'abc'.rsplit, u'')
154 assert u' a b c '.rsplit(None, 0) == [u' a b c']
155 assert u''.rsplit('aaa') == [u'']
156 assert u'a\nb\u1680c'.rsplit() == [u'a', u'b', u'c']
157
158 def test_rsplit_bug():
159 assert u'Vestur- og Mið'.rsplit() == [u'Vestur-', u'og', u'Mið']
160
161 def test_center():
162 s=u"a b"
163 assert s.center(0) == u"a b"
164 assert s.center(1) == u"a b"
165 assert s.center(2) == u"a b"
166 assert s.center(3) == u"a b"
167 assert s.center(4) == u"a b "
168 assert s.center(5) == u" a b "
169 assert s.center(6) == u" a b "
170 assert s.center(7) == u" a b "
171 assert s.center(8) == u" a b "
172 assert s.center(9) == u" a b "
173 assert u'abc'.center(10) == u' abc '
174 assert u'abc'.center(6) == u' abc '
175 assert u'abc'.center(3) == u'abc'
176 assert u'abc'.center(2) == u'abc'
177 assert u'abc'.center(5, u'*') == u'*abc*' # Python 2.4
178 assert u'abc'.center(5, '*') == u'*abc*' # Python 2.4
179 raises(TypeError, u'abc'.center, 4, u'cba')
180 assert 'x'.center(2, u'\U0010FFFF') == u'x\U0010FFFF'
181
182 def test_title():
183 assert "brown fox".title() == "Brown Fox"
184 assert "!brown fox".title() == "!Brown Fox"
185 assert "bROWN fOX".title() == "Brown Fox"
186 assert "Brown Fox".title() == "Brown Fox"
187 assert "bro!wn fox".title() == "Bro!Wn Fox"
188 assert u'A\u03a3 \u1fa1xy'.title() == u'A\u03c2 \u1fa9xy'
189 assert u'A\u03a3A'.title() == u'A\u03c3a'
190 assert u"brow\u4321n fox".title() == u"Brow\u4321N Fox"
191 assert u'\ud800'.title() == u'\ud800'
192 assert (chr(0x345) + u'abc').title() == u'\u0399abc'
193 assert (chr(0x345) + u'ABC').title() == u'\u0399abc'
194
195 def test_title_bug():
196 assert (chr(496) + "abc").title() == 'J̌abc'
197
198 def test_istitle():
199 assert u"".istitle() == False
200 assert u"!".istitle() == False
201 assert u"!!".istitle() == False
202 assert u"brown fox".istitle() == False
203 assert u"!brown fox".istitle() == False
204 assert u"bROWN fOX".istitle() == False
205 assert u"Brown Fox".istitle() == True
206 assert u"bro!wn fox".istitle() == False
207 assert u"Bro!wn fox".istitle() == False
208 assert u"!brown Fox".istitle() == False
209 assert u"!Brown Fox".istitle() == True
210 assert u"Brow&&&&N Fox".istitle() == True
211 assert u"!Brow&&&&n Fox".istitle() == False
212 assert u'\u1FFc'.istitle()
213 assert u'Greek \u1FFcitlecases ...'.istitle()
214
215 def test_islower_isupper_with_titlecase():
216 # \u01c5 is a char which is neither lowercase nor uppercase, but
217 # titlecase
218 assert not '\u01c5abc'.islower()
219 assert not '\u01c5ABC'.isupper()
220
221 def test_islower():
222 assert u'\u2177'.islower()
223
224 def test_isidentifier():
225 assert "".isidentifier() is False
226 assert "a4".isidentifier() is True
227 assert "_var".isidentifier() is True
228 assert "_!var".isidentifier() is False
229 assert "3abc".isidentifier() is False
230
231 def test_lower_upper():
232 assert u'a'.lower() == u'a'
233 assert u'A'.lower() == u'a'
234 assert u'\u0105'.lower() == u'\u0105'
235 assert u'\u0104'.lower() == u'\u0105'
236 assert u'\ud800'.lower() == u'\ud800'
237 assert u'a'.upper() == u'A'
238 assert u'A'.upper() == u'A'
239 assert u'\u0105'.upper() == u'\u0104'
240 assert u'\u0104'.upper() == u'\u0104'
241 assert u'\ud800'.upper() == u'\ud800'
242
243 def test_capitalize():
244 assert u'A\u0345\u03a3'.capitalize() == u'A\u0345\u03c2'
245 assert u"brown fox".capitalize() == u"Brown fox"
246 assert u' hello '.capitalize() == u' hello '
247 assert u'Hello '.capitalize() == u'Hello '
248 assert u'hello '.capitalize() == u'Hello '
249 assert u'aaaa'.capitalize() == u'Aaaa'
250 assert u'AaAa'.capitalize() == u'Aaaa'
251 # check that titlecased chars are lowered correctly
252 # \u1ffc is the titlecased char
253 assert (u'\u1ff3\u1ff3\u1ffc\u1ffc'.capitalize() ==
254 u'\u1ffc\u1ff3\u1ff3\u1ff3')
255 # check with cased non-letter chars
256 assert (u'\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3'.capitalize() ==
257 u'\u24c5\u24e8\u24e3\u24d7\u24de\u24dd')
258 assert (u'\u24df\u24e8\u24e3\u24d7\u24de\u24dd'.capitalize() ==
259 u'\u24c5\u24e8\u24e3\u24d7\u24de\u24dd')
260 assert u'\u2160\u2161\u2162'.capitalize() == u'\u2160\u2171\u2172'
261 assert u'\u2170\u2171\u2172'.capitalize() == u'\u2160\u2171\u2172'
262 # check with Ll chars with no upper - nothing changes here
263 assert ('\u019b\u1d00\u1d86\u0221\u1fb7'.capitalize() ==
264 '\u019b\u1d00\u1d86\u0221\u1fb7')
265 # cpython issue 17252 for i_dot
266 assert u'h\u0130'.capitalize() == u'H\u0069\u0307'
267
268 def test_capitalize_bug_38():
269 assert 'finnish'.capitalize() == "Finnish"
270
271 def test_changed_in_unicodedata_version_8():
272 assert u'\u025C'.upper() == u'\uA7AB'
273
274 def test_isprintable():
275 assert "".isprintable()
276 assert " ".isprintable()
277 assert "abcdefg".isprintable()
278 assert not "abcdefg\n".isprintable()
279 # some defined Unicode character
280 assert "\u0374".isprintable()
281 # undefined character
282 assert not "\u0378".isprintable()
283 # single surrogate character
284 assert not "\ud800".isprintable()
285
286 def test_isascii():
287 assert "".isascii()
288 assert "abcdefg\t".isascii()
289 assert not "abc\u0374".isascii()
290 assert not "\ud800abc".isascii()
291
292 def test_rjust():
293 s = u"abc"
294 assert s.rjust(2) == s
295 assert s.rjust(3) == s
296 assert s.rjust(4) == u" " + s
297 assert s.rjust(5) == u" " + s
298 assert u'abc'.rjust(10) == u' abc'
299 assert u'abc'.rjust(6) == u' abc'
300 assert u'abc'.rjust(3) == u'abc'
301 assert u'abc'.rjust(2) == u'abc'
302 assert u'abc'.rjust(5, u'*') == u'**abc' # Python 2.4
303 assert u'abc'.rjust(5, '*') == u'**abc' # Python 2.4
304 raises(TypeError, u'abc'.rjust, 5, u'xx')
305
306 def test_ljust():
307 s = u"abc"
308 assert s.ljust(2) == s
309 assert s.ljust(3) == s
310 assert s.ljust(4) == s + u" "
311 assert s.ljust(5) == s + u" "
312 assert u'abc'.ljust(10) == u'abc '
313 assert u'abc'.ljust(6) == u'abc '
314 assert u'abc'.ljust(3) == u'abc'
315 assert u'abc'.ljust(2) == u'abc'
316 assert u'abc'.ljust(5, u'*') == u'abc**' # Python 2.4
317 assert u'abc'.ljust(5, '*') == u'abc**' # Python 2.4
318 raises(TypeError, u'abc'.ljust, 6, u'')
319
320 def test_replace():
321 assert 'one!two!three!'.replace('!', '@', 1) == 'one@two!three!'
322 assert 'one!two!three!'.replace('!', '') == 'onetwothree'
323 assert 'one!two!three!'.replace('!', '@', 2) == 'one@two@three!'
324 assert 'one!two!three!'.replace('!', '@', 3) == 'one@two@three@'
325 assert 'one!two!three!'.replace('!', '@', 4) == 'one@two@three@'
326 assert 'one!two!three!'.replace('!', '@', 0) == 'one!two!three!'
327 assert 'one!two!three!'.replace('!', '@') == 'one@two@three@'
328 assert 'one!two!three!'.replace('x', '@') == 'one!two!three!'
329 assert 'one!two!three!'.replace('x', '@', 2) == 'one!two!three!'
330 assert u'\u1234'.replace(u'', '-') == u'-\u1234-'
331 assert u'\u0234\u5678'.replace('', u'-') == u'-\u0234-\u5678-'
332 assert u'\u0234\u5678'.replace('', u'-', 0) == u'\u0234\u5678'
333 assert u'\u0234\u5678'.replace('', u'-', 1) == u'-\u0234\u5678'
334 assert u'\u0234\u5678'.replace('', u'-', 2) == u'-\u0234-\u5678'
335 assert u'\u0234\u5678'.replace('', u'-', 3) == u'-\u0234-\u5678-'
336 assert u'\u0234\u5678'.replace('', u'-', 4) == u'-\u0234-\u5678-'
337 assert u'\u0234\u5678'.replace('', u'-', 700) == u'-\u0234-\u5678-'
338 assert u'\u0234\u5678'.replace('', u'-', -1) == u'-\u0234-\u5678-'
339 assert u'\u0234\u5678'.replace('', u'-', -42) == u'-\u0234-\u5678-'
340 assert 'abc'.replace('', '-') == '-a-b-c-'
341 assert 'abc'.replace('', '-', 3) == '-a-b-c'
342 assert 'abc'.replace('', '-', 0) == 'abc'
343 assert ''.replace('', '') == ''
344 assert ''.replace('', 'a') == 'a'
345 assert 'abc'.replace('ab', '--', 0) == 'abc'
346 assert 'abc'.replace('xy', '--') == 'abc'
347 assert '123'.replace('123', '') == ''
348 assert '123123'.replace('123', '') == ''
349 assert '123x123'.replace('123', '') == 'x'
350
351 def test_replace_overflow():
352 import sys
353 if sys.maxsize > 2**31-1:
354 skip("Wrong platform")
355 s = "a" * (2**16)
356 raises(OverflowError, s.replace, "", s)
357
358 def test_empty_replace_empty():
359 assert "".replace("", "a", 0) == ""
360 assert "".replace("", "a", 1) == "a"
361 assert "".replace("", "a", 121344) == "a"
362
363 def test_strip():
364 s = " a b "
365 assert s.strip() == "a b"
366 assert s.rstrip() == " a b"
367 assert s.lstrip() == "a b "
368 assert 'xyzzyhelloxyzzy'.strip('xyz') == 'hello'
369 assert 'xyzzyhelloxyzzy'.lstrip('xyz') == 'helloxyzzy'
370 assert 'xyzzyhelloxyzzy'.rstrip('xyz') == 'xyzzyhello'
371 raises(TypeError, s.strip, bytearray(b'a'))
372
373 def test_strip_nonascii():
374 assert 'c\x1d'.strip() == 'c'
375 s = u" ä b "
376 assert s.strip() == u"ä b"
377 assert s.rstrip() == u" ä b"
378 assert s.lstrip() == u"ä b "
379 assert u'xyzzyh³lloxyzzy'.strip(u'xyzü') == u'h³llo'
380 assert u'xyzzyh³lloxyzzy'.lstrip(u'xyzü') == u'h³lloxyzzy'
381 assert u'xyzzyh³lloxyzzy'.rstrip(u'xyzü') == u'xyzzyh³llo'
382
383
384 def test_rstrip_bug():
385 assert u"aaaaaaaaaaaaaaaaaaa".rstrip(u"a") == u""
386 assert u"äääääääääääääääääääääääää".rstrip(u"ä") == u""
387
388
389 def test_strip_space_bug():
390 # mongolian vowel separator is not a space
391 assert u'\u180ea\u180e'.strip() == u'\u180ea\u180e'
392
393
394 def test_long_from_unicode():
395 assert int('12345678901234567890') == 12345678901234567890
396 assert int('123', 7) == 66
397
398 def test_int_from_unicode():
399 assert int('12345') == 12345
400
401 def test_float_from_unicode():
402 assert float('123.456e89') == float('123.456e89')
403
404 def test_repr_16bits():
405 # this used to fail when run on a CPython host with 16-bit unicodes
406 s = repr('\U00101234')
407 assert s == "'\\U00101234'"
408
409 def test_repr():
410 for ustr in ["", "a", "'", "\'", "\"", "\t", "\\", '',
411 'a', '"', '\'', '\"', '\t', '\\', "'''\"",
412 chr(19), chr(2), '\u1234', '\U00101234', '\U0001f42a']:
413 assert eval(repr(ustr)) == ustr
414
415 def test_getnewargs():
416 class X(str):
417 pass
418 x = X("foo\u1234")
419 a = x.__getnewargs__()
420 assert a == ("foo\u1234",)
421 assert type(a[0]) is str
422
423 def test_call_unicode():
424 assert str() == ''
425 assert str(None) == 'None'
426 assert str(123) == '123'
427 assert str(object=123) == '123'
428 assert str([2, 3]) == '[2, 3]'
429 assert str(errors='strict') == ''
430 class U(str):
431 pass
432 assert str(U()).__class__ is str
433 assert U().__str__().__class__ is str
434 assert U('test') == 'test'
435 assert U('test').__class__ is U
436 assert U(errors='strict') == U('')
437
438 def test_call_unicode_2():
439 class X(object):
440 def __bytes__(self):
441 return b'x'
442 raises(TypeError, str, X(), 'ascii')
443
444 def test_startswith():
445 assert 'ab'.startswith('ab') is True
446 assert 'ab'.startswith('a') is True
447 assert 'ab'.startswith('') is True
448 assert 'x'.startswith('a') is False
449 assert 'x'.startswith('x') is True
450 assert ''.startswith('') is True
451 assert ''.startswith('a') is False
452 assert 'x'.startswith('xx') is False
453 assert 'y'.startswith('xx') is False
454 assert u'\u1234\u5678\u4321'.startswith(u'\u1234') is True
455 assert u'\u1234\u5678\u4321'.startswith(u'\u1234\u4321') is False
456 assert u'\u1234'.startswith(u'') is True
457
458 def test_startswith_more():
459 assert 'ab'.startswith('a', 0) is True
460 assert 'ab'.startswith('a', 1) is False
461 assert 'ab'.startswith('b', 1) is True
462 assert 'abc'.startswith('bc', 1, 2) is False
463 assert 'abc'.startswith('c', -1, 4) is True
464 assert '0'.startswith('', 1, -1) is False
465 assert '0'.startswith('', 1, 0) is False
466 assert '0'.startswith('', 1) is True
467 assert '0'.startswith('', 1, None) is True
468 assert ''.startswith('', 1, -1) is False
469 assert ''.startswith('', 1, 0) is False
470 assert ''.startswith('', 1) is False
471 assert ''.startswith('', 1, None) is False
472 try:
473 'hello'.startswith(['o'])
474 except TypeError as e:
475 msg = str(e)
476 assert 'str' in msg
477 assert 'tuple' in msg
478 else:
479 assert False, 'Expected TypeError'
480
481 def test_startswith_too_large():
482 assert u'ab'.startswith(u'b', 1) is True
483 assert u'ab'.startswith(u'', 2) is True
484 assert u'ab'.startswith(u'', 3) is False
485 assert u'ab'.endswith(u'b', 1) is True
486 assert u'ab'.endswith(u'', 2) is True
487 assert u'ab'.endswith(u'', 3) is False
488
489 def test_startswith_tuples():
490 assert 'hello'.startswith(('he', 'ha'))
491 assert not 'hello'.startswith(('lo', 'llo'))
492 assert 'hello'.startswith(('hellox', 'hello'))
493 assert not 'hello'.startswith(())
494 assert 'helloworld'.startswith(('hellowo', 'rld', 'lowo'), 3)
495 assert not 'helloworld'.startswith(('hellowo', 'ello', 'rld'), 3)
496 assert 'hello'.startswith(('lo', 'he'), 0, -1)
497 assert not 'hello'.startswith(('he', 'hel'), 0, 1)
498 assert 'hello'.startswith(('he', 'hel'), 0, 2)
499 raises(TypeError, 'hello'.startswith, (42,))
500
501 def test_startswith_endswith_convert():
502 assert 'hello'.startswith(('he\u1111', 'he'))
503 assert not 'hello'.startswith(('lo\u1111', 'llo'))
504 assert 'hello'.startswith(('hellox\u1111', 'hello'))
505 assert not 'hello'.startswith(('lo', 'he\u1111'), 0, -1)
506 assert not 'hello'.endswith(('he\u1111', 'he'))
507 assert 'hello'.endswith(('\u1111lo', 'llo'))
508 assert 'hello'.endswith(('\u1111hellox', 'hello'))
509
510 def test_endswith():
511 assert 'ab'.endswith('ab') is True
512 assert 'ab'.endswith('b') is True
513 assert 'ab'.endswith('') is True
514 assert 'x'.endswith('a') is False
515 assert 'x'.endswith('x') is True
516 assert ''.endswith('') is True
517 assert ''.endswith('a') is False
518 assert 'x'.endswith('xx') is False
519 assert 'y'.endswith('xx') is False
520 assert 'x'.endswith('', 1, 0) is False
521 assert ''.endswith('', 1, 9223372036854775808) is False
522
523
524 def test_endswith_more():
525 assert 'abc'.endswith('ab', 0, 2) is True
526 assert 'abc'.endswith('bc', 1) is True
527 assert 'abc'.endswith('bc', 2) is False
528 assert 'abc'.endswith('b', -3, -1) is True
529 assert '0'.endswith('', 1, -1) is False
530 try:
531 'hello'.endswith(['o'])
532 except TypeError as e:
533 msg = str(e)
534 assert 'str' in msg
535 assert 'tuple' in msg
536 else:
537 assert False, 'Expected TypeError'
538
539 def test_endswith_tuple():
540 assert not 'hello'.endswith(('he', 'ha'))
541 assert 'hello'.endswith(('lo', 'llo'))
542 assert 'hello'.endswith(('hellox', 'hello'))
543 assert not 'hello'.endswith(())
544 assert 'helloworld'.endswith(('hellowo', 'rld', 'lowo'), 3)
545 assert not 'helloworld'.endswith(('hellowo', 'ello', 'rld'), 3, -1)
546 assert 'hello'.endswith(('hell', 'ell'), 0, -1)
547 assert not 'hello'.endswith(('he', 'hel'), 0, 1)
548 assert 'hello'.endswith(('he', 'hell'), 0, 4)
549 raises(TypeError, 'hello'.endswith, (42,))
550
551 def test_expandtabs():
552 assert 'abc\rab\tdef\ng\thi'.expandtabs() == 'abc\rab def\ng hi'
553 assert 'abc\rab\tdef\ng\thi'.expandtabs(8) == 'abc\rab def\ng hi'
554 assert 'abc\rab\tdef\ng\thi'.expandtabs(4) == 'abc\rab def\ng hi'
555 assert 'abc\r\nab\tdef\ng\thi'.expandtabs(4) == 'abc\r\nab def\ng hi'
556 assert 'abc\rab\tdef\ng\thi'.expandtabs() == 'abc\rab def\ng hi'
557 assert 'abc\rab\tdef\ng\thi'.expandtabs(8) == 'abc\rab def\ng hi'
558 assert 'abc\r\nab\r\ndef\ng\r\nhi'.expandtabs(4) == 'abc\r\nab\r\ndef\ng\r\nhi'
559
560 s = 'xy\t'
561 assert s.expandtabs() =='xy '
562
563 s = '\txy\t'
564 assert s.expandtabs() ==' xy '
565 assert s.expandtabs(1) ==' xy '
566 assert s.expandtabs(2) ==' xy '
567 assert s.expandtabs(3) ==' xy '
568
569 assert 'xy'.expandtabs() =='xy'
570 assert ''.expandtabs() ==''
571
572 def test_expandtabs_overflows_gracefully():
573 import sys
574 raises((OverflowError, MemoryError), 't\tt\t'.expandtabs, sys.maxsize)
575
576 def test_expandtabs_0():
577 assert u'x\ty'.expandtabs(0) == u'xy'
578 assert u'x\ty'.expandtabs(-42) == u'xy'
579
580 def test_expandtabs_bug():
581 assert u"a\u266f\ttest".expandtabs() == u'a\u266f test'
582 assert u"a\u266f\ttest".expandtabs(0) == u'a\u266ftest'
583
584 def test_translate():
585 import sys
586 assert 'bbbc' == 'abababc'.translate({ord('a'):None})
587 assert 'iiic' == 'abababc'.translate({ord('a'):None, ord('b'):ord('i')})
588 assert 'iiix' == 'abababc'.translate({ord('a'):None, ord('b'):ord('i'), ord('c'):'x'})
589 assert '<i><i><i>c' == 'abababc'.translate({ord('a'):None, ord('b'):'<i>'})
590 assert 'c' == 'abababc'.translate({ord('a'):None, ord('b'):''})
591 assert 'xyyx' == 'xzx'.translate({ord('z'):'yy'})
592 assert 'abcd' == 'ab\0d'.translate('c')
593 assert 'abcd' == 'abcd'.translate('')
594 assert 'abababc'.translate({ord('a'): ''}) == 'bbbc'
595
596 raises(TypeError, 'hello'.translate)
597 raises(ValueError, "\xff".translate, {0xff: sys.maxunicode+1})
598 raises(ValueError, u'x'.translate, {ord('x'):0x110000})
599
600 def test_maketrans():
601 assert 'abababc' == 'abababc'.translate({'b': '<i>'})
602 tbl = str.maketrans({'a': None, 'b': '<i>'})
603 assert '<i><i><i>c' == 'abababc'.translate(tbl)
604 tbl = str.maketrans('abc', 'xyz', 'd')
605 assert 'xyzzy' == 'abdcdcbdddd'.translate(tbl)
606 tbl = str.maketrans({'\xe9': 'a'})
607 assert "[\xe9]".translate(tbl) == "[a]"
608
609 raises(TypeError, str.maketrans)
610 raises(ValueError, str.maketrans, 'abc', 'defg')
611 raises(TypeError, str.maketrans, 2, 'def')
612 raises(TypeError, str.maketrans, 'abc', 2)
613 raises(TypeError, str.maketrans, 'abc', 'def', 2)
614 raises(ValueError, str.maketrans, {'xy': 2})
615 raises(TypeError, str.maketrans, {(1,): 2})
616
617 raises(TypeError, 'hello'.translate)
618 raises(TypeError, 'abababc'.translate, 'abc', 'xyz')
619
620 def test_maketrans_bug():
621 assert str.maketrans(u'啊', u'阿') == {21834: 38463}
622 assert str.maketrans(u'啊', u'a') == {21834: 97}
623 assert str.maketrans(u'', u'', u'阿') == {38463: None}
624
625 def test_unicode_from_encoded_object():
626 assert str(b'x', 'utf-8') == 'x'
627 assert str(b'x', 'utf-8', 'strict') == 'x'
628
629 def test_unicode_startswith_tuple():
630 assert 'xxx'.startswith(('x', 'y', 'z'), 0)
631 assert 'xxx'.endswith(('x', 'y', 'z'), 0)
632
633 def test_missing_cases():
634 # some random cases, which are discovered to not be tested during annotation
635 assert 'xxx'[1:1] == ''
636
637 # these tests test lots of encodings, so they really belong to the _codecs
638 # module. however, they test useful unicode methods too
639 # they are stolen from CPython's unit tests
640
641 def test_codecs_utf7():
642 utfTests = [
643 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
644 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
645 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
646 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
647 ('+', b'+-'),
648 ('+-', b'+--'),
649 ('+?', b'+-?'),
650 ('\?', b'+AFw?'),
651 ('+?', b'+-?'),
652 (r'\\?', b'+AFwAXA?'),
653 (r'\\\?', b'+AFwAXABc?'),
654 (r'++--', b'+-+---'),
655 ]
656
657 for (x, y) in utfTests:
658 assert x.encode('utf-7') == y
659
660 # surrogates are supported
661 assert str(b'+3ADYAA-', 'utf-7') == '\udc00\ud800'
662
663 assert str(b'+AB', 'utf-7', 'replace') == '\ufffd'
664
665 def test_codecs_utf8():
666 import sys
667 assert ''.encode('utf-8') == b''
668 assert '\u20ac'.encode('utf-8') == b'\xe2\x82\xac'
669 raises(UnicodeEncodeError, '\ud800'.encode, 'utf-8')
670 raises(UnicodeEncodeError, '\udc00'.encode, 'utf-8')
671 raises(UnicodeEncodeError, '\udc00!'.encode, 'utf-8')
672 if sys.maxunicode > 0xFFFF and len(chr(0x10000)) == 1:
673 raises(UnicodeEncodeError, '\ud800\udc02'.encode, 'utf-8')
674 raises(UnicodeEncodeError, '\ud84d\udc56'.encode, 'utf-8')
675 raises(UnicodeEncodeError, ('\ud800\udc02'*1000).encode, 'utf-8')
676 else:
677 assert '\ud800\udc02'.encode('utf-8') == b'\xf0\x90\x80\x82'
678 assert '\ud84d\udc56'.encode('utf-8') == b'\xf0\xa3\x91\x96'
679 assert ('\ud800\udc02'*1000).encode('utf-8') == b'\xf0\x90\x80\x82'*1000
680 assert (
681 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
682 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
683 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
684 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
685 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
686 ' Nunstuck git und'.encode('utf-8') ==
687 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
688 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
689 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
690 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
691 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
692 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
693 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
694 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
695 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
696 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
697 )
698
699 # UTF-8 specific decoding tests
700 assert str(b'\xf0\xa3\x91\x96', 'utf-8') == '\U00023456'
701 assert str(b'\xf0\x90\x80\x82', 'utf-8') == '\U00010002'
702 assert str(b'\xe2\x82\xac', 'utf-8') == '\u20ac'
703 # Invalid Continuation Bytes, EOF
704 raises(UnicodeDecodeError, b'\xc4\x00'.decode, 'utf-8')
705 raises(UnicodeDecodeError, b'\xe2\x82'.decode, 'utf-8')
706 # Non-Canonical Forms
707 raises(UnicodeDecodeError, b'\xc0\x80'.decode, 'utf-8')
708 raises(UnicodeDecodeError, b'\xc1\xbf'.decode, 'utf-8')
709 raises(UnicodeDecodeError, b'\xe0\x9f\xbf'.decode, 'utf-8')
710 raises(UnicodeDecodeError, b'\xf0\x8f\x8f\x84'.decode, 'utf-8')
711 raises(UnicodeDecodeError, b'\xf5\x80\x81\x82'.decode, 'utf-8')
712 raises(UnicodeDecodeError, b'\xf4\x90\x80\x80'.decode, 'utf-8')
713 # CESU-8
714 raises(UnicodeDecodeError, b'\xed\xa0\xbc\xed\xb2\xb1'.decode, 'utf-8')
715
716 def test_encode_fast_path_bug_position():
717 info = raises(UnicodeEncodeError, "ää\ud800".encode, "utf-8")
718 assert info.value.start == 2 # used to be 4
719
720 def test_invalid_lookup():
721
722 raises(LookupError, u"abcd".encode, "hex")
723 raises(LookupError, b"abcd".decode, "hex")
724
725 def test_repr_printable():
726 # PEP 3138: __repr__ respects printable characters.
727 x = '\u027d'
728 y = "'\u027d'"
729 assert (repr(x) == y)
730 x = '\U00090418\u027d\U000582b9\u54c3\U000fcb6e'
731 y = "'\\U00090418\u027d\\U000582b9\u54c3\\U000fcb6e'"
732 assert (repr(x) == y)
733 assert (repr('\n') ==
734 "'\\n'")
735
736
737 def test_partition():
738 assert (u'this is the par', u'ti', u'tion method') == \
739 u'this is the partition method'.partition(u'ti')
740
741 # from raymond's original specification
742 S = u'http://www.python.org'
743 assert (u'http', u'://', u'www.python.org') == S.partition(u'://')
744 assert (u'http://www.python.org', u'', u'') == S.partition(u'?')
745 assert (u'', u'http://', u'www.python.org') == S.partition(u'http://')
746 assert (u'http://www.python.', u'org', u'') == S.partition(u'org')
747
748 raises(ValueError, S.partition, u'')
749 raises(TypeError, S.partition, None)
750
751 def test_rpartition():
752 assert (u'this is the rparti', u'ti', u'on method') == \
753 u'this is the rpartition method'.rpartition(u'ti')
754
755 # from raymond's original specification
756 S = u'http://www.python.org'
757 assert (u'http', u'://', u'www.python.org') == S.rpartition(u'://')
758 assert (u'', u'', u'http://www.python.org') == S.rpartition(u'?')
759 assert (u'', u'http://', u'www.python.org') == S.rpartition(u'http://')
760 assert (u'http://www.python.', u'org', u'') == S.rpartition(u'org')
761
762 raises(ValueError, S.rpartition, u'')
763 raises(TypeError, S.rpartition, None)
764
765 def test_mul():
766 zero = 0
767 assert type('' * zero) == type(zero * '') is str
768 assert '' * zero == zero * '' == ''
769 assert 'x' * zero == zero * 'x' == ''
770 assert type('x' * zero) == type(zero * 'x') is str
771 assert '123' * zero == zero * '123' == ''
772 assert type('123' * zero) == type(zero * '123') is str
773 for i in range(10):
774 u = '123' * i
775 assert len(u) == 3*i
776 for j in range(0, i, 3):
777 assert u[j+0] == '1'
778 assert u[j+1] == '2'
779 assert u[j+2] == '3'
780 assert '123' * i == i * '123'
781
782 def test_index():
783 assert "rrarrrrrrrrra".index('a', 4, None) == 12
784 assert "rrarrrrrrrrra".index('a', None, 6) == 2
785 assert u"\u1234\u4321\u5678".index(u'\u5678', 1) == 2
786
787 def test_rindex():
788 from sys import maxsize
789 assert 'abcdefghiabc'.rindex('') == 12
790 assert 'abcdefghiabc'.rindex('def') == 3
791 assert 'abcdefghiabc'.rindex('abc') == 9
792 assert 'abcdefghiabc'.rindex('abc', 0, -1) == 0
793 assert 'abcdefghiabc'.rindex('abc', -4*maxsize, 4*maxsize) == 9
794 assert 'rrarrrrrrrrra'.rindex('a', 4, None) == 12
795 assert u"\u1234\u5678".rindex(u'\u5678') == 1
796
797 raises(ValueError, 'abcdefghiabc'.rindex, 'hib')
798 raises(ValueError, 'defghiabc'.rindex, 'def', 1)
799 raises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
800 raises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
801 raises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
802 raises(TypeError, 'abcdefghijklmn'.rindex, 'abc', 0, 0.0)
803 raises(TypeError, 'abcdefghijklmn'.rindex, 'abc', -10.0, 30)
804
805 def test_rfind():
806 assert 'abcdefghiabc'.rfind('abc') == 9
807 assert 'abcdefghiabc'.rfind('') == 12
808 assert 'abcdefghiabc'.rfind('abcd') == 0
809 assert 'abcdefghiabc'.rfind('abcz') == -1
810 assert u"\u1234\u5678".rfind(u'\u5678') == 1
811
812 def test_rfind_corner_case():
813 assert 'abc'.rfind('', 4) == -1
814
815 def test_count_unicode():
816 assert u'aaa'.count(u'', 10) == 0
817 assert u'aaa'.count(u'', 3) == 1
818 assert u"".count(u"x") ==0
819 assert u"".count(u"") ==1
820 assert u"Python".count(u"") ==7
821 assert u"ab aaba".count(u"ab") ==2
822 assert u'aaa'.count(u'a') == 3
823 assert u'aaa'.count(u'b') == 0
824 assert u'aaa'.count(u'a', -1) == 1
825 assert u'aaa'.count(u'a', -10) == 3
826 assert u'aaa'.count(u'a', 0, -1) == 2
827 assert u'aaa'.count(u'a', 0, -10) == 0
828 assert u'ababa'.count(u'aba') == 1
829
830 def test_swapcase():
831 assert '\xe4\xc4\xdf'.swapcase() == '\xc4\xe4SS'
832 # sigma-little becomes sigma-little-final
833 assert u'A\u0345\u03a3'.swapcase() == u'a\u0399\u03c2'
834 # but not if the previous codepoint is 0-width
835 assert u'\u0345\u03a3'.swapcase() == u'\u0399\u03c3'
836
837 def test_call_special_methods():
838 # xxx not completely clear if these are implementation details or not
839 assert 'abc'.__add__('def') == 'abcdef'
840 assert u'abc'.__rmod__(u'%s') == u'abc'
841 ret = u'abc'.__rmod__('%s')
842 with raises(AttributeError):
843 u'abc'.__radd__(u'def')
844
845 def test_str_unicode_concat_overrides():
846 "Test from Jython about being bug-compatible with CPython."
847
848 def check(value, expected):
849 assert type(value) == type(expected)
850 assert value == expected
851
852 def _test_concat(t1, t2):
853 class SubclassB(t2):
854 def __add__(self, other):
855 return SubclassB(t2(self) + t2(other))
856 check(SubclassB('py') + SubclassB('thon'), SubclassB('python'))
857 check(t1('python') + SubclassB('3'), str('python3'))
858 check(SubclassB('py') + t1('py'), SubclassB('pypy'))
859
860 class SubclassC(t2):
861 def __radd__(self, other):
862 return SubclassC(t2(other) + t2(self))
863 check(SubclassC('stack') + SubclassC('less'), t2('stackless'))
864 check(t1('iron') + SubclassC('python'), SubclassC('ironpython'))
865 check(SubclassC('tiny') + t1('py'), str('tinypy'))
866
867 class SubclassD(t2):
868 def __add__(self, other):
869 return SubclassD(t2(self) + t2(other))
870
871 def __radd__(self, other):
872 return SubclassD(t2(other) + t2(self))
873 check(SubclassD('di') + SubclassD('ct'), SubclassD('dict'))
874 check(t1('list') + SubclassD(' comp'), SubclassD('list comp'))
875 check(SubclassD('dun') + t1('der'), SubclassD('dunder'))
876
877 _test_concat(str, str)
878
879 def test_returns_subclass1():
880 class X(str):
881 pass
882
883 class Y(str):
884 def __str__(self):
885 return X("stuff")
886
887 assert str(Y()).__class__ is X
888
889 def test_returns_subclass2():
890 class StrSubclass(str):
891 pass
892
893 class WithRepr:
894 def __init__(self, value):
895 self.value = value
896 def __repr__(self):
897 return self.value
898
899 expected = StrSubclass("abc")
900 actual = ascii(WithRepr(expected))
901 assert type(actual) is type(expected)
902 assert actual == expected
903
904 expected = r"<\U0001f40d>"
905 actual = ascii(WithRepr(StrSubclass("<\U0001f40d>")))
906 assert type(actual) is type(expected)
907 assert actual == expected
908
909 def test_getslice():
910 s = u"\u0105b\u0107"
911 assert s[:] == u"\u0105b\u0107"
912 assert s[1:] == u"b\u0107"
913 assert s[:2] == u"\u0105b"
914 assert s[1:2] == u"b"
915 assert s[-2:] == u"b\u0107"
916 assert s[:-1] == u"\u0105b"
917 assert s[-2:2] == u"b"
918 assert s[1:-1] == u"b"
919 assert s[-2:-1] == u"b"
920
921 def test_getitem_slice():
922 assert u'123456'.__getitem__(slice(1, 5)) == u'2345'
923 s = u"\u0105b\u0107"
924 assert s[slice(3)] == u"\u0105b\u0107"
925 assert s[slice(1, 3)] == u"b\u0107"
926 assert s[slice(2)] == u"\u0105b"
927 assert s[slice(1, 2)] == u"b"
928 assert s[slice(-2, 3)] == u"b\u0107"
929 assert s[slice(-1)] == u"\u0105b"
930 assert s[slice(-2, 2)] == u"b"
931 assert s[slice(1, -1)] == u"b"
932 assert s[slice(-2, -1)] == u"b"
933 assert u"abcde"[::2] == u"ace"
934 assert u"\u0105\u0106\u0107abcd"[::2] == u"\u0105\u0107bd"
935
936 def test_iter():
937 foo = "\u1111\u2222\u3333"
938 assert hasattr(foo, '__iter__')
939 iter = foo.__iter__()
940 assert next(iter) == '\u1111'
941 assert next(iter) == '\u2222'
942
943 def test_no_len_on_str_iter():
944 iterable = "hello"
945 raises(TypeError, len, iter(iterable))
946
947 def test_encode_raw_unicode_escape():
948 u = str(b'\\', 'raw_unicode_escape')
949 assert u == '\\'
950 s = '\u05d1\u05d3\u05d9\u05e7\u05d4'.encode('raw_unicode_escape')
951 assert s == b'\\u05d1\\u05d3\\u05d9\\u05e7\\u05d4'
952
953 def test_decode_from_buffer():
954 buf = b'character buffers are decoded to unicode'
955 u = str(buf, 'utf-8', 'strict')
956 assert u == 'character buffers are decoded to unicode'
957
958 def test_unicode_conversion_with__str__():
959 class A(str):
960 def __str__(self):
961 return "foo"
962 class B(str):
963 pass
964 a = A('bar')
965 assert a == 'bar'
966 assert str(a) == 'foo'
967 b = B('bar')
968 assert b == 'bar'
969 assert str(b) == 'bar'
970
971 def test_unicode_conversion_with__str__():
972 # new-style classes
973 class A(object):
974 def __str__(self):
975 return '\u1234'
976 s = str(A())
977 assert type(s) is str
978 assert s == '\u1234'
979 # with old-style classes, it's different, but it should work as well
980 class A:
981 def __str__(self):
982 return '\u1234'
983 s = str(A())
984 assert type(s) is str
985 assert s == '\u1234'
986
987 def test_formatting_uchr():
988 assert '%c' % '\U00021483' == '\U00021483'
989
990 def test_formatting_unicode__str__0():
991 assert '%.2s' % "a\xe9\u20ac" == 'a\xe9'
992 class A:
993 def __init__(self, num):
994 self.num = num
995 def __str__(self):
996 return chr(self.num)
997
998 s = '%s' % A(111) # this is ASCII
999 assert type(s) is str
1000 assert s == chr(111)
1001
1002 s = '%s' % A(0x1234) # this is not ASCII
1003 assert type(s) is str
1004 assert s == '\u1234'
1005
1006 # now the same with a new-style class...
1007 class A(object):
1008 def __init__(self, num):
1009 self.num = num
1010 def __str__(self):
1011 return chr(self.num)
1012
1013 s = '%s' % A(111) # this is ASCII
1014 assert type(s) is str
1015 assert s == chr(111)
1016
1017 s = '%s' % A(0x1234) # this is not ASCII
1018 assert type(s) is str
1019 assert s == '\u1234'
1020
1021 def test_formatting_unicode__str__2():
1022 class A:
1023 def __str__(self):
1024 return u'baz'
1025
1026 class B:
1027 def __str__(self):
1028 return 'bar'
1029
1030 a = A()
1031 b = B()
1032 s = '%s %s' % (a, b)
1033 assert s == 'baz bar'
1034
1035 def test_formatting_unicode__str__3():
1036 # "bah" is all I can say
1037 class X(object):
1038 def __repr__(self):
1039 return u'\u1234'
1040 '%s' % X()
1041 #
1042 class X(object):
1043 def __str__(self):
1044 return u'\u1234'
1045 '%s' % X()
1046
1047 def test_formatting_unicode__str__4():
1048 # from lib-python/3/test/test_tokenize
1049 fmt = "%(token)-13.13r %(start)s"
1050 vals = {"token" : u"Örter", "start": "(1, 0)"}
1051 expected = u"'Örter' (1, 0)"
1052 s = fmt % vals
1053 assert s == expected, "\ns = '%s'\nexpected= '%s'" %(s, expected)
1054
1055 def test_format_repeat():
1056 assert format(u"abc", u"z<5") == u"abczz"
1057 assert format(u"abc", u"\u2007<5") == u"abc\u2007\u2007"
1058 assert format(123, "\u2007<5") == "123\u2007\u2007"
1059
1060 def test_formatting_unicode__repr__():
1061 # Printable character
1062 assert '%r' % chr(0xe9) == "'\xe9'"
1063
1064 def test_formatting_not_tuple():
1065 class mydict(dict):
1066 pass
1067 assert 'xxx' % mydict() == 'xxx'
1068 assert 'xxx' % b'foo' == 'xxx' # b'foo' considered as a mapping(!)
1069 assert 'xxx' % bytearray() == 'xxx' # same
1070 assert 'xxx' % [] == 'xxx' # [] considered as a mapping(!)
1071 with raises(TypeError):
1072 'xxx' % 'foo'
1073 with raises(TypeError):
1074 'xxx' % 53
1075
1076 def test_str_subclass():
1077 class Foo9(str):
1078 def __str__(self):
1079 return "world"
1080 assert str(Foo9("hello")) == "world"
1081
1082 def test_format_unicode_subclass():
1083 class U(str):
1084 def __str__(self):
1085 return '__str__ overridden'
1086 u = U('xxx')
1087 assert repr("%s" % u) == "'__str__ overridden'"
1088 assert repr("{}".format(u)) == "'__str__ overridden'"
1089
1090 def test_format_c_overflow():
1091 import sys
1092 raises(OverflowError, u'{0:c}'.format, -1)
1093 raises(OverflowError, u'{0:c}'.format, sys.maxunicode + 1)
1094
1095 def test_format_0s():
1096 assert "{0:8s}".format("result") == "result "
1097 assert "{0:0s}".format("result") == "result"
1098
1099 def test_replace_with_buffer():
1100 raises(TypeError, 'abc'.replace, b'b', b'e')
1101
1102 def test_unicode_subclass():
1103 class S(str):
1104 pass
1105
1106 a = S('hello \u1234')
1107 b = str(a)
1108 assert type(b) is str
1109 assert b == 'hello \u1234'
1110
1111 assert '%s' % S('mar\xe7') == 'mar\xe7'
1112
1113 def test_format_new():
1114 assert '0{0}1{b}2'.format('A', b='B') == '0A1B2'
1115
1116 def test_format_map():
1117 assert '0{a}1'.format_map({'a': 'A'}) == '0A1'
1118
1119 def test_format_map_positional():
1120 raises(ValueError, '{}'.format_map, {})
1121
1122 def test_isdecimal():
1123 assert '0'.isdecimal()
1124 assert not ''.isdecimal()
1125 assert not 'a'.isdecimal()
1126 assert not '\u2460'.isdecimal() # CIRCLED DIGIT ONE
1127
1128 def test_isnumeric():
1129 assert '0'.isnumeric()
1130 assert not ''.isnumeric()
1131 assert not 'a'.isnumeric()
1132 assert '\u2460'.isnumeric() # CIRCLED DIGIT ONE
1133
1134 def test_replace_autoconvert():
1135 res = 'one!two!three!'.replace('!', '@', 1)
1136 assert res == 'one@two!three!'
1137 assert type(res) == str
1138
1139 def test_join_subclass():
1140 class StrSubclass(str):
1141 pass
1142 class BytesSubclass(bytes):
1143 pass
1144
1145 s1 = StrSubclass('a')
1146 assert ''.join([s1]) is not s1
1147 s2 = BytesSubclass(b'a')
1148 assert b''.join([s2]) is not s2
1149
1150 def test_encoding_and_errors_cant_be_none():
1151 with raises(TypeError):
1152 b''.decode(None)
1153 with raises(TypeError):
1154 u''.encode(None)
1155 with raises(TypeError):
1156 str(b'', encoding=None)
1157 with raises(TypeError):
1158 u"".encode("utf-8", None)
1159
1160 def test_encode_wrong_errors():
1161 assert ''.encode(errors='some_wrong_name') == b''
1162
1163 def test_casefold():
1164 assert u'hello'.casefold() == u'hello'
1165 assert u'hELlo'.casefold() == u'hello'
1166 assert u'ß'.casefold() == u'ss'
1167 assert u'fi'.casefold() == u'fi'
1168 assert u'\u03a3'.casefold() == u'\u03c3'
1169 assert u'A\u0345\u03a3'.casefold() == u'a\u03b9\u03c3'
1170 assert u'\u00b5'.casefold() == u'\u03bc'
1171
1172 def test_lower_3a3():
1173 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
1174 assert u'\u03a3'.lower() == u'\u03c3'
1175 assert u'\u0345\u03a3'.lower() == u'\u0345\u03c3'
1176 assert u'A\u0345\u03a3'.lower() == u'a\u0345\u03c2'
1177 assert u'A\u0345\u03a3a'.lower() == u'a\u0345\u03c3a'
1178 assert u'A\u0345\u03a3'.lower() == u'a\u0345\u03c2'
1179 assert u'A\u03a3\u0345'.lower() == u'a\u03c2\u0345'
1180 assert u'\u03a3\u0345 '.lower() == u'\u03c3\u0345 '
1181
1182 def test_title_3a3():
1183 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
1184 assert u'\u03a3abc'.title() == u'\u03a3abc'
1185 assert u'\u03a3'.title() == u'Σ'
1186 assert u'\u0345\u03a3'.title() == u'Ισ'
1187 assert u'A\u0345\u03a3'.title() == u'Aͅς'
1188 assert u'A\u0345\u03a3a'.title() == u'Aͅσa'
1189 assert u'A\u0345\u03a3'.title() == u'Aͅς'
1190 assert u'A\u03a3\u0345'.title() == u'Aςͅ'
1191 assert u'\u03a3\u0345 '.title() == u'Σͅ '
1192
1193 assert u'ääää \u03a3'.title() == u'Ääää Σ'
1194 assert u'ääää \u0345\u03a3'.title() == u'Ääää Ισ'
1195 assert u'ääää A\u0345\u03a3'.title() == u'Ääää Aͅς'
1196 assert u'ääää A\u0345\u03a3a'.title() == u'Ääää Aͅσa'
1197 assert u'ääää A\u0345\u03a3'.title() == u'Ääää Aͅς'
1198 assert u'ääää A\u03a3\u0345'.title() == u'Ääää Aςͅ'
1199 assert u'ääää \u03a3\u0345 '.title() == u'Ääää Σͅ '
1200
1201
1202 def test_unicode_constructor_misc():
1203 x = u'foo'
1204 x += u'bar'
1205 assert str(x) is x
1206 #
1207 class U(str):
1208 def __str__(self):
1209 return u'BOK'
1210 u = U(x)
1211 assert str(u) == u'BOK'
1212 #
1213 class U2(str):
1214 pass
1215 z = U2(u'foobaz')
1216 assert type(str(z)) is str
1217 assert str(z) == u'foobaz'
1218 #
1219 assert str(encoding='supposedly_the_encoding') == u''
1220 assert str(errors='supposedly_the_error') == u''
1221 e = raises(TypeError, str, u'', 'supposedly_the_encoding')
1222 assert str(e.value) == 'decoding str is not supported'
1223 e = raises(TypeError, str, u'', errors='supposedly_the_error')
1224 assert str(e.value) == 'decoding str is not supported'
1225 e = raises(TypeError, str, u, 'supposedly_the_encoding')
1226 assert str(e.value) == 'decoding str is not supported'
1227 e = raises(TypeError, str, z, 'supposedly_the_encoding')
1228 assert str(e.value) == 'decoding str is not supported'
1229 #
1230 e = raises(TypeError, str, 42, 'supposedly_the_encoding')
1231 assert str(e.value) in [
1232 "decoding to str: a bytes-like object is required, not int",
1233 'decoding to str: need a bytes-like object, int found']
1234 e = raises(TypeError, str, None, 'supposedly_the_encoding')
1235 assert str(e.value) in [
1236 'decoding to str: a bytes-like object is required, not None',
1237 'decoding to str: need a bytes-like object, NoneType found']
1238
1239 def test_reduce_iterator():
1240 it = iter(u"abcdef")
1241 assert next(it) == u"a"
1242 assert next(it) == u"b"
1243 assert next(it) == u"c"
1244 assert next(it) == u"d"
1245 args = it.__reduce__()
1246 assert next(it) == u"e"
1247 assert next(it) == u"f"
1248 it2 = args[0](*args[1])
1249 it2.__setstate__(args[2])
1250 assert next(it2) == u"e"
1251 assert next(it2) == u"f"
1252 it3 = args[0](*args[1])
1253 it3.__setstate__(args[2])
1254 assert next(it3) == u"e"
1255 assert next(it3) == u"f"
1256
1257
1258 def test_newlist_utf8_non_ascii():
1259 'ä'.split("\n")[0] # does not crash
1260
1261 def test_replace_no_occurrence():
1262 x = u"xyz"
1263 assert x.replace(u"a", u"b") is x
1264
1265 def test_removeprefix():
1266 assert u'abc'.removeprefix(u'x') == u'abc'
1267 assert u'abc'.removeprefix(u'ab') == u'c'
1268
1269 def test_removesuffix():
1270 assert u'abc'.removesuffix(u'x') == u'abc'
1271 assert u'abc'.removesuffix(u'bc') == u'a'
1272 assert u'abc'.removesuffix(u'') == u'abc'
1273 assert u'spam'.removesuffix(u'am') == u'sp'
1274
1275 def test_id_preserved():
1276 a = u"abc"
1277 assert a * 1 is a
1278
1279 class Sub(str):
1280 pass
1281
1282 a = Sub(u"abc")
1283 assert a * 1 is not a
1284
1285 def test_bad_encoding():
1286 with raises(UnicodeEncodeError):
1287 u"abc".encode("utf-8\udce2\udc80\udc9d")
1288
1289 def test_mul():
1290 assert u'abc'.__mul__(2) == u'abcabc'
1291 with raises(TypeError):
1292 u'abc'.__mul__('')