Debian Codegraph @

pypy/objspace/std/test/test_bytesobject.py

raw symbols SCIP
1 # coding: utf-8
2 import pytest
3
4 from pypy.interpreter.error import OperationError
5
6
7 class TestW_BytesObject:
8
9 def teardown_method(self, method):
10 pass
11
12 def test_bytes_w(self):
13 assert self.space.bytes_w(self.space.newbytes("foo")) == "foo"
14
15 def test_equality(self):
16 w = self.space.newbytes
17 assert self.space.eq_w(w('abc'), w('abc'))
18 assert not self.space.eq_w(w('abc'), w('def'))
19
20 def test_order_cmp(self):
21 space = self.space
22 w = space.newbytes
23 assert self.space.is_true(space.lt(w('a'), w('b')))
24 assert self.space.is_true(space.lt(w('a'), w('ab')))
25 assert self.space.is_true(space.le(w('a'), w('a')))
26 assert self.space.is_true(space.gt(w('a'), w('')))
27
28 def test_truth(self):
29 w = self.space.newbytes
30 assert self.space.is_true(w('non-empty'))
31 assert not self.space.is_true(w(''))
32
33 def test_getitem(self):
34 space = self.space
35 w = space.wrap
36 w_str = space.newbytes('abc')
37 assert space.eq_w(space.getitem(w_str, w(0)), w(ord('a')))
38 assert space.eq_w(space.getitem(w_str, w(-1)), w(ord('c')))
39 self.space.raises_w(space.w_IndexError,
40 space.getitem,
41 w_str,
42 w(3))
43
44 def test_slice(self):
45 space = self.space
46 w = space.wrap
47 wb = space.newbytes
48 w_str = wb('abc')
49
50 w_slice = space.newslice(w(0), w(0), space.w_None)
51 assert self.space.eq_w(space.getitem(w_str, w_slice), wb(''))
52
53 w_slice = space.newslice(w(0), w(1), space.w_None)
54 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('a'))
55
56 w_slice = space.newslice(w(0), w(10), space.w_None)
57 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('abc'))
58
59 w_slice = space.newslice(space.w_None, space.w_None, space.w_None)
60 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('abc'))
61
62 w_slice = space.newslice(space.w_None, w(-1), space.w_None)
63 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('ab'))
64
65 w_slice = space.newslice(w(-1), space.w_None, space.w_None)
66 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('c'))
67
68 def test_extended_slice(self):
69 space = self.space
70 if self.space.__class__.__name__.startswith('Trivial'):
71 import sys
72 if sys.version < (2, 3):
73 return
74 w_None = space.w_None
75 w = space.wrap
76 wb = space.newbytes
77 w_str = wb('hello')
78
79 w_slice = space.newslice(w_None, w_None, w(1))
80 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('hello'))
81
82 w_slice = space.newslice(w_None, w_None, w(-1))
83 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('olleh'))
84
85 w_slice = space.newslice(w_None, w_None, w(2))
86 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('hlo'))
87
88 w_slice = space.newslice(w(1), w_None, w(2))
89 assert self.space.eq_w(space.getitem(w_str, w_slice), wb('el'))
90
91 def test_listview_bytes_int(self):
92 w_bytes = self.space.newbytes('abcd')
93 # list(b'abcd') is a list of numbers
94 assert self.space.listview_bytes(w_bytes) == None
95 assert self.space.listview_int(w_bytes) == [97, 98, 99, 100]
96
97 def test_constructor_single_char(self, monkeypatch):
98 from rpython.rlib import jit
99 monkeypatch.setattr(jit, 'isconstant', lambda x: True)
100 space = self.space
101 w_res = space.call_function(space.w_bytes, space.wrap([42]))
102 assert space.bytes_w(w_res) == b'*'
103
104
105 class AppTestBytesObject:
106
107 def setup_class(cls):
108 cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
109
110 def test_constructor(self):
111 assert bytes() == b''
112 assert bytes(3) == b'\0\0\0'
113 assert bytes(b'abc') == b'abc'
114 assert bytes('abc', 'ascii') == b'abc'
115 assert bytes(set(b'foo')) in (b'fo', b'of')
116 assert bytes([]) == b''
117 assert bytes([42]) == b'*'
118 assert bytes([0xFC]) == b'\xFC'
119 assert bytes([42, 0xCC]) == b'*\xCC'
120 raises(TypeError, bytes, 'abc', b'ascii')
121 raises(UnicodeEncodeError, bytes, '\x80', 'ascii')
122
123 def test_constructor_list_of_objs(self):
124 class X:
125 def __index__(self):
126 return 42
127 class Y:
128 def __int__(self):
129 return 42
130 for obj in [42, X()]:
131 assert bytes([obj]) == b'*'
132 assert bytes([obj, obj, obj]) == b'***'
133 raises(TypeError, bytes, [Y()])
134 raises(TypeError, bytes, [Y(), Y()])
135
136 def test_fromhex(self):
137 assert bytes.fromhex("abcd") == b'\xab\xcd'
138 assert b''.fromhex("abcd") == b'\xab\xcd'
139 assert bytes.fromhex("ab cd ef") == b'\xab\xcd\xef'
140 assert bytes.fromhex("\nab\tcd \tef\t") == b'\xab\xcd\xef'
141 raises(TypeError, bytes.fromhex, b"abcd")
142 info = raises(TypeError, bytes.fromhex, True)
143 assert str(info.value) == 'fromhex() argument must be str, not bool'
144 raises(ValueError, bytes.fromhex, "hello world")
145
146 def test_fromhex_subclass(self):
147 class Sub(bytes):
148 pass
149 assert type(Sub.fromhex("abcd")) is Sub
150 class mystr(str):
151 pass
152 assert bytes.fromhex(mystr("abcd")) == b'\xab\xcd'
153
154 def test_format(self):
155 raises(TypeError, "foo".__mod__, "bar")
156 raises(TypeError, u"foo".__mod__, "bar")
157 raises(TypeError, "foo".__mod__, u"bar")
158
159 for format, arg, cls in [("a %s b", "foo", str),
160 (u"a %s b", "foo", unicode),
161 ("a %s b", u"foo", unicode),
162 (u"a %s b", u"foo", unicode)]:
163 raises(TypeError, format[:2].__mod__, arg)
164 result = format % arg
165 assert result == "a foo b"
166 assert isinstance(result, cls)
167
168 for format, arg, cls in [("a %s b", "foo", str),
169 (u"a %s b", u"foo", unicode)]:
170 raises(TypeError, arg.__rmod__, format[:2])
171 result = arg.__rmod__(format)
172 assert result == "a foo b"
173 assert isinstance(result, cls)
174 for format, arg, cls in [(u"a %s b", "foo", str),
175 ("a %s b", u"foo", unicode)]:
176 result = arg.__rmod__(format)
177 if '__pypy__' in sys.builtin_module_names:
178 raises(TypeError, arg.__rmod__, format[:2])
179 assert result == "a foo b"
180 assert isinstance(result, cls)
181 else:
182 assert result is NotImplemented
183
184 def test_format_wrongtype(self):
185 for int_format in '%d', '%o', '%x', '%u':
186 exc_info = raises(TypeError, int_format.__mod__, '123')
187 expected1 = int_format + ' format: a real number is required, not str'
188 expected2 = int_format + ' format: an integer is required, not str'
189 assert str(exc_info.value) in (expected1, expected2)
190 raises(TypeError, "None % 'abc'") # __rmod__
191 assert b'abc'.__rmod__('-%b-') is NotImplemented
192 assert b'abc'.__rmod__(b'-%b-') == b'-abc-'
193
194 def test_format_bytes(self):
195 assert b'<%s>' % b'abc' == b'<abc>'
196
197 def test_formatting_not_tuple(self):
198 class mydict(dict):
199 pass
200 assert b'xxx' % mydict() == b'xxx'
201 assert b'xxx' % [] == b'xxx' # [] considered as a mapping(!)
202 raises(TypeError, "b'xxx' % 'foo'")
203 raises(TypeError, "b'xxx' % b'foo'")
204 raises(TypeError, "b'xxx' % bytearray()")
205 raises(TypeError, "b'xxx' % 53")
206
207 def test_format_percent_subclass_tuple_ignores_iter(self):
208 class t(tuple):
209 def __iter__(self):
210 yield b"1"
211 yield b"2"
212 yield b"3"
213 assert b"%s %s %s" % t((b"4", b"5", b"6")) == b"4 5 6"
214
215
216 def test_split(self):
217 assert b"".split() == []
218 assert b"".split(b'x') == [b'']
219 assert b" ".split() == []
220 assert b"a".split() == [b'a']
221 assert b"a".split(b"aa") == [b'a']
222 assert b"a".split(b"a", 1) == [b'', b'']
223 assert b" ".split(b" ", 1) == [b'', b'']
224 assert b"aa".split(b"a", 2) == [b'', b'', b'']
225 assert b" a ".split() == [b'a']
226 assert b"a b c".split() == [b'a',b'b',b'c']
227 assert b'this is the split function'.split() == [
228 b'this', b'is', b'the', b'split', b'function']
229 assert b'a|b|c|d'.split(b'|') == [b'a', b'b', b'c', b'd']
230 assert b'a|b|c|d'.split(b'|', 2) == [b'a', b'b', b'c|d']
231 assert b'a b c d'.split(None, 1) == [b'a', b'b c d']
232 assert b'a b c d'.split(None, 2) == [b'a', b'b', b'c d']
233 assert b'a b c d'.split(None, 3) == [b'a', b'b', b'c', b'd']
234 assert b'a b c d'.split(None, 4) == [b'a', b'b', b'c', b'd']
235 assert b'a b c d'.split(None, 0) == [b'a b c d']
236 assert b'a b c d'.split(None, 2) == [b'a', b'b', b'c d']
237 assert b'a b c d '.split() == [b'a', b'b', b'c', b'd']
238 assert b'a//b//c//d'.split(b'//') == [b'a', b'b', b'c', b'd']
239 assert b'endcase test'.split(b'test') == [b'endcase ', b'']
240 raises(ValueError, b'abc'.split, b'')
241 raises(TypeError, b'abc'.split, 123)
242 raises(TypeError, b'abc'.split, None, 1.0)
243
244 def test_rsplit(self):
245 assert b"".rsplit() == []
246 assert b" ".rsplit() == []
247 assert b"a".rsplit() == [b'a']
248 assert b"a".rsplit(b"a", 1) == [b'', b'']
249 assert b" ".rsplit(b" ", 1) == [b'', b'']
250 assert b"aa".rsplit(b"a", 2) == [b'', b'', b'']
251 assert b" a ".rsplit() == [b'a']
252 assert b"a b c".rsplit() == [b'a',b'b',b'c']
253 assert b'this is the rsplit function'.rsplit() == [
254 b'this', b'is', b'the', b'rsplit', b'function']
255 assert b'a|b|c|d'.rsplit(b'|') == [b'a', b'b', b'c', b'd']
256 assert b'a|b|c|d'.rsplit(b'|', 2) == [b'a|b', b'c', b'd']
257 assert b'a b c d'.rsplit(None, 1) == [b'a b c', b'd']
258 assert b'a b c d'.rsplit(None, 2) == [b'a b', b'c', b'd']
259 assert b'a b c d'.rsplit(None, 3) == [b'a', b'b', b'c', b'd']
260 assert b'a b c d'.rsplit(None, 4) == [b'a', b'b', b'c', b'd']
261 assert b'a b c d'.rsplit(None, 0) == [b'a b c d']
262 assert b'a b c d'.rsplit(None, 2) == [b'a b', b'c', b'd']
263 assert b'a b c d '.rsplit() == [b'a', b'b', b'c', b'd']
264 assert b'a//b//c//d'.rsplit(b'//') == [b'a', b'b', b'c', b'd']
265 assert b'endcase test'.rsplit(b'test') == [b'endcase ', b'']
266 raises(ValueError, b'abc'.rsplit, b'')
267
268 def test_title(self):
269 assert b"brown fox".title() == b"Brown Fox"
270 assert b"!brown fox".title() == b"!Brown Fox"
271 assert b"bROWN fOX".title() == b"Brown Fox"
272 assert b"Brown Fox".title() == b"Brown Fox"
273 assert b"bro!wn fox".title() == b"Bro!Wn Fox"
274
275 def test_istitle(self):
276 assert b"".istitle() == False
277 assert b"!".istitle() == False
278 assert b"!!".istitle() == False
279 assert b"brown fox".istitle() == False
280 assert b"!brown fox".istitle() == False
281 assert b"bROWN fOX".istitle() == False
282 assert b"Brown Fox".istitle() == True
283 assert b"bro!wn fox".istitle() == False
284 assert b"Bro!wn fox".istitle() == False
285 assert b"!brown Fox".istitle() == False
286 assert b"!Brown Fox".istitle() == True
287 assert b"Brow&&&&N Fox".istitle() == True
288 assert b"!Brow&&&&n Fox".istitle() == False
289
290 def test_capitalize(self):
291 assert b"brown fox".capitalize() == b"Brown fox"
292 assert b' hello '.capitalize() == b' hello '
293 assert b'Hello '.capitalize() == b'Hello '
294 assert b'hello '.capitalize() == b'Hello '
295 assert b'aaaa'.capitalize() == b'Aaaa'
296 assert b'AaAa'.capitalize() == b'Aaaa'
297
298 def test_isascii(self):
299 assert b"hello".isascii() is True
300 assert b"\x00\x7f".isascii() is True
301 assert b"\x80".isascii() is False
302 assert b"\x97".isascii() is False
303 assert b"\xff".isascii() is False
304 assert b"Hello World\x00".isascii() is True
305 assert b"Hello World\x80".isascii() is False
306
307 def test_rjust(self):
308 s = b"abc"
309 assert s.rjust(2) == s
310 assert s.rjust(3) == s
311 assert s.rjust(4) == b" " + s
312 assert s.rjust(5) == b" " + s
313 assert b'abc'.rjust(10) == b' abc'
314 assert b'abc'.rjust(6) == b' abc'
315 assert b'abc'.rjust(3) == b'abc'
316 assert b'abc'.rjust(2) == b'abc'
317 assert b'abc'.rjust(5, b'*') == b'**abc' # Python 2.4
318 assert b'abc'.rjust(0) == b'abc'
319 assert b'abc'.rjust(-1) == b'abc'
320 assert b'abc'.rjust(5, bytearray(b' ')) == b' abc'
321 raises(TypeError, b'abc'.rjust, 5.0)
322 raises(TypeError, b'abc'.rjust, 5, '*')
323 raises(TypeError, b'abc'.rjust, 5, b'xx')
324 raises(TypeError, b'abc'.rjust, 5, 32)
325
326 def test_ljust(self):
327 s = b"abc"
328 assert s.ljust(2) == s
329 assert s.ljust(3) == s
330 assert s.ljust(4) == s + b" "
331 assert s.ljust(5) == s + b" "
332 assert b'abc'.ljust(10) == b'abc '
333 assert b'abc'.ljust(6) == b'abc '
334 assert b'abc'.ljust(3) == b'abc'
335 assert b'abc'.ljust(2) == b'abc'
336 assert b'abc'.ljust(5, b'*') == b'abc**' # Python 2.4
337 raises(TypeError, b'abc'.ljust, 5, '*')
338 raises(TypeError, b'abc'.ljust, 6, b'')
339
340 def test_replace(self):
341 assert b'one!two!three!'.replace(b'!', b'@', 1) == b'one@two!three!'
342 assert b'one!two!three!'.replace(b'!', b'') == b'onetwothree'
343 assert b'one!two!three!'.replace(b'!', b'@', 2) == b'one@two@three!'
344 assert b'one!two!three!'.replace(b'!', b'@', 3) == b'one@two@three@'
345 assert b'one!two!three!'.replace(b'!', b'@', 4) == b'one@two@three@'
346 assert b'one!two!three!'.replace(b'!', b'@', 0) == b'one!two!three!'
347 assert b'one!two!three!'.replace(b'!', b'@') == b'one@two@three@'
348 assert b'one!two!three!'.replace(b'x', b'@') == b'one!two!three!'
349 assert b'one!two!three!'.replace(b'x', b'@', 2) == b'one!two!three!'
350 assert b'abc'.replace(b'', b'-') == b'-a-b-c-'
351 assert b'abc'.replace(b'', b'-', 3) == b'-a-b-c'
352 assert b'abc'.replace(b'', b'-', 0) == b'abc'
353 assert b''.replace(b'', b'') == b''
354 assert b''.replace(b'', b'a') == b'a'
355 assert b'abc'.replace(b'ab', b'--', 0) == b'abc'
356 assert b'abc'.replace(b'xy', b'--') == b'abc'
357 assert b'123'.replace(b'123', b'') == b''
358 assert b'123123'.replace(b'123', b'') == b''
359 assert b'123x123'.replace(b'123', b'') == b'x'
360
361 def test_replace_buffer(self):
362 assert b'one'.replace(memoryview(b'o'), memoryview(b'n'), 1) == b'nne'
363 assert b'one'.replace(memoryview(b'o'), memoryview(b'n')) == b'nne'
364
365 def test_replace_no_occurrence(self):
366 x = b"xyz"
367 assert x.replace(b"a", b"b") is x
368
369 def test_strip(self):
370 s = b" a b "
371 assert s.strip() == b"a b"
372 assert s.rstrip() == b" a b"
373 assert s.lstrip() == b"a b "
374 assert b'xyzzyhelloxyzzy'.strip(b'xyz') == b'hello'
375 assert b'xyzzyhelloxyzzy'.lstrip(b'xyz') == b'helloxyzzy'
376 assert b'xyzzyhelloxyzzy'.rstrip(b'xyz') == b'xyzzyhello'
377
378 def test_zfill(self):
379 assert b'123'.zfill(2) == b'123'
380 assert b'123'.zfill(3) == b'123'
381 assert b'123'.zfill(4) == b'0123'
382 assert b'+123'.zfill(3) == b'+123'
383 assert b'+123'.zfill(4) == b'+123'
384 assert b'+123'.zfill(5) == b'+0123'
385 assert b'-123'.zfill(3) == b'-123'
386 assert b'-123'.zfill(4) == b'-123'
387 assert b'-123'.zfill(5) == b'-0123'
388 assert b''.zfill(3) == b'000'
389 assert b'34'.zfill(1) == b'34'
390 assert b'34'.zfill(4) == b'0034'
391
392 def test_center(self):
393 s="a b"
394 assert s.center(0) == "a b"
395 assert s.center(1) == "a b"
396 assert s.center(2) == "a b"
397 assert s.center(3) == "a b"
398 assert s.center(4) == "a b "
399 assert s.center(5) == " a b "
400 assert s.center(6) == " a b "
401 assert s.center(7) == " a b "
402 assert s.center(8) == " a b "
403 assert s.center(9) == " a b "
404 assert b'abc'.center(10) == b' abc '
405 assert b'abc'.center(6) == b' abc '
406 assert b'abc'.center(3) == b'abc'
407 assert b'abc'.center(2) == b'abc'
408 assert b'abc'.center(5, b'*') == b'*abc*' # Python 2.4
409 assert b'abc'.center(0) == b'abc'
410 assert b'abc'.center(-1) == b'abc'
411 assert b'abc'.center(5, bytearray(b' ')) == b' abc '
412 raises(TypeError, b'abc'.center, 4, b'cba')
413 assert b' abc'.center(7) == b' abc '
414
415 def test_count(self):
416 assert b"".count(b"x") ==0
417 assert b"".count(b"") ==1
418 assert b"Python".count(b"") ==7
419 assert b"ab aaba".count(b"ab") ==2
420 assert b'aaa'.count(b'a') == 3
421 assert b'aaa'.count(b'b') == 0
422 assert b'aaa'.count(b'a', -1) == 1
423 assert b'aaa'.count(b'a', -10) == 3
424 assert b'aaa'.count(b'a', 0, -1) == 2
425 assert b'aaa'.count(b'a', 0, -10) == 0
426 assert b'ababa'.count(b'aba') == 1
427 assert b'ababa'.count(ord('a')) == 3
428
429 def test_startswith(self):
430 assert b'ab'.startswith(b'ab') is True
431 assert b'ab'.startswith(b'a') is True
432 assert b'ab'.startswith(b'') is True
433 assert b'x'.startswith(b'a') is False
434 assert b'x'.startswith(b'x') is True
435 assert b''.startswith(b'') is True
436 assert b''.startswith(b'a') is False
437 assert b'x'.startswith(b'xx') is False
438 assert b'hello'.startswith((bytearray(b'he'), bytearray(b'hel')))
439 assert b'hello'.startswith((b'he', None, 123))
440 assert b'y'.startswith(b'xx') is False
441 try:
442 b'hello'.startswith([b'o'])
443 except TypeError as e:
444 assert 'bytes' in str(e)
445 else:
446 assert False, 'Expected TypeError'
447
448 def test_startswith_more(self):
449 assert b'ab'.startswith(b'a', 0) is True
450 assert b'ab'.startswith(b'a', 1) is False
451 assert b'ab'.startswith(b'b', 1) is True
452 assert b'abc'.startswith(b'bc', 1, 2) is False
453 assert b'abc'.startswith(b'c', -1, 4) is True
454 assert b'0'.startswith(b'', 1, -1) is False
455 assert b'0'.startswith(b'', 1, 0) is False
456 assert b'0'.startswith(b'', 1) is True
457 assert b'0'.startswith(b'', 1, None) is True
458 assert b''.startswith(b'', 1, -1) is False
459 assert b''.startswith(b'', 1, 0) is False
460 assert b''.startswith(b'', 1) is False
461 assert b''.startswith(b'', 1, None) is False
462
463 def test_startswith_too_large(self):
464 assert b'ab'.startswith(b'b', 1) is True
465 assert b'ab'.startswith(b'', 2) is True
466 assert b'ab'.startswith(b'', 3) is False
467 assert b'ab'.endswith(b'b', 1) is True
468 assert b'ab'.endswith(b'', 2) is True
469 assert b'ab'.endswith(b'', 3) is False
470
471 def test_startswith_tuples(self):
472 assert b'hello'.startswith((b'he', b'ha'))
473 assert not b'hello'.startswith((b'lo', b'llo'))
474 assert b'hello'.startswith((b'hellox', b'hello'))
475 assert not b'hello'.startswith(())
476 assert b'helloworld'.startswith((b'hellowo', b'rld', b'lowo'), 3)
477 assert not b'helloworld'.startswith((b'hellowo', b'ello', b'rld'), 3)
478 assert b'hello'.startswith((b'lo', b'he'), 0, -1)
479 assert not b'hello'.startswith((b'he', b'hel'), 0, 1)
480 assert b'hello'.startswith((b'he', b'hel'), 0, 2)
481 raises(TypeError, b'hello'.startswith, (42,))
482
483 def test_endswith(self):
484 assert b'ab'.endswith(b'ab') is True
485 assert b'ab'.endswith(b'b') is True
486 assert b'ab'.endswith(b'') is True
487 assert b'x'.endswith(b'a') is False
488 assert b'x'.endswith(b'x') is True
489 assert b''.endswith(b'') is True
490 assert b''.endswith(b'a') is False
491 assert b'x'.endswith(b'xx') is False
492 assert b'y'.endswith(b'xx') is False
493 try:
494 b'hello'.endswith([b'o'])
495 except TypeError as e:
496 assert 'bytes' in str(e)
497 else:
498 assert False, 'Expected TypeError'
499
500 def test_endswith_more(self):
501 assert b'abc'.endswith(b'ab', 0, 2) is True
502 assert b'abc'.endswith(b'bc', 1) is True
503 assert b'abc'.endswith(b'bc', 2) is False
504 assert b'abc'.endswith(b'b', -3, -1) is True
505 assert b'0'.endswith(b'', 1, -1) is False
506
507 def test_endswith_tuple(self):
508 assert not b'hello'.endswith((b'he', b'ha'))
509 assert b'hello'.endswith((b'lo', b'llo'))
510 assert b'hello'.endswith((b'hellox', b'hello'))
511 assert not b'hello'.endswith(())
512 assert b'helloworld'.endswith((b'hellowo', b'rld', b'lowo'), 3)
513 assert not b'helloworld'.endswith((b'hellowo', b'ello', b'rld'), 3, -1)
514 assert b'hello'.endswith((b'hell', b'ell'), 0, -1)
515 assert not b'hello'.endswith((b'he', b'hel'), 0, 1)
516 assert b'hello'.endswith((b'he', b'hell'), 0, 4)
517 raises(TypeError, b'hello'.endswith, (42,))
518
519 def test_expandtabs(self):
520 import sys
521
522 assert b'abc\rab\tdef\ng\thi'.expandtabs() == b'abc\rab def\ng hi'
523 assert b'abc\rab\tdef\ng\thi'.expandtabs(8) == b'abc\rab def\ng hi'
524 assert b'abc\rab\tdef\ng\thi'.expandtabs(4) == b'abc\rab def\ng hi'
525 assert b'abc\r\nab\tdef\ng\thi'.expandtabs(4) == b'abc\r\nab def\ng hi'
526 assert b'abc\rab\tdef\ng\thi'.expandtabs() == b'abc\rab def\ng hi'
527 assert b'abc\rab\tdef\ng\thi'.expandtabs(8) == b'abc\rab def\ng hi'
528 assert b'abc\r\nab\r\ndef\ng\r\nhi'.expandtabs(4) == b'abc\r\nab\r\ndef\ng\r\nhi'
529
530 s = b'xy\t'
531 assert s.expandtabs() == b'xy '
532
533 s = b'\txy\t'
534 assert s.expandtabs() == b' xy '
535 assert s.expandtabs(1) == b' xy '
536 assert s.expandtabs(2) == b' xy '
537 assert s.expandtabs(3) == b' xy '
538
539 assert b'xy'.expandtabs() == b'xy'
540 assert b''.expandtabs() == b''
541
542 assert b'x\t\t'.expandtabs(-1) == b'x'
543 assert b'x\t\t'.expandtabs(0) == b'x'
544
545 raises(OverflowError, b"t\tt\t".expandtabs, sys.maxsize)
546
547 def test_expandtabs_overflows_gracefully(self):
548 import sys
549 raises((MemoryError, OverflowError), b't\tt\t'.expandtabs, sys.maxsize)
550
551 def test_expandtabs_0(self):
552 assert 'x\ty'.expandtabs(0) == 'xy'
553 assert 'x\ty'.expandtabs(-42) == 'xy'
554
555 def test_splitlines(self):
556 s = b""
557 assert s.splitlines() == []
558 assert s.splitlines() == s.splitlines(1)
559 s = b"a + 4"
560 assert s.splitlines() == [b'a + 4']
561 # The following is true if no newline in string.
562 assert s.splitlines() == s.splitlines(1)
563 s = b"a + 4\nb + 2"
564 assert s.splitlines() == [b'a + 4', b'b + 2']
565 assert s.splitlines(1) == [b'a + 4\n', b'b + 2']
566 s = b"ab\nab\n \n x\n\n\n"
567 assert s.splitlines() ==[b'ab', b'ab', b' ', b' x', b'', b'']
568 assert s.splitlines() ==s.splitlines(0)
569 assert s.splitlines(1) ==[b'ab\n', b'ab\n', b' \n', b' x\n', b'\n', b'\n']
570 s = b"\none\n\two\nthree\n\n"
571 assert s.splitlines() ==[b'', b'one', b'\two', b'three', b'']
572 assert s.splitlines(1) ==[b'\n', b'one\n', b'\two\n', b'three\n', b'\n']
573 # Split on \r and \r\n too
574 assert b'12\r34\r\n56'.splitlines() == [b'12', b'34', b'56']
575 assert b'12\r34\r\n56'.splitlines(1) == [b'12\r', b'34\r\n', b'56']
576
577 def test_find(self):
578 assert b'abcdefghiabc'.find(b'abc') == 0
579 assert b'abcdefghiabc'.find(b'abc', 1) == 9
580 assert b'abcdefghiabc'.find(b'def', 4) == -1
581 assert b'abcdef'.find(b'', 13) == -1
582 assert b'abcdefg'.find(b'def', 5, None) == -1
583 assert b'abcdef'.find(b'd', 6, 0) == -1
584 assert b'abcdef'.find(b'd', 3, 3) == -1
585 raises(TypeError, b'abcdef'.find, b'd', 1.0)
586
587 def test_index(self):
588 from sys import maxsize
589 assert b'abcdefghiabc'.index(b'') == 0
590 assert b'abcdefghiabc'.index(b'def') == 3
591 assert b'abcdefghiabc'.index(b'abc') == 0
592 assert b'abcdefghiabc'.index(b'abc', 1) == 9
593 assert b'abcdefghiabc'.index(b'def', -4*maxsize, 4*maxsize) == 3
594 assert b'abcdefgh'.index(b'def', 2, None) == 3
595 assert b'abcdefgh'.index(b'def', None, None) == 3
596 raises(ValueError, b'abcdefghiabc'.index, b'hib')
597 raises(ValueError, b'abcdefghiab'.index, b'abc', 1)
598 raises(ValueError, b'abcdefghi'.index, b'ghi', 8)
599 raises(ValueError, b'abcdefghi'.index, b'ghi', -1)
600 raises(TypeError, b'abcdefghijklmn'.index, b'abc', 0, 0.0)
601 raises(TypeError, b'abcdefghijklmn'.index, b'abc', -10.0, 30)
602
603 def test_rfind(self):
604 assert b'abc'.rfind(b'', 4) == -1
605 assert b'abcdefghiabc'.rfind(b'abc') == 9
606 assert b'abcdefghiabc'.rfind(b'') == 12
607 assert b'abcdefghiabc'.rfind(b'abcd') == 0
608 assert b'abcdefghiabc'.rfind(b'abcz') == -1
609 assert b'abc'.rfind(b'', 0) == 3
610 assert b'abc'.rfind(b'', 3) == 3
611 assert b'abcdefgh'.rfind(b'def', 2, None) == 3
612
613 def test_rindex(self):
614 from sys import maxsize
615 assert b'abcdefghiabc'.rindex(b'') == 12
616 assert b'abcdefghiabc'.rindex(b'def') == 3
617 assert b'abcdefghiabc'.rindex(b'abc') == 9
618 assert b'abcdefghiabc'.rindex(b'abc', 0, -1) == 0
619 assert b'abcdefghiabc'.rindex(b'abc', -4*maxsize, 4*maxsize) == 9
620 raises(ValueError, b'abcdefghiabc'.rindex, b'hib')
621 raises(ValueError, b'defghiabc'.rindex, b'def', 1)
622 raises(ValueError, b'defghiabc'.rindex, b'abc', 0, -1)
623 raises(ValueError, b'abcdefghi'.rindex, b'ghi', 0, 8)
624 raises(ValueError, b'abcdefghi'.rindex, b'ghi', 0, -1)
625 raises(TypeError, b'abcdefghijklmn'.rindex, b'abc', 0, 0.0)
626 raises(TypeError, b'abcdefghijklmn'.rindex, b'abc', -10.0, 30)
627
628
629 def test_partition(self):
630
631 assert (b'this is the par', b'ti', b'tion method') == \
632 b'this is the partition method'.partition(b'ti')
633
634 # from raymond's original specification
635 S = b'http://www.python.org'
636 assert (b'http', b'://', b'www.python.org') == S.partition(b'://')
637 assert (b'http://www.python.org', b'', b'') == S.partition(b'?')
638 assert (b'', b'http://', b'www.python.org') == S.partition(b'http://')
639 assert (b'http://www.python.', b'org', b'') == S.partition(b'org')
640
641 raises(ValueError, S.partition, b'')
642 raises(TypeError, S.partition, None)
643
644 def test_rpartition(self):
645
646 assert (b'this is the rparti', b'ti', b'on method') == \
647 b'this is the rpartition method'.rpartition(b'ti')
648
649 # from raymond's original specification
650 S = b'http://www.python.org'
651 assert (b'http', b'://', b'www.python.org') == S.rpartition(b'://')
652 assert (b'', b'', b'http://www.python.org') == S.rpartition(b'?')
653 assert (b'', b'http://', b'www.python.org') == S.rpartition(b'http://')
654 assert (b'http://www.python.', b'org', b'') == S.rpartition(b'org')
655
656 raises(ValueError, S.rpartition, b'')
657 raises(TypeError, S.rpartition, None)
658
659 def test_split_maxsplit(self):
660 assert b"/a/b/c".split(b'/', 2) == [b'',b'a',b'b/c']
661 assert b"a/b/c".split(b"/") == [b'a', b'b', b'c']
662 assert b" a ".split(None, 0) == [b'a ']
663 assert b" a ".split(None, 1) == [b'a']
664 assert b" a a ".split(b" ", 0) == [b' a a ']
665 assert b" a a ".split(b" ", 1) == [b'', b'a a ']
666
667 def test_join(self):
668 assert b", ".join([b'a', b'b', b'c']) == b"a, b, c"
669 assert b"".join([]) == b""
670 assert b"-".join([b'a', b'b']) == b'a-b'
671 text = b'text'
672 assert b"".join([text]) is text
673 assert b" -- ".join([text]) is text
674 raises(TypeError, b''.join, 1)
675 raises(TypeError, b''.join, [1])
676 raises(TypeError, b''.join, [[1]])
677
678 def test_unicode_join_str_arg_ascii(self):
679 raises(TypeError, ''.join, [b'\xc3\xa1'])
680
681 def test_unicode_join_endcase(self):
682 # This class inserts a Unicode object into its argument's natural
683 # iteration, in the 3rd position.
684 class OhPhooey(object):
685 def __init__(self, seq):
686 self.it = iter(seq)
687 self.i = 0
688
689 def __iter__(self):
690 return self
691
692 def __next__(self):
693 i = self.i
694 self.i = i+1
695 if i == 2:
696 return "fooled you!"
697 return next(self.it)
698
699 f = (b'a\n', b'b\n', b'c\n')
700 raises(TypeError, b" - ".join, OhPhooey(f))
701
702 def test_lower(self):
703 assert b"aaa AAA".lower() == b"aaa aaa"
704 assert b"".lower() == b""
705
706 def test_upper(self):
707 assert b"aaa AAA".upper() == b"AAA AAA"
708 assert b"".upper() == b""
709
710 def test_isalnum(self):
711 assert b"".isalnum() == False
712 assert b"!Bro12345w&&&&n Fox".isalnum() == False
713 assert b"125 Brown Foxes".isalnum() == False
714 assert b"125BrownFoxes".isalnum() == True
715
716 def test_isalpha(self):
717 assert b"".isalpha() == False
718 assert b"!Bro12345w&&&&nFox".isalpha() == False
719 assert b"Brown Foxes".isalpha() == False
720 assert b"125".isalpha() == False
721
722 def test_isdigit(self):
723 assert b"".isdigit() == False
724 assert b"!Bro12345w&&&&nFox".isdigit() == False
725 assert b"Brown Foxes".isdigit() == False
726 assert b"125".isdigit() == True
727
728 def test_isspace(self):
729 assert b"".isspace() == False
730 assert b"!Bro12345w&&&&nFox".isspace() == False
731 assert b" ".isspace() == True
732 assert b"\t\t\b\b\n".isspace() == False
733 assert b"\t\t".isspace() == True
734 assert b"\t\t\r\r\n".isspace() == True
735
736 def test_islower(self):
737 assert b"".islower() == False
738 assert b" ".islower() == False
739 assert b"\t\t\b\b\n".islower() == False
740 assert b"b".islower() == True
741 assert b"bbb".islower() == True
742 assert b"!bbb".islower() == True
743 assert b"BBB".islower() == False
744 assert b"bbbBBB".islower() == False
745
746 def test_isupper(self):
747 assert b"".isupper() == False
748 assert b" ".isupper() == False
749 assert b"\t\t\b\b\n".isupper() == False
750 assert b"B".isupper() == True
751 assert b"BBB".isupper() == True
752 assert b"!BBB".isupper() == True
753 assert b"bbb".isupper() == False
754 assert b"BBBbbb".isupper() == False
755
756
757 def test_swapcase(self):
758 assert b"aaa AAA 111".swapcase() == b"AAA aaa 111"
759 assert b"".swapcase() == b""
760
761 def test_translate(self):
762 def maketrans(origin, image):
763 if len(origin) != len(image):
764 raise ValueError("maketrans arguments must have same length")
765 L = [i for i in range(256)]
766 for i in range(len(origin)):
767 L[origin[i]] = image[i]
768
769 tbl = bytes(L)
770 return tbl
771
772 table = maketrans(b'abc', b'xyz')
773 assert b'xyzxyz' == b'xyzabcdef'.translate(table, b'def')
774 assert b'xyzxyz' == b'xyzabcdef'.translate(memoryview(table), b'def')
775
776 table = maketrans(b'a', b'A')
777 assert b'Abc' == b'abc'.translate(table)
778 assert b'xyz' == b'xyz'.translate(table)
779 assert b'yz' == b'xyz'.translate(table, b'x')
780 raises(TypeError, b'xyz'.translate, table, 'x')
781
782 raises(ValueError, b'xyz'.translate, b'too short', b'strip')
783 raises(ValueError, b'xyz'.translate, b'too short')
784 raises(ValueError, b'xyz'.translate, b'too long'*33)
785
786 assert b'yz' == b'xyz'.translate(None, b'x') # 2.6
787
788 def test_iter(self):
789 l=[]
790 for i in iter(b"42"):
791 l.append(i)
792 assert l == [52, 50]
793 assert list(b"42".__iter__()) == [52, 50]
794
795 def test_repr(self):
796 for f in str, repr:
797 assert f(b"") =="b''"
798 assert f(b"a") =="b'a'"
799 assert f(b"'") =='b"\'"'
800 assert f(b"\'") =="b\"\'\""
801 assert f(b"\"") =='b\'"\''
802 assert f(b"\t") =="b'\\t'"
803 assert f(b"\\") =="b'\\\\'"
804 assert f(b'') =="b''"
805 assert f(b'a') =="b'a'"
806 assert f(b'"') =="b'\"'"
807 assert f(b'\'') =='b"\'"'
808 assert f(b'\"') =="b'\"'"
809 assert f(b'\t') =="b'\\t'"
810 assert f(b'\\') =="b'\\\\'"
811 assert f(b"'''\"") =='b\'\\\'\\\'\\\'"\''
812 assert f(b"\x13") =="b'\\x13'"
813 assert f(b"\x02") =="b'\\x02'"
814
815 def test_contains(self):
816 assert b'' in b'abc'
817 assert b'a' in b'abc'
818 assert b'ab' in b'abc'
819 assert not b'd' in b'abc'
820 assert 97 in b'a'
821 raises(TypeError, b'a'.__contains__, 1.0)
822 raises(ValueError, b'a'.__contains__, 256)
823 raises(ValueError, b'a'.__contains__, -1)
824 raises(TypeError, b'a'.__contains__, None)
825
826 def test_decode(self):
827 assert b'hello'.decode('ascii') == 'hello'
828 raises(UnicodeDecodeError, b'he\x97lo'.decode, 'ascii')
829
830 def test_decode_surrogatepass_issue_3132(self):
831 with raises(UnicodeDecodeError):
832 b"\xd8=a".decode("utf-16-be", "surrogatepass")
833
834 def test_decode_surrogates_in_encoding(self):
835 with raises(UnicodeEncodeError):
836 # encoding the encoding fails with surrogates
837 b"abc".decode("utf-8\udce2\udc80\udc9d")
838
839 def test_encode(self):
840 assert 'hello'.encode() == b'hello'
841 assert type('hello'.encode()) is bytes
842
843 def test_non_text_encoding(self):
844 raises(LookupError, b'hello'.decode, 'base64')
845 raises(LookupError, 'hello'.encode, 'base64')
846
847 def test_hash(self):
848 if self.runappdirect:
849 skip("randomized hash by default")
850 # check that we have the same hash as CPython for at least 31 bits
851 # (but don't go checking CPython's special case -1)
852 # disabled: assert hash('') == 0 --- different special case
853 assert hash('hello') & 0x7fffffff == 0x347697fd
854 assert hash('hello world!') & 0x7fffffff == 0x2f0bb411
855
856 def test_buffer(self):
857 x = b"he"
858 x += b"llo"
859 b = memoryview(x)
860 assert len(b) == 5
861 assert b[-1] == ord("o")
862 assert b[:] == b"hello"
863 assert b[1:0] == b""
864 raises(TypeError, "b[3] = 'x'")
865
866 def test_concat_array(self):
867 m = memoryview(b"123")
868 assert b"abc" + m == b'abc123'
869
870 def test_fromobject(self):
871 class S:
872 def __bytes__(self):
873 return b"bytes"
874 assert bytes(S()) == b"bytes"
875
876 class X:
877 __bytes__ = property(lambda self: self.bytes)
878 def bytes(self):
879 return b'pyramid'
880 assert bytes(X()) == b'pyramid'
881
882 class Z:
883 def __bytes__(self):
884 return [3, 4]
885 raises(TypeError, bytes, Z())
886
887 def test_fromobject___index__(self):
888 class WithIndex:
889 def __index__(self):
890 return 3
891 assert bytes(WithIndex()) == b'\x00\x00\x00'
892
893 def test_fromobject___int__(self):
894 class WithInt:
895 def __int__(self):
896 return 3
897 raises(TypeError, bytes, WithInt())
898
899 def test_fromobject___bytes__(self):
900 class WithIndex:
901 def __bytes__(self):
902 return b'a'
903 def __index__(self):
904 return 3
905 assert bytes(WithIndex()) == b'a'
906
907 class Str(str):
908 def __bytes__(self):
909 return b'a'
910 assert bytes(Str('abc')) == b'a'
911
912 def test_getnewargs(self):
913 assert b"foo".__getnewargs__() == (b"foo",)
914
915 def test_subclass(self):
916 class S(bytes):
917 pass
918 s = S(b'abc')
919 assert type(b''.join([s])) is bytes
920 assert type(s.join([])) is bytes
921 assert type(s.split(b'x')[0]) is bytes
922 assert type(s.ljust(3)) is bytes
923 assert type(s.rjust(3)) is bytes
924 assert type(S(b'A').upper()) is bytes
925 assert type(S(b'a').lower()) is bytes
926 assert type(S(b'A').capitalize()) is bytes
927 assert type(S(b'A').title()) is bytes
928 assert type(s.replace(s, s)) is bytes
929 assert type(s.replace(b'x', b'y')) is bytes
930 assert type(s.replace(b'x', b'y', 0)) is bytes
931 assert type(s.zfill(3)) is bytes
932 assert type(s.strip()) is bytes
933 assert type(s.rstrip()) is bytes
934 assert type(s.lstrip()) is bytes
935 assert type(s.center(3)) is bytes
936 assert type(s.splitlines()[0]) is bytes
937
938 def test_replace_overflow(self):
939 import sys
940 if sys.maxsize > 2**31-1:
941 skip("Wrong platform")
942 s = b"a" * (2**16)
943 raises(OverflowError, s.replace, b"", s)
944
945 def test_replace_issue2448(self):
946 assert b''.replace(b'', b'x') == b'x'
947 assert b''.replace(b'', b'x', 1000) == b'x'
948
949 def test_getslice(self):
950 s = b"abc"
951 assert s[:] == b"abc"
952 assert s[1:] == b"bc"
953 assert s[:2] == b"ab"
954 assert s[1:2] == b"b"
955 assert s[-2:] == b"bc"
956 assert s[:-1] == b"ab"
957 assert s[-2:2] == b"b"
958 assert s[1:-1] == b"b"
959 assert s[-2:-1] == b"b"
960
961 def test_no_len_on_str_iter(self):
962 iterable = b"hello"
963 raises(TypeError, len, iter(iterable))
964
965 def test___radd__(self):
966 raises(TypeError, "None + ''")
967 raises(AttributeError, "'abc'.__radd__('def')")
968
969
970 class Foo(object):
971 def __radd__(self, other):
972 return 42
973 x = Foo()
974 assert "hello" + x == 42
975
976 def test_maketrans(self):
977 table = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
978 assert bytes.maketrans(b'abc', b'xyz') == table
979 raises(TypeError, bytes.maketrans, 5, 5)
980
981 def test_compatibility(self):
982 #a whole bunch of methods should accept bytearray/memoryview without complaining...
983 #I don't know how slavishly we should follow the cpython spec here, since it appears
984 #quite arbitrary in which methods accept only bytes as secondary arguments or
985 #anything with the buffer protocol
986
987 b = b'hello world'
988 b2 = b'ello'
989 #not testing result, just lack of TypeError
990 for bb in (b2, bytearray(b2), memoryview(b2)):
991 assert b.split(bb)
992 assert b.rsplit(bb)
993 assert b.split(bb[:1])
994 assert b.rsplit(bb[:1])
995 assert b.join((bb, bb)) # accepts memoryview() since CPython 3.4/5
996 assert bb in b
997 assert b.find(bb)
998 assert b.rfind(bb)
999 assert b.strip(bb)
1000 assert b.rstrip(bb)
1001 assert b.lstrip(bb)
1002 assert not b.startswith(bb)
1003 assert not b.startswith((bb, bb))
1004 assert not b.endswith(bb)
1005 assert not b.endswith((bb, bb))
1006 assert bytes.maketrans(bb, bb)
1007
1008 def test_constructor_dont_convert_int(self):
1009 class A(object):
1010 def __int__(self):
1011 return 42
1012 raises(TypeError, bytes, A())
1013
1014 def test_hex(self):
1015 assert bytes('santa claus', 'ascii').hex() == "73616e746120636c617573"
1016 assert bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73]).hex() == \
1017 "73616e746120636c617573"
1018 assert bytes(64).hex() == "00"*64
1019
1020 def test_hex_sep(self):
1021 raises(TypeError, bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73]).hex, 12)
1022 res = bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73]).hex(b'.')
1023 assert res == "73.61.6e.74.61.20.63.6c.61.75.73"
1024 res = bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73]).hex('.')
1025 assert res == "73.61.6e.74.61.20.63.6c.61.75.73"
1026 with raises(ValueError):
1027 bytes([1, 2, 3]).hex("abc")
1028 assert bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73]).hex('?', 4) == \
1029 "73616e?74612063?6c617573"
1030 assert bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73]).hex('?', -4) == \
1031 "73616e74?6120636c?617573"
1032 with raises(ValueError) as excinfo:
1033 bytes([1, 2, 3]).hex("ä")
1034 assert "ASCII" in str(excinfo.value)
1035 with raises(TypeError):
1036 bytes().hex(None, 1)
1037
1038 def test_format(self):
1039 """
1040 assert b'a%db' % 2 == b'a2b'
1041 assert b'00%.2f'.__mod__((0.01234,)) == b'000.01'
1042 assert b'%04X' % 10 == b'000A'
1043 assert b'%c' % 48 == b'0'
1044 assert b'%c' % b'a' == b'a'
1045 """
1046
1047 def test_format_b(self):
1048 """
1049 assert b'%b' % b'abc' == b'abc'
1050 assert b'%b' % u'はい'.encode('utf-8') == u'はい'.encode('utf-8')
1051 raises(TypeError, 'b"%b" % 3.14')
1052 raises(TypeError, 'b"%b" % "hello world"')
1053 assert b'%b %b' % (b'a', bytearray(b'f f e')) == b'a f f e'
1054 """
1055
1056 def test_getitem_error_message(self):
1057 e = raises(TypeError, b'abc'.__getitem__, b'd')
1058 assert str(e.value).startswith(
1059 'byte indices must be integers or slices')
1060
1061 def test_constructor_typeerror(self):
1062 raises(TypeError, bytes, b'', 'ascii')
1063 raises(TypeError, bytes, '')
1064
1065 def test_constructor_subclass(self):
1066 class Sub(bytes):
1067 pass
1068 class X:
1069 def __bytes__(self):
1070 return Sub(b'foo')
1071 assert type(bytes(X())) is Sub
1072
1073 def test_constructor_subclass_2(self):
1074 class Sub(bytes):
1075 pass
1076 class X(bytes):
1077 def __bytes__(self):
1078 return Sub(b'foo')
1079 assert type(bytes(X())) is Sub
1080
1081 def test_constructor_subclass_3(self):
1082 class Sub(bytes):
1083 pass
1084 class X(bytes):
1085 def __bytes__(self):
1086 return Sub(b'foo')
1087 class Sub1(bytes):
1088 pass
1089 assert type(Sub1(X())) is Sub1
1090 assert Sub1(X()) == b'foo'
1091
1092 def test_id(self):
1093 a = b'abcabc'
1094 id_b = id(str(a, 'latin1'))
1095 id_a = id(a)
1096 assert a is not str(a, 'latin1')
1097 assert id_a != id_b
1098
1099 def test_error_message_wrong_self(self):
1100 e = raises(TypeError, bytes.upper, 42)
1101 assert "bytes" in str(e.value)
1102 if hasattr(bytes.upper, 'im_func'):
1103 e = raises(TypeError, bytes.upper.im_func, 42)
1104 assert "'bytes'" in str(e.value)
1105
1106 def test_removeprefix(self):
1107 assert b'abc'.removeprefix(b'x') == b'abc'
1108 assert b'abc'.removeprefix(b'ab') == b'c'
1109 assert b'abc'.removeprefix(b'') == b'abc'
1110
1111 def test_removesuffix(self):
1112 assert b'abc'.removesuffix(b'x') == b'abc'
1113 assert b'abc'.removesuffix(b'bc') == b'a'
1114 assert b'abc'.removesuffix(b'') == b'abc'
1115 assert b'spam'.removesuffix(b'am') == b'sp'
1116
1117 def test_id_preserved(self):
1118 a = b"abc!"
1119 assert a * 1 is a
1120
1121 class Sub(bytes):
1122 pass
1123
1124 a = Sub(b"abc!")
1125 assert a * 1 is not a
1126
1127 def test_bytes_special_method(self):
1128 b = b"abc"
1129 assert b.__bytes__() is b
1130
1131 class Sub(bytes):
1132 pass
1133 a = Sub(b"abc!")
1134 assert a.__bytes__() == a
1135 assert a.__bytes__().__class__ is bytes