Debian Codegraph @

pypy/objspace/std/test/test_bytearrayobject.py

raw symbols SCIP
1 # coding: utf-8
2
3 import random
4 from pypy import conftest
5 from pypy.objspace.std import bytearrayobject
6
7 class DontAccess(object):
8 pass
9 dont_access = DontAccess()
10
11 seed = random.randrange(0, 2**31)
12 print "BYTEARRAY TWEAK SEED", seed
13 random.seed(seed)
14
15 class AppTestBytesArray:
16 def setup_class(cls):
17 cls.w_runappdirect = cls.space.wrap(conftest.option.runappdirect)
18 def tweak(w_bytearray):
19 n = random.randint(-3, 16)
20 if n > 0:
21 w_bytearray._data = [dont_access] * n + w_bytearray._data
22 w_bytearray._offset += n
23 cls._old_tweak = [bytearrayobject._tweak_for_tests]
24 bytearrayobject._tweak_for_tests = tweak
25
26 def teardown_class(cls):
27 [bytearrayobject._tweak_for_tests] = cls._old_tweak
28
29 def test_basics(self):
30 b = bytearray()
31 assert type(b) is bytearray
32 assert b.__class__ is bytearray
33
34 def test_constructor(self):
35 assert bytearray() == b""
36 assert bytearray(b'abc') == b"abc"
37 assert bytearray([65, 66, 67]) == b"ABC"
38 assert bytearray(5) == b'\0' * 5
39 assert bytearray(set(b'foo')) in (b'fo', b'of')
40 raises(TypeError, bytearray, ['a', 'bc'])
41 raises(ValueError, bytearray, [65, -3])
42 raises(TypeError, bytearray, [65.0])
43 raises(ValueError, bytearray, -1)
44 assert bytearray('abc', 'ascii') == b'abc'
45 raises(TypeError, bytearray, 'abc', b'ascii')
46 raises(UnicodeEncodeError, bytearray, '\x80', 'ascii')
47
48 def test_init_override(self):
49 class subclass(bytearray):
50 def __init__(self, newarg=1, *args, **kwargs):
51 bytearray.__init__(self, *args, **kwargs)
52 x = subclass(4, source=b"abcd")
53 assert x == b"abcd"
54
55 def test_encoding(self):
56 data = "Hello world\n\u1234\u5678\u9abc\def0\def0"
57 for encoding in 'utf8', 'utf16':
58 b = bytearray(data, encoding)
59 assert b == data.encode(encoding)
60 raises(TypeError, bytearray, 9, 'utf8')
61
62 def test_encoding_with_ignore_errors(self):
63 data = "H\u1234"
64 b = bytearray(data, "latin1", errors="ignore")
65 assert b == b"H"
66
67 def test_len(self):
68 b = bytearray(b'test')
69 assert len(b) == 4
70
71 def test_nohash(self):
72 raises(TypeError, hash, bytearray())
73
74 def test_repr(self):
75 assert repr(bytearray()) == "bytearray(b'')"
76 assert repr(bytearray(b'test')) == "bytearray(b'test')"
77 assert repr(bytearray(b"d'oh")) == r'bytearray(b"d\'oh")'
78 assert repr(bytearray(b'd"oh')) == 'bytearray(b\'d"oh\')'
79 assert repr(bytearray(b'd"\'oh')) == 'bytearray(b\'d"\\\'oh\')'
80 assert repr(bytearray(b'd\'"oh')) == 'bytearray(b\'d\\\'"oh\')'
81
82 def test_str(self):
83 assert str(bytearray()) == "bytearray(b'')"
84 assert str(bytearray(b'test')) == "bytearray(b'test')"
85 assert str(bytearray(b"d'oh")) == r'bytearray(b"d\'oh")'
86
87 def test_getitem(self):
88 b = bytearray(b'test')
89 assert b[0] == ord('t')
90 assert b[2] == ord('s')
91 raises(IndexError, b.__getitem__, 4)
92 assert b[1:5] == bytearray(b'est')
93 assert b[slice(1,5)] == bytearray(b'est')
94 assert b[1:5:2] == bytearray(b'et')
95
96 def test_arithmetic(self):
97 b1 = bytearray(b'hello ')
98 b2 = bytearray(b'world')
99 assert b1 + b2 == bytearray(b'hello world')
100 assert b1 * 2 == bytearray(b'hello hello ')
101 assert b1 * 1 is not b1
102
103 b3 = b1
104 b3 *= 3
105 assert b3 == b'hello hello hello '
106 assert type(b3) == bytearray
107 assert b3 is b1
108
109 def test_contains(self):
110 assert ord('l') in bytearray(b'hello')
111 assert b'l' in bytearray(b'hello')
112 assert bytearray(b'll') in bytearray(b'hello')
113 assert memoryview(b'll') in bytearray(b'hello')
114
115 raises(TypeError, lambda: 'foo' in bytearray(b'foobar'))
116
117 def test_splitlines(self):
118 b = bytearray(b'1234')
119 assert b.splitlines()[0] == b
120 assert b.splitlines()[0] is not b
121
122 assert len(bytearray(b'foo\nbar').splitlines()) == 2
123 for item in bytearray(b'foo\nbar').splitlines():
124 assert isinstance(item, bytearray)
125
126 def test_ord(self):
127 b = bytearray(b'\0A\x7f\x80\xff')
128 assert ([ord(b[i:i+1]) for i in range(len(b))] ==
129 [0, 65, 127, 128, 255])
130 raises(TypeError, ord, bytearray(b'll'))
131 raises(TypeError, ord, bytearray())
132
133 def test_translate(self):
134 b = b'hello'
135 ba = bytearray(b)
136 rosetta = bytearray(range(0, 256))
137 rosetta[ord('o')] = ord('e')
138
139 c = ba.translate(rosetta)
140 assert ba == bytearray(b'hello')
141 assert c == bytearray(b'helle')
142 assert isinstance(c, bytearray)
143
144 def test_strip(self):
145 b = bytearray(b'mississippi ')
146
147 assert b.strip() == b'mississippi'
148 assert b.strip(None) == b'mississippi'
149
150 b = bytearray(b'mississippi')
151
152 for strip_type in bytes, memoryview:
153 assert b.strip(strip_type(b'i')) == b'mississipp'
154 assert b.strip(strip_type(b'm')) == b'ississippi'
155 assert b.strip(strip_type(b'pi')) == b'mississ'
156 assert b.strip(strip_type(b'im')) == b'ssissipp'
157 assert b.strip(strip_type(b'pim')) == b'ssiss'
158 assert b.strip(strip_type(b)) == b''
159
160 def test_iter(self):
161 assert list(bytearray(b'hello')) == [104, 101, 108, 108, 111]
162 assert list(bytearray(b'hello').__iter__()) == [104, 101, 108, 108, 111]
163
164 def test_compare(self):
165 assert bytearray(b'hello') == bytearray(b'hello')
166 assert bytearray(b'hello') < bytearray(b'world')
167 assert bytearray(b'world') > bytearray(b'hello')
168
169 def test_compare_str(self):
170 assert bytearray(b'hello1') == b'hello1'
171 assert not (bytearray(b'hello1') != b'hello1')
172 assert b'hello2' == bytearray(b'hello2')
173 assert not (b'hello1' != bytearray(b'hello1'))
174 # unicode is always different
175 assert not (bytearray(b'hello3') == 'world')
176 assert bytearray(b'hello3') != 'hello3'
177 assert 'hello3' != bytearray(b'world')
178 assert 'hello4' != bytearray(b'hello4')
179 assert not (bytearray(b'') == '')
180 assert not ('' == bytearray(b''))
181 assert bytearray(b'') != ''
182 assert '' != bytearray(b'')
183
184 def test_stringlike_operations(self):
185 assert bytearray(b'hello').islower()
186 assert bytearray(b'HELLO').isupper()
187 assert bytearray(b'hello').isalpha()
188 assert not bytearray(b'hello2').isalpha()
189 assert bytearray(b'hello2').isalnum()
190 assert bytearray(b'1234').isdigit()
191 assert bytearray(b' ').isspace()
192 assert bytearray(b'Abc').istitle()
193
194 assert bytearray(b'hello').count(b'l') == 2
195 assert bytearray(b'hello').count(bytearray(b'l')) == 2
196 assert bytearray(b'hello').count(memoryview(b'l')) == 2
197 assert bytearray(b'hello').count(ord('l')) == 2
198
199 assert bytearray(b'hello').index(b'e') == 1
200 assert bytearray(b'hello').rindex(b'l') == 3
201 assert bytearray(b'hello').index(bytearray(b'e')) == 1
202 assert bytearray(b'hello').find(b'l') == 2
203 assert bytearray(b'hello').find(b'l', -2) == 3
204 assert bytearray(b'hello').rfind(b'l') == 3
205
206 assert bytearray(b'hello').index(ord('e')) == 1
207 assert bytearray(b'hello').rindex(ord('l')) == 3
208 assert bytearray(b'hello').find(ord('e')) == 1
209 assert bytearray(b'hello').rfind(ord('l')) == 3
210
211 assert bytearray(b'hello').startswith(b'he')
212 assert bytearray(b'hello').startswith(bytearray(b'he'))
213 assert bytearray(b'hello').startswith((b'lo', bytearray(b'he')))
214 assert bytearray(b'hello').endswith(b'lo')
215 assert bytearray(b'hello').endswith(bytearray(b'lo'))
216 assert bytearray(b'hello').endswith((bytearray(b'lo'), b'he'))
217 try:
218 bytearray(b'hello').startswith([b'o'])
219 except TypeError as e:
220 assert 'bytes' in str(e)
221 else:
222 assert False, 'Expected TypeError'
223 try:
224 bytearray(b'hello').endswith([b'o'])
225 except TypeError as e:
226 assert 'bytes' in str(e)
227 else:
228 assert False, 'Expected TypeError'
229
230 def test_startswith_too_large(self):
231 assert bytearray(b'0').startswith(bytearray(b''), 1, -1) is False
232 assert bytearray(b'ab').startswith(bytearray(b'b'), 1) is True
233 assert bytearray(b'ab').startswith(bytearray(b''), 2) is True
234 assert bytearray(b'ab').startswith(bytearray(b''), 3) is False
235 assert bytearray(b'ab').endswith(bytearray(b'b'), 1) is True
236 assert bytearray(b'ab').endswith(bytearray(b''), 2) is True
237 assert bytearray(b'ab').endswith(bytearray(b''), 3) is False
238 assert bytearray(b'0').endswith(bytearray(b''), 1, -1) is False
239
240 def test_startswith_self(self):
241 b = bytearray(b'abcd')
242 assert b.startswith(b)
243
244 def test_stringlike_conversions(self):
245 # methods that should return bytearray (and not str)
246 def check(result, expected):
247 assert result == expected
248 assert type(result) is bytearray
249
250 check(bytearray(b'abc').replace(b'b', bytearray(b'd')), b'adc')
251 check(bytearray(b'abc').replace(b'b', b'd'), b'adc')
252 check(bytearray(b'').replace(b'a', b'ab'), b'')
253
254 check(bytearray(b'abc').upper(), b'ABC')
255 check(bytearray(b'ABC').lower(), b'abc')
256 check(bytearray(b'abc').title(), b'Abc')
257 check(bytearray(b'AbC').swapcase(), b'aBc')
258 check(bytearray(b'abC').capitalize(), b'Abc')
259
260 check(bytearray(b'abc').ljust(5), b'abc ')
261 check(bytearray(b'abc').rjust(5), b' abc')
262 check(bytearray(b'abc').center(5), b' abc ')
263 check(bytearray(b'1').zfill(5), b'00001')
264 check(bytearray(b'1\t2').expandtabs(5), b'1 2')
265
266 check(bytearray(b',').join([b'a', bytearray(b'b')]), b'a,b')
267 check(bytearray(b'abca').lstrip(b'a'), b'bca')
268 check(bytearray(b'cabc').rstrip(b'c'), b'cab')
269 check(bytearray(b'abc').lstrip(memoryview(b'a')), b'bc')
270 check(bytearray(b'abc').rstrip(memoryview(b'c')), b'ab')
271 check(bytearray(b'aba').strip(b'a'), b'b')
272
273 def test_empty_replace_empty(self):
274 assert bytearray(b"").replace(b"", b"a", 0) == bytearray(b"")
275 assert bytearray(b"").replace(b"", b"a", 1) == bytearray(b"a")
276 assert bytearray(b"").replace(b"", b"a", 121344) == bytearray(b"a")
277
278 def test_empty_ops_empty(self):
279 import sys
280 empty = bytearray(b'')
281 assert empty.find(b'') == 0
282 assert empty.count(empty, 1, 1) == 0
283 assert empty.find(empty, 1, 1) == -1
284 assert empty.count(empty, sys.maxsize, 0) == 0
285 assert empty.find(empty, sys.maxsize, 0) == -1
286
287 def test_xjust_no_mutate(self):
288 # a previous regression
289 b = bytearray(b'')
290 assert b.ljust(1) == bytearray(b' ')
291 assert not len(b)
292
293 b2 = b.ljust(0)
294 b2 += b' '
295 assert not len(b)
296
297 b2 = b.rjust(0)
298 b2 += b' '
299 assert not len(b)
300
301 def test_split(self):
302 # methods that should return a sequence of bytearrays
303 def check(result, expected):
304 assert result == expected
305 assert set(type(x) for x in result) == set([bytearray])
306
307 b = bytearray(b'mississippi')
308 check(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
309 check(b.split(memoryview(b'i')), [b'm', b'ss', b'ss', b'pp', b''])
310 check(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
311 check(b.rsplit(memoryview(b'i')), [b'm', b'ss', b'ss', b'pp', b''])
312 check(b.rsplit(b'i', 2), [b'mississ', b'pp', b''])
313
314 check(bytearray(b'foo bar').split(), [b'foo', b'bar'])
315 check(bytearray(b'foo bar').split(None), [b'foo', b'bar'])
316
317 check(b.partition(b'ss'), (b'mi', b'ss', b'issippi'))
318 check(b.partition(memoryview(b'ss')), (b'mi', b'ss', b'issippi'))
319 check(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi'))
320 check(b.rpartition(memoryview(b'ss')), (b'missi', b'ss', b'ippi'))
321
322 def test_append(self):
323 b = bytearray(b'abc')
324 b.append(ord('d'))
325 b.append(ord('e'))
326 assert b == b'abcde'
327
328 def test_insert(self):
329 b = bytearray(b'abc')
330 b.insert(0, ord('d'))
331 assert b == bytearray(b'dabc')
332
333 b.insert(-1, ord('e'))
334 assert b == bytearray(b'dabec')
335
336 b.insert(6, ord('f'))
337 assert b == bytearray(b'dabecf')
338
339 b.insert(1, ord('g'))
340 assert b == bytearray(b'dgabecf')
341
342 b.insert(-12, ord('h'))
343 assert b == bytearray(b'hdgabecf')
344
345 raises(TypeError, b.insert, 1, 'g')
346 raises(TypeError, b.insert, 1, b'g')
347 raises(TypeError, b.insert, b'g', b'o')
348
349 def test_pop(self):
350 b = bytearray(b'world')
351 assert b.pop() == ord('d')
352 assert b.pop(0) == ord('w')
353 assert b.pop(-2) == ord('r')
354 raises(IndexError, b.pop, 10)
355 raises(IndexError, bytearray().pop)
356 assert bytearray(b'\xff').pop() == 0xff
357
358 def test_remove(self):
359 class Indexable:
360 def __index__(self):
361 return ord('e')
362
363 b = bytearray(b'hello')
364 b.remove(ord('l'))
365 assert b == b'helo'
366 b.remove(ord('l'))
367 assert b == b'heo'
368 raises(ValueError, b.remove, ord('l'))
369 raises(ValueError, b.remove, 400)
370 raises(TypeError, b.remove, 'e')
371 raises(TypeError, b.remove, 2.3)
372 # remove first and last
373 b.remove(ord('o'))
374 b.remove(ord('h'))
375 assert b == b'e'
376 raises(TypeError, b.remove, 'e')
377 b.remove(Indexable())
378 assert b == b''
379
380 def test_clear(self):
381 b = bytearray(b'hello')
382 b2 = b.copy()
383 b.clear()
384 assert b == bytearray()
385 assert b2 == bytearray(b'hello')
386
387 def test_reverse(self):
388 b = bytearray(b'hello')
389 b.reverse()
390 assert b == bytearray(b'olleh')
391
392 def test_delitem_from_front(self):
393 b = bytearray(b'abcdefghij')
394 del b[0]
395 del b[0]
396 assert len(b) == 8
397 assert b == bytearray(b'cdefghij')
398 del b[-8]
399 del b[-7]
400 assert len(b) == 6
401 assert b == bytearray(b'efghij')
402 del b[:3]
403 assert len(b) == 3
404 assert b == bytearray(b'hij')
405
406 def test_delitem(self):
407 b = bytearray(b'abc')
408 del b[1]
409 assert b == bytearray(b'ac')
410 del b[1:1]
411 assert b == bytearray(b'ac')
412 del b[:]
413 assert b == bytearray()
414
415 b = bytearray(b'fooble')
416 del b[::2]
417 assert b == bytearray(b'obe')
418
419 def test_iadd(self):
420 b = b0 = bytearray(b'abc')
421 xx = bytearray(b'XX')
422 b += b'def'
423 assert b == b'abcdef'
424 assert b is b0
425 raises(TypeError, b.__iadd__, "")
426 #
427 b += xx
428 print(repr(b))
429 assert b == b'abcdefXX'
430 assert b is b0
431 #
432 b += memoryview(b'ABC')
433 assert b == b'abcdefXXABC'
434 assert b is b0
435
436 def test_add(self):
437 b1 = bytearray(b"abc")
438 b2 = bytearray(b"def")
439
440 def check(a, b, expected):
441 result = a + b
442 assert result == expected
443 assert isinstance(result, type(a))
444
445 check(b1, b2, b"abcdef")
446 check(b1, b"def", b"abcdef")
447 check(b"def", b1, b"defabc")
448 check(b1, memoryview(b"def"), b"abcdef")
449 raises(TypeError, lambda: b1 + "def")
450 raises(TypeError, lambda: "abc" + b2)
451
452 def test_fromhex(self):
453 raises(TypeError, bytearray.fromhex, 9)
454
455 assert bytearray.fromhex('') == bytearray()
456 assert bytearray.fromhex('') == bytearray()
457
458 b = bytearray([0x1a, 0x2b, 0x30])
459 assert bytearray.fromhex('1a2B30') == b
460 assert bytearray.fromhex(' 1A 2B 30 ') == b
461 assert bytearray.fromhex('''\t1a\t2B\n
462 30\n''') == b
463 assert bytearray.fromhex('0000') == b'\0\0'
464
465 raises(ValueError, bytearray.fromhex, 'a')
466 raises(ValueError, bytearray.fromhex, 'A')
467 raises(ValueError, bytearray.fromhex, 'rt')
468 raises(ValueError, bytearray.fromhex, '1a b cd')
469 raises(ValueError, bytearray.fromhex, '\x00')
470 raises(ValueError, bytearray.fromhex, '12 \x00 34')
471 raises(ValueError, bytearray.fromhex, '\u1234')
472
473 def test_fromhex_subclass(self):
474 class Sub(bytearray):
475 pass
476 assert type(Sub.fromhex("abcd")) is Sub
477 class mystr(str):
478 pass
479 assert bytearray.fromhex(mystr("abcd")) == bytearray(b'\xab\xcd')
480
481 def test_extend(self):
482 b = bytearray(b'abc')
483 b.extend(bytearray(b'def'))
484 assert b == b'abcdef', b
485 b.extend(b'ghi')
486 assert b == b'abcdefghi', b
487 b.extend(memoryview(b'jkl'))
488 assert b == b'abcdefghijkl'
489
490 b = bytearray(b'world')
491 b.extend([ord(c) for c in 'hello'])
492 assert b == bytearray(b'worldhello')
493
494 b = bytearray(b'world')
495 b.extend(list(b'hello'))
496 assert b == bytearray(b'worldhello')
497
498 b = bytearray(b'world')
499 b.extend(c for c in b'hello')
500 assert b == bytearray(b'worldhello')
501
502 raises(TypeError, b.extend, 3)
503 raises(TypeError, b.extend, [b'fish'])
504 raises(ValueError, b.extend, [256])
505 raises(TypeError, b.extend, object())
506 raises(TypeError, b.extend, [object()])
507 raises(TypeError, b.extend, "unicode")
508
509 b = bytearray(b'abc')
510 b.extend(memoryview(b'def'))
511 assert b == bytearray(b'abcdef')
512
513 def test_extend_calls_len_or_lengthhint(self):
514 class BadLen(object):
515 def __iter__(self): return iter(range(10))
516 def __len__(self): raise RuntimeError('hello')
517 b = bytearray()
518 raises(RuntimeError, b.extend, BadLen())
519
520 def test_setitem_from_front(self):
521 b = bytearray(b'abcdefghij')
522 b[:2] = b''
523 assert len(b) == 8
524 assert b == bytearray(b'cdefghij')
525 b[:3] = b'X'
526 assert len(b) == 6
527 assert b == bytearray(b'Xfghij')
528 b[:2] = b'ABC'
529 assert len(b) == 7
530 assert b == bytearray(b'ABCghij')
531
532 def test_setslice(self):
533 b = bytearray(b'hello')
534 b[:] = [ord(c) for c in 'world']
535 assert b == bytearray(b'world')
536
537 b = bytearray(b'hello world')
538 b[::2] = b'bogoff'
539 assert b == bytearray(b'beolg ooflf')
540
541 def set_wrong_size():
542 b[::2] = b'foo'
543 raises(ValueError, set_wrong_size)
544
545 def test_delitem_slice(self):
546 b = bytearray(b'abcdefghi')
547 del b[5:8]
548 assert b == b'abcdei'
549 del b[:3]
550 assert b == b'dei'
551
552 b = bytearray(b'hello world')
553 del b[::2]
554 assert b == bytearray(b'el ol')
555
556 def test_setitem(self):
557 b = bytearray(b'abcdefghi')
558 b[1] = ord('B')
559 assert b == b'aBcdefghi'
560
561 def test_setitem_slice(self):
562 b = bytearray(b'abcdefghi')
563 b[0:3] = b'ABC'
564 assert b == b'ABCdefghi'
565 b[3:3] = b'...'
566 assert b == b'ABC...defghi'
567 b[3:6] = b'()'
568 assert b == b'ABC()defghi'
569 b[6:6] = b'<<'
570 assert b == b'ABC()d<<efghi'
571
572 def test_buffer(self):
573 b = bytearray(b'abcdefghi')
574 buf = memoryview(b)
575 assert buf[2] == ord('c')
576 buf[3] = ord('D')
577 assert b == b'abcDefghi'
578 buf[4:6] = b'EF'
579 assert b == b'abcDEFghi'
580
581 def test_decode(self):
582 b = bytearray(b'abcdefghi')
583 u = b.decode('utf-8')
584 assert isinstance(u, str)
585 assert u == 'abcdefghi'
586 assert b.decode().encode() == b
587
588 def test_int(self):
589 assert int(bytearray(b'-1234')) == -1234
590 assert int(bytearray(b'10'), 16) == 16
591
592 def test_float(self):
593 assert float(bytearray(b'10.4')) == 10.4
594 assert float(bytearray(b'-1.7e-1')) == -1.7e-1
595 assert float(bytearray('.9e10', 'utf-8')) == .9e10
596 import math
597 assert math.isnan(float(bytearray(b'nan')))
598 raises(ValueError, float, bytearray(b'not_a_number'))
599
600 def test_reduce(self):
601 assert bytearray(b'caf\xe9').__reduce__() == (
602 bytearray, ('caf\xe9', 'latin-1'), None)
603
604 def test_reduce_subclass(self):
605 class Slots(bytearray):
606 __slots__ = ['x', 'y', '__dict__']
607
608 b = Slots(b'caf\xe9')
609 b.x = 1
610 b.y = 2
611 b.z = 3
612
613 assert b.__reduce__() == (
614 Slots, ('caf\xe9', 'latin-1'), ({'z': 3}, {'x': 1, 'y': 2}))
615
616 def test_setitem_slice_performance(self):
617 # because of a complexity bug, this used to take forever on a
618 # translated pypy. On CPython2.6 -A, it takes around 8 seconds.
619 if self.runappdirect:
620 count = 16*1024*1024
621 else:
622 count = 1024
623 b = bytearray(count)
624 for i in range(count):
625 b[i:i+1] = b'y'
626 assert bytes(b) == b'y' * count
627
628 def test_partition_return_copy(self):
629 b = bytearray(b'foo')
630 assert b.partition(b'x')[0] is not b
631
632 def test_split_whitespace(self):
633 b = bytearray(b'\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F')
634 assert b.split() == [b'\x1c\x1d\x1e\x1f']
635
636 def test_maketrans(self):
637 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'
638 result = bytearray.maketrans(b'abc', b'xyz')
639 assert result == table
640 assert type(result) is bytes
641
642 def test_hex(self):
643 assert bytearray(b'santa claus').hex() == "73616e746120636c617573"
644
645 def test_hex_sep(self):
646 res = bytearray(bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73])).hex('.')
647 assert res == "73.61.6e.74.61.20.63.6c.61.75.73"
648 with raises(ValueError):
649 bytes([1, 2, 3]).hex("abc")
650 assert bytearray(
651 bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73])).hex('?', 4) == \
652 "73616e?74612063?6c617573"
653 res = bytearray(bytes([0x73,0x61,0x6e,0x74,0x61,0x20,0x63,0x6c,0x61,0x75,0x73])).hex('.', 0)
654 assert res == "73616e746120636c617573"
655
656 def test_isascii(self):
657 assert bytearray(b'hello world').isascii() is True
658 assert bytearray(b'\x00\x7f').isascii() is True
659 assert bytearray(b'\x80').isascii() is False
660 ba = bytearray(b"\xff\xffHello World")
661 assert ba.isascii() is False
662 del ba[0:1]
663 assert ba.isascii() is False
664 del ba[0:1]
665 assert ba.isascii() is True
666
667 def test_format(self):
668 """
669 assert bytearray(b'a%db') % 2 == b'a2b'
670 assert bytearray(b'00%.2f').__mod__((0.01234,)) == b'000.01'
671 assert bytearray(b'%04X') % 10 == b'000A'
672 assert bytearray(b'%c') % 48 == b'0'
673 assert bytearray(b'%c') % b'a' == b'a'
674 assert bytearray(b'%c') % bytearray(b'a') == b'a'
675
676 raises(TypeError, bytearray(b'a').__mod__, 5)
677 assert bytearray(b'a').__rmod__(5) == NotImplemented
678 """
679
680 def test_format_b(self):
681 """
682 assert bytearray(b'%b') % b'abc' == b'abc'
683 assert bytearray(b'%b') % u'はい'.encode('utf-8') == u'はい'.encode('utf-8')
684 raises(TypeError, 'bytearray(b"%b") % 3.14')
685 raises(TypeError, 'bytearray(b"%b") % "hello world"')
686 assert bytearray(b'%b %b') % (b'a', bytearray(b'f f e')) == b'a f f e'
687 """
688
689 def test_format_bytes(self):
690 assert bytearray(b'<%s>') % b'abc' == b'<abc>'
691
692 def test_formatting_not_tuple(self):
693 class mydict(dict):
694 pass
695 xxx = bytearray(b'xxx')
696 assert xxx % mydict() == xxx
697 assert xxx % [] == xxx # [] considered as a mapping(!)
698 raises(TypeError, "xxx % 'foo'")
699 raises(TypeError, "xxx % b'foo'")
700 raises(TypeError, "xxx % bytearray()")
701 raises(TypeError, "xxx % 53")
702
703 def test___alloc__(self):
704 # pypy: always returns len()+1; cpython: may be bigger
705 assert bytearray(b'123456').__alloc__() >= 7
706
707 def test_getitem_error_message(self):
708 e = raises(TypeError, bytearray(b'abc').__getitem__, b'd')
709 assert str(e.value).startswith(
710 'bytearray indices must be integers or slices')
711
712 def test_compatibility(self):
713 # see comments in test_bytesobject.test_compatibility
714 b = bytearray(b'hello world')
715 b2 = b'ello'
716 #not testing result, just lack of TypeError
717 for bb in (b2, bytearray(b2), memoryview(b2)):
718 assert b.split(bb)
719 assert b.rsplit(bb)
720 assert b.split(bb[:1])
721 assert b.rsplit(bb[:1])
722 assert b.join((bb, bb))
723 assert bb in b
724 assert b.find(bb)
725 assert b.rfind(bb)
726 assert b.strip(bb)
727 assert b.rstrip(bb)
728 assert b.lstrip(bb)
729 assert not b.startswith(bb)
730 assert not b.startswith((bb, bb))
731 assert not b.endswith(bb)
732 assert not b.endswith((bb, bb))
733 assert bytearray.maketrans(bb, bb)
734
735 def test_constructor_typeerror(self):
736 raises(TypeError, bytearray, b'', 'ascii')
737 raises(TypeError, bytearray, '')
738
739 def test_dont_force_offset(self):
740 def make(x=b'abcdefghij', shift=3):
741 b = bytearray(b'?'*shift + x)
742 b + b'' # force 'b'
743 del b[:shift] # add shift to b._offset
744 return b
745 assert make(shift=0).__alloc__() == 11
746 #
747 x = make(shift=3)
748 assert x.__alloc__() == 14
749 assert memoryview(x)[1] == ord('b')
750 assert x.__alloc__() == 14
751 assert len(x) == 10
752 assert x.__alloc__() == 14
753 assert x[3] == ord('d')
754 assert x[-3] == ord('h')
755 assert x.__alloc__() == 14
756 assert x[3:-3] == b'defg'
757 assert x[-3:3:-1] == b'hgfe'
758 assert x.__alloc__() == 14
759 assert repr(x) == "bytearray(b'abcdefghij')"
760 assert x.__alloc__() == 14
761 #
762 x = make(shift=3)
763 x[3] = ord('D')
764 assert x.__alloc__() == 14
765 x[4:6] = b'EF'
766 assert x.__alloc__() == 14
767 x[6:8] = b'G'
768 assert x.__alloc__() == 13
769 x[-2:4:-2] = b'*/'
770 assert x.__alloc__() == 13
771 assert x == bytearray(b'abcDE/G*j')
772 #
773 x = make(b'abcdefghijklmnopqrstuvwxyz', shift=11)
774 assert len(x) == 26
775 assert x.__alloc__() == 38
776 del x[:1]
777 assert len(x) == 25
778 assert x.__alloc__() == 38
779 del x[0:5]
780 assert len(x) == 20
781 assert x.__alloc__() == 38
782 del x[0]
783 assert len(x) == 19
784 assert x.__alloc__() == 38
785 del x[0] # too much emptiness, forces now
786 assert len(x) == 18
787 assert x.__alloc__() == 19
788 #
789 x = make(b'abcdefghijklmnopqrstuvwxyz', shift=11)
790 del x[:9] # too much emptiness, forces now
791 assert len(x) == 17
792 assert x.__alloc__() == 18
793 #
794 x = make(b'abcdefghijklmnopqrstuvwxyz', shift=11)
795 assert x.__alloc__() == 38
796 del x[1]
797 assert x.__alloc__() == 37 # not forced, but the list shrank
798 del x[3:10:2]
799 assert x.__alloc__() == 33
800 assert x == bytearray(b'acdfhjlmnopqrstuvwxyz')
801 #
802 x = make(shift=3)
803 assert b'f' in x
804 assert b'ef' in x
805 assert b'efx' not in x
806 assert b'very long string longer than the original' not in x
807 assert x.__alloc__() == 14
808 assert x.find(b'f') == 5
809 assert x.rfind(b'f', 2, 11) == 5
810 assert x.find(b'fe') == -1
811 assert x.index(b'f', 2, 11) == 5
812 assert x.__alloc__() == 14
813
814 def test_subclass_repr(self):
815 class subclass(bytearray):
816 pass
817 assert repr(subclass(b'test')) == "subclass(b'test')"
818
819 def test_removeprefix(self):
820 assert bytearray(b'abc').removeprefix(b'x') == bytearray(b'abc')
821 assert bytearray(b'abc').removeprefix(b'ab') == bytearray(b'c')
822
823 def test_removesuffix(self):
824 assert bytearray(b'abc').removesuffix(b'x') == bytearray(b'abc')
825 assert bytearray(b'abc').removesuffix(b'bc') == bytearray(b'a')
826
827 def test_mutate_while_slice(self):
828 class X:
829 def __index__(self):
830 del a[:]
831 return 1
832
833 a = bytearray([0])
834 assert a[:X():2] == bytearray()
835 assert a == bytearray()
836
837 a = bytearray([0])
838 assert a[X():2] == bytearray()
839 assert a == bytearray()
840
841 a = bytearray([0])
842 assert a[0:2:X()] == bytearray()
843 assert a == bytearray()
844
845 def test_compare(self):
846 b1 = bytearray([1, 2, 3])
847 b2 = bytearray([1, 2, 3])
848 b3 = bytearray([1, 3])
849
850 assert b1 == b2
851 assert b2 != b3
852 assert b1 <= b2
853 assert b1 <= b3
854 assert b1 < b3
855 assert b1 >= b2
856 assert b3 >= b2
857 assert b3 > b2
858
859 assert not b1 != b2
860 assert not b2 == b3
861 assert not b1 > b2
862 assert not b1 > b3
863 assert not b1 >= b3
864 assert not b1 < b2
865 assert not b3 < b2
866 assert not b3 <= b2
867
868 def test_endswith_special(self):
869 b1 = bytearray(b'0')
870 b2 = bytearray(b'0')
871 assert b1.endswith(b2, 0, 2)