Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(5)

Delta Between Two Patch Sets: Lib/test/test_bytes.py

Issue 25958: Implicit ABCs have no means of "anti-registration"
Left Patch Set: Created 4 years, 1 month ago
Right Patch Set: Created 3 years, 6 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_bool.py ('k') | Lib/test/test_collections.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 """Unit tests for the bytes and bytearray types. 1 """Unit tests for the bytes and bytearray types.
2 2
3 XXX This is a mess. Common tests should be moved to buffer_tests.py, 3 XXX This is a mess. Common tests should be unified with string_tests.py (and
4 which itself ought to be unified with string_tests.py (and the latter 4 the latter should be modernized).
5 should be modernized).
6 """ 5 """
7 6
8 import os 7 import os
9 import re 8 import re
10 import sys 9 import sys
11 import copy 10 import copy
12 import functools 11 import functools
13 import pickle 12 import pickle
14 import tempfile 13 import tempfile
15 import unittest 14 import unittest
16 15
17 import test.support 16 import test.support
18 import test.string_tests 17 import test.string_tests
19 import test.buffer_tests 18 import test.list_tests
20 from test.support import bigaddrspacetest, MAX_Py_ssize_t 19 from test.support import bigaddrspacetest, MAX_Py_ssize_t
21 20
22 21
23 if sys.flags.bytes_warning: 22 if sys.flags.bytes_warning:
24 def check_bytes_warnings(func): 23 def check_bytes_warnings(func):
25 @functools.wraps(func) 24 @functools.wraps(func)
26 def wrapper(*args, **kw): 25 def wrapper(*args, **kw):
27 with test.support.check_warnings(('', BytesWarning)): 26 with test.support.check_warnings(('', BytesWarning)):
28 return func(*args, **kw) 27 return func(*args, **kw)
29 return wrapper 28 return wrapper
(...skipping 233 matching lines...) Expand 10 before | Expand all | Expand 10 after
263 def test_repeat_1char(self): 262 def test_repeat_1char(self):
264 self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100 )) 263 self.assertEqual(self.type2test(b'x')*100, self.type2test([ord('x')]*100 ))
265 264
266 def test_contains(self): 265 def test_contains(self):
267 b = self.type2test(b"abc") 266 b = self.type2test(b"abc")
268 self.assertIn(ord('a'), b) 267 self.assertIn(ord('a'), b)
269 self.assertIn(int(ord('a')), b) 268 self.assertIn(int(ord('a')), b)
270 self.assertNotIn(200, b) 269 self.assertNotIn(200, b)
271 self.assertRaises(ValueError, lambda: 300 in b) 270 self.assertRaises(ValueError, lambda: 300 in b)
272 self.assertRaises(ValueError, lambda: -1 in b) 271 self.assertRaises(ValueError, lambda: -1 in b)
272 self.assertRaises(ValueError, lambda: sys.maxsize+1 in b)
273 self.assertRaises(TypeError, lambda: None in b) 273 self.assertRaises(TypeError, lambda: None in b)
274 self.assertRaises(TypeError, lambda: float(ord('a')) in b) 274 self.assertRaises(TypeError, lambda: float(ord('a')) in b)
275 self.assertRaises(TypeError, lambda: "a" in b) 275 self.assertRaises(TypeError, lambda: "a" in b)
276 for f in bytes, bytearray: 276 for f in bytes, bytearray:
277 self.assertIn(f(b""), b) 277 self.assertIn(f(b""), b)
278 self.assertIn(f(b"a"), b) 278 self.assertIn(f(b"a"), b)
279 self.assertIn(f(b"b"), b) 279 self.assertIn(f(b"b"), b)
280 self.assertIn(f(b"c"), b) 280 self.assertIn(f(b"c"), b)
281 self.assertIn(f(b"ab"), b) 281 self.assertIn(f(b"ab"), b)
282 self.assertIn(f(b"bc"), b) 282 self.assertIn(f(b"bc"), b)
(...skipping 194 matching lines...) Expand 10 before | Expand all | Expand 10 after
477 self.assertRaises(ValueError, b.rindex, w) 477 self.assertRaises(ValueError, b.rindex, w)
478 478
479 self.assertEqual(b.rindex(b'ss', 3), 5) 479 self.assertEqual(b.rindex(b'ss', 3), 5)
480 self.assertEqual(b.rindex(b'ss', 0, 6), 2) 480 self.assertEqual(b.rindex(b'ss', 0, 6), 2)
481 481
482 self.assertEqual(b.rindex(i, 1, 3), 1) 482 self.assertEqual(b.rindex(i, 1, 3), 1)
483 self.assertEqual(b.rindex(i, 3, 9), 7) 483 self.assertEqual(b.rindex(i, 3, 9), 7)
484 self.assertRaises(ValueError, b.rindex, w, 1, 3) 484 self.assertRaises(ValueError, b.rindex, w, 1, 3)
485 485
486 def test_mod(self): 486 def test_mod(self):
487 b = b'hello, %b!' 487 b = self.type2test(b'hello, %b!')
488 orig = b 488 orig = b
489 b = b % b'world' 489 b = b % b'world'
490 self.assertEqual(b, b'hello, world!') 490 self.assertEqual(b, b'hello, world!')
491 self.assertEqual(orig, b'hello, %b!') 491 self.assertEqual(orig, b'hello, %b!')
492 self.assertFalse(b is orig) 492 self.assertFalse(b is orig)
493 b = b'%s / 100 = %d%%' 493 b = self.type2test(b'%s / 100 = %d%%')
494 a = b % (b'seventy-nine', 79) 494 a = b % (b'seventy-nine', 79)
495 self.assertEqual(a, b'seventy-nine / 100 = 79%') 495 self.assertEqual(a, b'seventy-nine / 100 = 79%')
496 self.assertIs(type(a), self.type2test)
496 497
497 def test_imod(self): 498 def test_imod(self):
498 b = b'hello, %b!' 499 b = self.type2test(b'hello, %b!')
499 orig = b 500 orig = b
500 b %= b'world' 501 b %= b'world'
501 self.assertEqual(b, b'hello, world!') 502 self.assertEqual(b, b'hello, world!')
502 self.assertEqual(orig, b'hello, %b!') 503 self.assertEqual(orig, b'hello, %b!')
503 self.assertFalse(b is orig) 504 self.assertFalse(b is orig)
504 b = b'%s / 100 = %d%%' 505 b = self.type2test(b'%s / 100 = %d%%')
505 b %= (b'seventy-nine', 79) 506 b %= (b'seventy-nine', 79)
506 self.assertEqual(b, b'seventy-nine / 100 = 79%') 507 self.assertEqual(b, b'seventy-nine / 100 = 79%')
508 self.assertIs(type(b), self.type2test)
509
510 def test_rmod(self):
511 with self.assertRaises(TypeError):
512 object() % self.type2test(b'abc')
513 self.assertIs(self.type2test(b'abc').__rmod__('%r'), NotImplemented)
507 514
508 def test_replace(self): 515 def test_replace(self):
509 b = self.type2test(b'mississippi') 516 b = self.type2test(b'mississippi')
510 self.assertEqual(b.replace(b'i', b'a'), b'massassappa') 517 self.assertEqual(b.replace(b'i', b'a'), b'massassappa')
511 self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi') 518 self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi')
512 519
513 def test_split(self): 520 def test_split_string_error(self):
514 b = self.type2test(b'mississippi') 521 self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
515 self.assertEqual(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b'']) 522
516 self.assertEqual(b.split(b'ss'), [b'mi', b'i', b'ippi']) 523 def test_split_unicodewhitespace(self):
517 self.assertEqual(b.split(b'w'), [b])
518 # with keyword args
519 b = self.type2test(b'a|b|c|d')
520 self.assertEqual(b.split(sep=b'|'), [b'a', b'b', b'c', b'd'])
521 self.assertEqual(b.split(b'|', maxsplit=1), [b'a', b'b|c|d'])
522 self.assertEqual(b.split(sep=b'|', maxsplit=1), [b'a', b'b|c|d'])
523 self.assertEqual(b.split(maxsplit=1, sep=b'|'), [b'a', b'b|c|d'])
524 b = self.type2test(b'a b c d')
525 self.assertEqual(b.split(maxsplit=1), [b'a', b'b c d'])
526
527 def test_split_whitespace(self):
528 for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
529 b'arf\fbarf', b'arf\vbarf'):
530 b = self.type2test(b)
531 self.assertEqual(b.split(), [b'arf', b'barf'])
532 self.assertEqual(b.split(None), [b'arf', b'barf'])
533 self.assertEqual(b.split(None, 2), [b'arf', b'barf'])
534 for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'): 524 for b in (b'a\x1Cb', b'a\x1Db', b'a\x1Eb', b'a\x1Fb'):
535 b = self.type2test(b) 525 b = self.type2test(b)
536 self.assertEqual(b.split(), [b]) 526 self.assertEqual(b.split(), [b])
537 self.assertEqual(self.type2test(b' a bb c ').split(None, 0), [b'a b b c '])
538 self.assertEqual(self.type2test(b' a bb c ').split(None, 1), [b'a', b'bb c '])
539 self.assertEqual(self.type2test(b' a bb c ').split(None, 2), [b'a', b'bb', b'c '])
540 self.assertEqual(self.type2test(b' a bb c ').split(None, 3), [b'a', b'bb', b'c'])
541
542 def test_split_string_error(self):
543 self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
544
545 def test_split_unicodewhitespace(self):
546 b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F") 527 b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
547 self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f']) 528 self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f'])
548
549 def test_rsplit(self):
550 b = self.type2test(b'mississippi')
551 self.assertEqual(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
552 self.assertEqual(b.rsplit(b'ss'), [b'mi', b'i', b'ippi'])
553 self.assertEqual(b.rsplit(b'w'), [b])
554 # with keyword args
555 b = self.type2test(b'a|b|c|d')
556 self.assertEqual(b.rsplit(sep=b'|'), [b'a', b'b', b'c', b'd'])
557 self.assertEqual(b.rsplit(b'|', maxsplit=1), [b'a|b|c', b'd'])
558 self.assertEqual(b.rsplit(sep=b'|', maxsplit=1), [b'a|b|c', b'd'])
559 self.assertEqual(b.rsplit(maxsplit=1, sep=b'|'), [b'a|b|c', b'd'])
560 b = self.type2test(b'a b c d')
561 self.assertEqual(b.rsplit(maxsplit=1), [b'a b c', b'd'])
562
563 def test_rsplit_whitespace(self):
564 for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
565 b'arf\fbarf', b'arf\vbarf'):
566 b = self.type2test(b)
567 self.assertEqual(b.rsplit(), [b'arf', b'barf'])
568 self.assertEqual(b.rsplit(None), [b'arf', b'barf'])
569 self.assertEqual(b.rsplit(None, 2), [b'arf', b'barf'])
570 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 0), [b' a bb c'])
571 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 1), [b' a bb', b'c'])
572 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 2), [b' a ', b'bb', b'c'])
573 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 3), [b'a', b'bb', b'c'])
574 529
575 def test_rsplit_string_error(self): 530 def test_rsplit_string_error(self):
576 self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ') 531 self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ')
577 532
578 def test_rsplit_unicodewhitespace(self): 533 def test_rsplit_unicodewhitespace(self):
579 b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F") 534 b = self.type2test(b"\x09\x0A\x0B\x0C\x0D\x1C\x1D\x1E\x1F")
580 self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f']) 535 self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f'])
581 536
582 def test_partition(self): 537 def test_partition(self):
583 b = self.type2test(b'mississippi') 538 b = self.type2test(b'mississippi')
(...skipping 18 matching lines...) Expand all
602 for proto in range(pickle.HIGHEST_PROTOCOL + 1): 557 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
603 for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0": 558 for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
604 it = itorg = iter(self.type2test(b)) 559 it = itorg = iter(self.type2test(b))
605 data = list(self.type2test(b)) 560 data = list(self.type2test(b))
606 d = pickle.dumps(it, proto) 561 d = pickle.dumps(it, proto)
607 it = pickle.loads(d) 562 it = pickle.loads(d)
608 self.assertEqual(type(itorg), type(it)) 563 self.assertEqual(type(itorg), type(it))
609 self.assertEqual(list(it), data) 564 self.assertEqual(list(it), data)
610 565
611 it = pickle.loads(d) 566 it = pickle.loads(d)
612 try: 567 if not b:
613 next(it)
614 except StopIteration:
615 continue 568 continue
569 next(it)
616 d = pickle.dumps(it, proto) 570 d = pickle.dumps(it, proto)
617 it = pickle.loads(d) 571 it = pickle.loads(d)
618 self.assertEqual(list(it), data[1:]) 572 self.assertEqual(list(it), data[1:])
619
620 def test_strip(self):
621 b = self.type2test(b'mississippi')
622 self.assertEqual(b.strip(b'i'), b'mississipp')
623 self.assertEqual(b.strip(b'm'), b'ississippi')
624 self.assertEqual(b.strip(b'pi'), b'mississ')
625 self.assertEqual(b.strip(b'im'), b'ssissipp')
626 self.assertEqual(b.strip(b'pim'), b'ssiss')
627 self.assertEqual(b.strip(b), b'')
628
629 def test_lstrip(self):
630 b = self.type2test(b'mississippi')
631 self.assertEqual(b.lstrip(b'i'), b'mississippi')
632 self.assertEqual(b.lstrip(b'm'), b'ississippi')
633 self.assertEqual(b.lstrip(b'pi'), b'mississippi')
634 self.assertEqual(b.lstrip(b'im'), b'ssissippi')
635 self.assertEqual(b.lstrip(b'pim'), b'ssissippi')
636
637 def test_rstrip(self):
638 b = self.type2test(b'mississippi')
639 self.assertEqual(b.rstrip(b'i'), b'mississipp')
640 self.assertEqual(b.rstrip(b'm'), b'mississippi')
641 self.assertEqual(b.rstrip(b'pi'), b'mississ')
642 self.assertEqual(b.rstrip(b'im'), b'mississipp')
643 self.assertEqual(b.rstrip(b'pim'), b'mississ')
644
645 def test_strip_whitespace(self):
646 b = self.type2test(b' \t\n\r\f\vabc \t\n\r\f\v')
647 self.assertEqual(b.strip(), b'abc')
648 self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v')
649 self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc')
650 573
651 def test_strip_bytearray(self): 574 def test_strip_bytearray(self):
652 self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b') 575 self.assertEqual(self.type2test(b'abc').strip(memoryview(b'ac')), b'b')
653 self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc' ) 576 self.assertEqual(self.type2test(b'abc').lstrip(memoryview(b'ac')), b'bc' )
654 self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab' ) 577 self.assertEqual(self.type2test(b'abc').rstrip(memoryview(b'ac')), b'ab' )
655 578
656 def test_strip_string_error(self): 579 def test_strip_string_error(self):
657 self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b') 580 self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b')
658 self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b') 581 self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b')
659 self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'b') 582 self.assertRaises(TypeError, self.type2test(b'abc').rstrip, 'b')
(...skipping 94 matching lines...) Expand 10 before | Expand all | Expand 10 after
754 self.assertRaisesRegex(TypeError, r'\bindex\b', b.index, 677 self.assertRaisesRegex(TypeError, r'\bindex\b', b.index,
755 x, None, None, None) 678 x, None, None, None)
756 self.assertRaisesRegex(TypeError, r'\brindex\b', b.rindex, 679 self.assertRaisesRegex(TypeError, r'\brindex\b', b.rindex,
757 x, None, None, None) 680 x, None, None, None)
758 self.assertRaisesRegex(TypeError, r'\bcount\b', b.count, 681 self.assertRaisesRegex(TypeError, r'\bcount\b', b.count,
759 x, None, None, None) 682 x, None, None, None)
760 self.assertRaisesRegex(TypeError, r'\bstartswith\b', b.startswith, 683 self.assertRaisesRegex(TypeError, r'\bstartswith\b', b.startswith,
761 x, None, None, None) 684 x, None, None, None)
762 self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith, 685 self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith,
763 x, None, None, None) 686 x, None, None, None)
687
688 def test_free_after_iterating(self):
689 test.support.check_free_after_iterating(self, iter, self.type2test)
690 test.support.check_free_after_iterating(self, reversed, self.type2test)
764 691
765 692
766 class BytesTest(BaseBytesTest, unittest.TestCase): 693 class BytesTest(BaseBytesTest, unittest.TestCase):
767 type2test = bytes 694 type2test = bytes
768 695
769 def test_getitem_error(self): 696 def test_getitem_error(self):
770 msg = "byte indices must be integers or slices" 697 msg = "byte indices must be integers or slices"
771 with self.assertRaisesRegex(TypeError, msg): 698 with self.assertRaisesRegex(TypeError, msg):
772 b'python'['a'] 699 b'python'['a']
773 700
(...skipping 135 matching lines...) Expand 10 before | Expand all | Expand 10 after
909 self.assertEqual(PyBytes_FromFormat(b'x=%i y=%', c_int(2), c_int(3)), 836 self.assertEqual(PyBytes_FromFormat(b'x=%i y=%', c_int(2), c_int(3)),
910 b'x=2 y=%') 837 b'x=2 y=%')
911 838
912 # Issue #19969: %c must raise OverflowError for values 839 # Issue #19969: %c must raise OverflowError for values
913 # not in the range [0; 255] 840 # not in the range [0; 255]
914 self.assertRaises(OverflowError, 841 self.assertRaises(OverflowError,
915 PyBytes_FromFormat, b'%c', c_int(-1)) 842 PyBytes_FromFormat, b'%c', c_int(-1))
916 self.assertRaises(OverflowError, 843 self.assertRaises(OverflowError,
917 PyBytes_FromFormat, b'%c', c_int(256)) 844 PyBytes_FromFormat, b'%c', c_int(256))
918 845
919
920 def test_bytes_blocking(self): 846 def test_bytes_blocking(self):
921 class IterationBlocked(list): 847 class IterationBlocked(list):
922 __bytes__ = None 848 __bytes__ = None
923 i = [0, 1, 2, 3] 849 i = [0, 1, 2, 3]
924 self.assertEqual(bytes(i), b'\x00\x01\x02\x03') 850 self.assertEqual(bytes(i), b'\x00\x01\x02\x03')
925 self.assertRaises(TypeError, bytes, IterationBlocked(i)) 851 self.assertRaises(TypeError, bytes, IterationBlocked(i))
926 852
927 # At least in CPython, because bytes.__new__ and the C API 853 # At least in CPython, because bytes.__new__ and the C API
928 # PyBytes_FromObject have different fallback rules, integer 854 # PyBytes_FromObject have different fallback rules, integer
929 # fallback is handled specially, so test separately. 855 # fallback is handled specially, so test separately.
930 class IntBlocked(int): 856 class IntBlocked(int):
931 __bytes__ = None 857 __bytes__ = None
932 self.assertEqual(bytes(3), b'\0\0\0') 858 self.assertEqual(bytes(3), b'\0\0\0')
933 self.assertRaises(TypeError, bytes, IntBlocked(3)) 859 self.assertRaises(TypeError, bytes, IntBlocked(3))
934 860
935 # While there is no separately-defined rule for handling bytes 861 # While there is no separately-defined rule for handling bytes
936 # subclasses differently from other buffer-interface classes, 862 # subclasses differently from other buffer-interface classes,
937 # an implementation may well special-case them (as CPython 2.x 863 # an implementation may well special-case them (as CPython 2.x
938 # str did), so test them separately. 864 # str did), so test them separately.
939 class BytesSubclassBlocked(bytes): 865 class BytesSubclassBlocked(bytes):
940 __bytes__ = None 866 __bytes__ = None
941 self.assertEqual(bytes(b'ab'), b'ab') 867 self.assertEqual(bytes(b'ab'), b'ab')
942 self.assertRaises(TypeError, bytes, BytesSubclassBlocked(b'ab')) 868 self.assertRaises(TypeError, bytes, BytesSubclassBlocked(b'ab'))
943 869
944 class BufferBlocked(bytearray): 870 class BufferBlocked(bytearray):
945 __bytes__ = None 871 __bytes__ = None
946 ba, bb = bytearray(b'ab'), BufferBlocked(b'ab') 872 ba, bb = bytearray(b'ab'), BufferBlocked(b'ab')
947 self.assertEqual(bytes(ba), b'ab') 873 self.assertEqual(bytes(ba), b'ab')
948 self.assertRaises(TypeError, bytes, bb) 874 self.assertRaises(TypeError, bytes, bb)
875
949 876
950 class ByteArrayTest(BaseBytesTest, unittest.TestCase): 877 class ByteArrayTest(BaseBytesTest, unittest.TestCase):
951 type2test = bytearray 878 type2test = bytearray
952 879
953 def test_getitem_error(self): 880 def test_getitem_error(self):
954 msg = "bytearray indices must be integers or slices" 881 msg = "bytearray indices must be integers or slices"
955 with self.assertRaisesRegex(TypeError, msg): 882 with self.assertRaisesRegex(TypeError, msg):
956 bytearray(b'python')['a'] 883 bytearray(b'python')['a']
957 884
958 def test_setitem_error(self): 885 def test_setitem_error(self):
(...skipping 209 matching lines...) Expand 10 before | Expand all | Expand 10 after
1168 del b[start:stop:step] 1095 del b[start:stop:step]
1169 self.assertEqual(b, bytearray(L)) 1096 self.assertEqual(b, bytearray(L))
1170 1097
1171 def test_setslice_trap(self): 1098 def test_setslice_trap(self):
1172 # This test verifies that we correctly handle assigning self 1099 # This test verifies that we correctly handle assigning self
1173 # to a slice of self (the old Lambert Meertens trap). 1100 # to a slice of self (the old Lambert Meertens trap).
1174 b = bytearray(range(256)) 1101 b = bytearray(range(256))
1175 b[8:] = b 1102 b[8:] = b
1176 self.assertEqual(b, bytearray(list(range(8)) + list(range(256)))) 1103 self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
1177 1104
1178 def test_mod(self):
1179 b = bytearray(b'hello, %b!')
1180 orig = b
1181 b = b % b'world'
1182 self.assertEqual(b, b'hello, world!')
1183 self.assertEqual(orig, bytearray(b'hello, %b!'))
1184 self.assertFalse(b is orig)
1185 b = bytearray(b'%s / 100 = %d%%')
1186 a = b % (b'seventy-nine', 79)
1187 self.assertEqual(a, bytearray(b'seventy-nine / 100 = 79%'))
1188
1189 def test_imod(self):
1190 b = bytearray(b'hello, %b!')
1191 orig = b
1192 b %= b'world'
1193 self.assertEqual(b, b'hello, world!')
1194 self.assertEqual(orig, bytearray(b'hello, %b!'))
1195 self.assertFalse(b is orig)
1196 b = bytearray(b'%s / 100 = %d%%')
1197 b %= (b'seventy-nine', 79)
1198 self.assertEqual(b, bytearray(b'seventy-nine / 100 = 79%'))
1199
1200 def test_iconcat(self): 1105 def test_iconcat(self):
1201 b = bytearray(b"abc") 1106 b = bytearray(b"abc")
1202 b1 = b 1107 b1 = b
1203 b += b"def" 1108 b += b"def"
1204 self.assertEqual(b, b"abcdef") 1109 self.assertEqual(b, b"abcdef")
1205 self.assertEqual(b, b1) 1110 self.assertEqual(b, b1)
1206 self.assertTrue(b is b1) 1111 self.assertTrue(b is b1)
1207 b += b"xyz" 1112 b += b"xyz"
1208 self.assertEqual(b, b"abcdefxyz") 1113 self.assertEqual(b, b"abcdefxyz")
1209 try: 1114 try:
(...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after
1295 self.assertRaises(ValueError, lambda: b.remove(ord('l'))) 1200 self.assertRaises(ValueError, lambda: b.remove(ord('l')))
1296 self.assertRaises(ValueError, lambda: b.remove(400)) 1201 self.assertRaises(ValueError, lambda: b.remove(400))
1297 self.assertRaises(TypeError, lambda: b.remove('e')) 1202 self.assertRaises(TypeError, lambda: b.remove('e'))
1298 # remove first and last 1203 # remove first and last
1299 b.remove(ord('o')) 1204 b.remove(ord('o'))
1300 b.remove(ord('h')) 1205 b.remove(ord('h'))
1301 self.assertEqual(b, b'e') 1206 self.assertEqual(b, b'e')
1302 self.assertRaises(TypeError, lambda: b.remove(b'e')) 1207 self.assertRaises(TypeError, lambda: b.remove(b'e'))
1303 b.remove(Indexable(ord('e'))) 1208 b.remove(Indexable(ord('e')))
1304 self.assertEqual(b, b'') 1209 self.assertEqual(b, b'')
1210
1211 # test values outside of the ascii range: (0, 127)
1212 c = bytearray([126, 127, 128, 129])
1213 c.remove(127)
1214 self.assertEqual(c, bytes([126, 128, 129]))
1215 c.remove(129)
1216 self.assertEqual(c, bytes([126, 128]))
1305 1217
1306 def test_pop(self): 1218 def test_pop(self):
1307 b = bytearray(b'world') 1219 b = bytearray(b'world')
1308 self.assertEqual(b.pop(), ord('d')) 1220 self.assertEqual(b.pop(), ord('d'))
1309 self.assertEqual(b.pop(0), ord('w')) 1221 self.assertEqual(b.pop(0), ord('w'))
1310 self.assertEqual(b.pop(-2), ord('r')) 1222 self.assertEqual(b.pop(-2), ord('r'))
1311 self.assertRaises(IndexError, lambda: b.pop(10)) 1223 self.assertRaises(IndexError, lambda: b.pop(10))
1312 self.assertRaises(IndexError, lambda: bytearray().pop()) 1224 self.assertRaises(IndexError, lambda: bytearray().pop())
1313 # test for issue #6846 1225 # test for issue #6846
1314 self.assertEqual(bytearray(b'\xff').pop(), 0xff) 1226 self.assertEqual(bytearray(b'\xff').pop(), 0xff)
(...skipping 87 matching lines...) Expand 10 before | Expand all | Expand 10 after
1402 def delslice(): 1314 def delslice():
1403 b[1:-1:2] = b"" 1315 b[1:-1:2] = b""
1404 self.assertRaises(BufferError, delslice) 1316 self.assertRaises(BufferError, delslice)
1405 self.assertEqual(b, orig) 1317 self.assertEqual(b, orig)
1406 1318
1407 @test.support.cpython_only 1319 @test.support.cpython_only
1408 def test_obsolete_write_lock(self): 1320 def test_obsolete_write_lock(self):
1409 from _testcapi import getbuffer_with_null_view 1321 from _testcapi import getbuffer_with_null_view
1410 self.assertRaises(BufferError, getbuffer_with_null_view, bytearray()) 1322 self.assertRaises(BufferError, getbuffer_with_null_view, bytearray())
1411 1323
1324 def test_iterator_pickling2(self):
1325 orig = bytearray(b'abc')
1326 data = list(b'qwerty')
1327 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1328 # initial iterator
1329 itorig = iter(orig)
1330 d = pickle.dumps((itorig, orig), proto)
1331 it, b = pickle.loads(d)
1332 b[:] = data
1333 self.assertEqual(type(it), type(itorig))
1334 self.assertEqual(list(it), data)
1335
1336 # running iterator
1337 next(itorig)
1338 d = pickle.dumps((itorig, orig), proto)
1339 it, b = pickle.loads(d)
1340 b[:] = data
1341 self.assertEqual(type(it), type(itorig))
1342 self.assertEqual(list(it), data[1:])
1343
1344 # empty iterator
1345 for i in range(1, len(orig)):
1346 next(itorig)
1347 d = pickle.dumps((itorig, orig), proto)
1348 it, b = pickle.loads(d)
1349 b[:] = data
1350 self.assertEqual(type(it), type(itorig))
1351 self.assertEqual(list(it), data[len(orig):])
1352
1353 # exhausted iterator
1354 self.assertRaises(StopIteration, next, itorig)
1355 d = pickle.dumps((itorig, orig), proto)
1356 it, b = pickle.loads(d)
1357 b[:] = data
1358 self.assertEqual(list(it), [])
1359
1360 test_exhausted_iterator = test.list_tests.CommonTest.test_exhausted_iterator
1361
1362 def test_iterator_length_hint(self):
1363 # Issue 27443: __length_hint__ can return negative integer
1364 ba = bytearray(b'ab')
1365 it = iter(ba)
1366 next(it)
1367 ba.clear()
1368 # Shouldn't raise an error
1369 self.assertEqual(list(it), [])
1370
1371
1412 class AssortedBytesTest(unittest.TestCase): 1372 class AssortedBytesTest(unittest.TestCase):
1413 # 1373 #
1414 # Test various combinations of bytes and bytearray 1374 # Test various combinations of bytes and bytearray
1415 # 1375 #
1416 1376
1417 @check_bytes_warnings 1377 @check_bytes_warnings
1418 def test_repr_str(self): 1378 def test_repr_str(self):
1419 for f in str, repr: 1379 for f in str, repr:
1420 self.assertEqual(f(bytearray()), "bytearray(b'')") 1380 self.assertEqual(f(bytearray()), "bytearray(b'')")
1421 self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')") 1381 self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')")
(...skipping 126 matching lines...) Expand 10 before | Expand all | Expand 10 after
1548 with bytes_warning(): 1508 with bytes_warning():
1549 0 != b'\0' 1509 0 != b'\0'
1550 1510
1551 # Optimizations: 1511 # Optimizations:
1552 # __iter__? (optimization) 1512 # __iter__? (optimization)
1553 # __reversed__? (optimization) 1513 # __reversed__? (optimization)
1554 1514
1555 # XXX More string methods? (Those that don't use character properties) 1515 # XXX More string methods? (Those that don't use character properties)
1556 1516
1557 # There are tests in string_tests.py that are more 1517 # There are tests in string_tests.py that are more
1558 # comprehensive for things like split, partition, etc. 1518 # comprehensive for things like partition, etc.
1559 # Unfortunately they are all bundled with tests that 1519 # Unfortunately they are all bundled with tests that
1560 # are not appropriate for bytes 1520 # are not appropriate for bytes
1561 1521
1562 # I've started porting some of those into bytearray_tests.py, we should port 1522 # I've started porting some of those into bytearray_tests.py, we should port
1563 # the rest that make sense (the code can be cleaned up to use modern 1523 # the rest that make sense (the code can be cleaned up to use modern
1564 # unittest methods at the same time). 1524 # unittest methods at the same time).
1565 1525
1566 class BytearrayPEP3137Test(unittest.TestCase, 1526 class BytearrayPEP3137Test(unittest.TestCase):
1567 test.buffer_tests.MixinBytesBufferCommonTests):
1568 def marshal(self, x): 1527 def marshal(self, x):
1569 return bytearray(x) 1528 return bytearray(x)
1570 1529
1571 def test_returns_new_copy(self): 1530 def test_returns_new_copy(self):
1572 val = self.marshal(b'1234') 1531 val = self.marshal(b'1234')
1573 # On immutable types these MAY return a reference to themselves 1532 # On immutable types these MAY return a reference to themselves
1574 # but on mutable types like bytearray they MUST return a new copy. 1533 # but on mutable types like bytearray they MUST return a new copy.
1575 for methname in ('zfill', 'rjust', 'ljust', 'center'): 1534 for methname in ('zfill', 'rjust', 'ljust', 'center'):
1576 method = getattr(val, methname) 1535 method = getattr(val, methname)
1577 newval = method(3) 1536 newval = method(3)
1578 self.assertEqual(val, newval) 1537 self.assertEqual(val, newval)
1579 self.assertTrue(val is not newval, 1538 self.assertTrue(val is not newval,
1580 methname+' returned self on a mutable object') 1539 methname+' returned self on a mutable object')
1581 for expr in ('val.split()[0]', 'val.rsplit()[0]', 1540 for expr in ('val.split()[0]', 'val.rsplit()[0]',
1582 'val.partition(b".")[0]', 'val.rpartition(b".")[2]', 1541 'val.partition(b".")[0]', 'val.rpartition(b".")[2]',
1583 'val.splitlines()[0]', 'val.replace(b"", b"")'): 1542 'val.splitlines()[0]', 'val.replace(b"", b"")'):
1584 newval = eval(expr) 1543 newval = eval(expr)
1585 self.assertEqual(val, newval) 1544 self.assertEqual(val, newval)
1586 self.assertTrue(val is not newval, 1545 self.assertTrue(val is not newval,
1587 expr+' returned val on a mutable object') 1546 expr+' returned val on a mutable object')
1588 sep = self.marshal(b'') 1547 sep = self.marshal(b'')
1589 newval = sep.join([val]) 1548 newval = sep.join([val])
1590 self.assertEqual(val, newval) 1549 self.assertEqual(val, newval)
1591 self.assertIsNot(val, newval) 1550 self.assertIsNot(val, newval)
1592 1551
1593 1552
1594 class FixedStringTest(test.string_tests.BaseTest): 1553 class FixedStringTest(test.string_tests.BaseTest):
1595
1596 def fixtype(self, obj): 1554 def fixtype(self, obj):
1597 if isinstance(obj, str): 1555 if isinstance(obj, str):
1598 return obj.encode("utf-8") 1556 return self.type2test(obj.encode("utf-8"))
1599 return super().fixtype(obj) 1557 return super().fixtype(obj)
1600 1558
1601 # Currently the bytes containment testing uses a single integer 1559 contains_bytes = True
1602 # value. This may not be the final design, but until then the
1603 # bytes section with in a bytes containment not valid
1604 def test_contains(self):
1605 pass
1606 def test_expandtabs(self):
1607 pass
1608 def test_upper(self):
1609 pass
1610 def test_lower(self):
1611 pass
1612 1560
1613 class ByteArrayAsStringTest(FixedStringTest, unittest.TestCase): 1561 class ByteArrayAsStringTest(FixedStringTest, unittest.TestCase):
1614 type2test = bytearray 1562 type2test = bytearray
1615 contains_bytes = True
1616 1563
1617 class BytesAsStringTest(FixedStringTest, unittest.TestCase): 1564 class BytesAsStringTest(FixedStringTest, unittest.TestCase):
1618 type2test = bytes 1565 type2test = bytes
1619 contains_bytes = True
1620 1566
1621 1567
1622 class SubclassTest: 1568 class SubclassTest:
1623 1569
1624 def test_basic(self): 1570 def test_basic(self):
1625 self.assertTrue(issubclass(self.subclass2test, self.type2test)) 1571 self.assertTrue(issubclass(self.type2test, self.basetype))
1626 self.assertIsInstance(self.subclass2test(), self.type2test) 1572 self.assertIsInstance(self.type2test(), self.basetype)
1627 1573
1628 a, b = b"abcd", b"efgh" 1574 a, b = b"abcd", b"efgh"
1629 _a, _b = self.subclass2test(a), self.subclass2test(b) 1575 _a, _b = self.type2test(a), self.type2test(b)
1630 1576
1631 # test comparison operators with subclass instances 1577 # test comparison operators with subclass instances
1632 self.assertTrue(_a == _a) 1578 self.assertTrue(_a == _a)
1633 self.assertTrue(_a != _b) 1579 self.assertTrue(_a != _b)
1634 self.assertTrue(_a < _b) 1580 self.assertTrue(_a < _b)
1635 self.assertTrue(_a <= _b) 1581 self.assertTrue(_a <= _b)
1636 self.assertTrue(_b >= _a) 1582 self.assertTrue(_b >= _a)
1637 self.assertTrue(_b > _a) 1583 self.assertTrue(_b > _a)
1638 self.assertTrue(_a is not a) 1584 self.assertTrue(_a is not a)
1639 1585
1640 # test concat of subclass instances 1586 # test concat of subclass instances
1641 self.assertEqual(a + b, _a + _b) 1587 self.assertEqual(a + b, _a + _b)
1642 self.assertEqual(a + b, a + _b) 1588 self.assertEqual(a + b, a + _b)
1643 self.assertEqual(a + b, _a + b) 1589 self.assertEqual(a + b, _a + b)
1644 1590
1645 # test repeat 1591 # test repeat
1646 self.assertTrue(a*5 == _a*5) 1592 self.assertTrue(a*5 == _a*5)
1647 1593
1648 def test_join(self): 1594 def test_join(self):
1649 # Make sure join returns a NEW object for single item sequences 1595 # Make sure join returns a NEW object for single item sequences
1650 # involving a subclass. 1596 # involving a subclass.
1651 # Make sure that it is of the appropriate type. 1597 # Make sure that it is of the appropriate type.
1652 s1 = self.subclass2test(b"abcd") 1598 s1 = self.type2test(b"abcd")
1653 s2 = self.type2test().join([s1]) 1599 s2 = self.basetype().join([s1])
1654 self.assertTrue(s1 is not s2) 1600 self.assertTrue(s1 is not s2)
1655 self.assertTrue(type(s2) is self.type2test, type(s2)) 1601 self.assertTrue(type(s2) is self.basetype, type(s2))
1656 1602
1657 # Test reverse, calling join on subclass 1603 # Test reverse, calling join on subclass
1658 s3 = s1.join([b"abcd"]) 1604 s3 = s1.join([b"abcd"])
1659 self.assertTrue(type(s3) is self.type2test) 1605 self.assertTrue(type(s3) is self.basetype)
1660 1606
1661 def test_pickle(self): 1607 def test_pickle(self):
1662 a = self.subclass2test(b"abcd") 1608 a = self.type2test(b"abcd")
1663 a.x = 10 1609 a.x = 10
1664 a.y = self.subclass2test(b"efgh") 1610 a.y = self.type2test(b"efgh")
1665 for proto in range(pickle.HIGHEST_PROTOCOL + 1): 1611 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1666 b = pickle.loads(pickle.dumps(a, proto)) 1612 b = pickle.loads(pickle.dumps(a, proto))
1667 self.assertNotEqual(id(a), id(b)) 1613 self.assertNotEqual(id(a), id(b))
1668 self.assertEqual(a, b) 1614 self.assertEqual(a, b)
1669 self.assertEqual(a.x, b.x) 1615 self.assertEqual(a.x, b.x)
1670 self.assertEqual(a.y, b.y) 1616 self.assertEqual(a.y, b.y)
1671 self.assertEqual(type(a), type(b)) 1617 self.assertEqual(type(a), type(b))
1672 self.assertEqual(type(a.y), type(b.y)) 1618 self.assertEqual(type(a.y), type(b.y))
1673 1619
1674 def test_copy(self): 1620 def test_copy(self):
1675 a = self.subclass2test(b"abcd") 1621 a = self.type2test(b"abcd")
1676 a.x = 10 1622 a.x = 10
1677 a.y = self.subclass2test(b"efgh") 1623 a.y = self.type2test(b"efgh")
1678 for copy_method in (copy.copy, copy.deepcopy): 1624 for copy_method in (copy.copy, copy.deepcopy):
1679 b = copy_method(a) 1625 b = copy_method(a)
1680 self.assertNotEqual(id(a), id(b)) 1626 self.assertNotEqual(id(a), id(b))
1681 self.assertEqual(a, b) 1627 self.assertEqual(a, b)
1682 self.assertEqual(a.x, b.x) 1628 self.assertEqual(a.x, b.x)
1683 self.assertEqual(a.y, b.y) 1629 self.assertEqual(a.y, b.y)
1684 self.assertEqual(type(a), type(b)) 1630 self.assertEqual(type(a), type(b))
1685 self.assertEqual(type(a.y), type(b.y)) 1631 self.assertEqual(type(a.y), type(b.y))
1686 1632
1633 def test_fromhex(self):
1634 b = self.type2test.fromhex('1a2B30')
1635 self.assertEqual(b, b'\x1a\x2b\x30')
1636 self.assertIs(type(b), self.type2test)
1637
1638 class B1(self.basetype):
1639 def __new__(cls, value):
1640 me = self.basetype.__new__(cls, value)
1641 me.foo = 'bar'
1642 return me
1643
1644 b = B1.fromhex('1a2B30')
1645 self.assertEqual(b, b'\x1a\x2b\x30')
1646 self.assertIs(type(b), B1)
1647 self.assertEqual(b.foo, 'bar')
1648
1649 class B2(self.basetype):
1650 def __init__(me, *args, **kwargs):
1651 if self.basetype is not bytes:
1652 self.basetype.__init__(me, *args, **kwargs)
1653 me.foo = 'bar'
1654
1655 b = B2.fromhex('1a2B30')
1656 self.assertEqual(b, b'\x1a\x2b\x30')
1657 self.assertIs(type(b), B2)
1658 self.assertEqual(b.foo, 'bar')
1659
1687 1660
1688 class ByteArraySubclass(bytearray): 1661 class ByteArraySubclass(bytearray):
1689 pass 1662 pass
1690 1663
1691 class BytesSubclass(bytes): 1664 class BytesSubclass(bytes):
1692 pass 1665 pass
1693 1666
1694 class OtherBytesSubclass(bytes): 1667 class OtherBytesSubclass(bytes):
1695 pass 1668 pass
1696 1669
1697 class ByteArraySubclassTest(SubclassTest, unittest.TestCase): 1670 class ByteArraySubclassTest(SubclassTest, unittest.TestCase):
1698 type2test = bytearray 1671 basetype = bytearray
1699 subclass2test = ByteArraySubclass 1672 type2test = ByteArraySubclass
1700 1673
1701 def test_init_override(self): 1674 def test_init_override(self):
1702 class subclass(bytearray): 1675 class subclass(bytearray):
1703 def __init__(me, newarg=1, *args, **kwargs): 1676 def __init__(me, newarg=1, *args, **kwargs):
1704 bytearray.__init__(me, *args, **kwargs) 1677 bytearray.__init__(me, *args, **kwargs)
1705 x = subclass(4, b"abcd") 1678 x = subclass(4, b"abcd")
1706 x = subclass(4, source=b"abcd") 1679 x = subclass(4, source=b"abcd")
1707 self.assertEqual(x, b"abcd") 1680 self.assertEqual(x, b"abcd")
1708 x = subclass(newarg=4, source=b"abcd") 1681 x = subclass(newarg=4, source=b"abcd")
1709 self.assertEqual(x, b"abcd") 1682 self.assertEqual(x, b"abcd")
1710 1683
1711 1684
1712 class BytesSubclassTest(SubclassTest, unittest.TestCase): 1685 class BytesSubclassTest(SubclassTest, unittest.TestCase):
1713 type2test = bytes 1686 basetype = bytes
1714 subclass2test = BytesSubclass 1687 type2test = BytesSubclass
1715 1688
1716 1689
1717 if __name__ == "__main__": 1690 if __name__ == "__main__":
1718 unittest.main() 1691 unittest.main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+