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

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, 3 months ago
Right Patch Set: Created 3 years, 7 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 10 matching lines...) Expand all
293 b = bytearray([0x1a, 0x2b, 0x30]) 293 b = bytearray([0x1a, 0x2b, 0x30])
294 self.assertEqual(self.type2test.fromhex('1a2B30'), b) 294 self.assertEqual(self.type2test.fromhex('1a2B30'), b)
295 self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b) 295 self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b)
296 self.assertEqual(self.type2test.fromhex('0000'), b'\0\0') 296 self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
297 self.assertRaises(TypeError, self.type2test.fromhex, b'1B') 297 self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
298 self.assertRaises(ValueError, self.type2test.fromhex, 'a') 298 self.assertRaises(ValueError, self.type2test.fromhex, 'a')
299 self.assertRaises(ValueError, self.type2test.fromhex, 'rt') 299 self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
300 self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd') 300 self.assertRaises(ValueError, self.type2test.fromhex, '1a b cd')
301 self.assertRaises(ValueError, self.type2test.fromhex, '\x00') 301 self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
302 self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34') 302 self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')
303
304 for data, pos in (
305 # invalid first hexadecimal character
306 ('12 x4 56', 3),
307 # invalid second hexadecimal character
308 ('12 3x 56', 4),
309 # two invalid hexadecimal characters
310 ('12 xy 56', 3),
311 # test non-ASCII string
312 ('12 3\xff 56', 4),
313 ):
314 with self.assertRaises(ValueError) as cm:
315 self.type2test.fromhex(data)
316 self.assertIn('at position %s' % pos, str(cm.exception))
303 317
304 def test_hex(self): 318 def test_hex(self):
305 self.assertRaises(TypeError, self.type2test.hex) 319 self.assertRaises(TypeError, self.type2test.hex)
306 self.assertRaises(TypeError, self.type2test.hex, 1) 320 self.assertRaises(TypeError, self.type2test.hex, 1)
307 self.assertEqual(self.type2test(b"").hex(), "") 321 self.assertEqual(self.type2test(b"").hex(), "")
308 self.assertEqual(bytearray([0x1a, 0x2b, 0x30]).hex(), '1a2b30') 322 self.assertEqual(bytearray([0x1a, 0x2b, 0x30]).hex(), '1a2b30')
309 self.assertEqual(self.type2test(b"\x1a\x2b\x30").hex(), '1a2b30') 323 self.assertEqual(self.type2test(b"\x1a\x2b\x30").hex(), '1a2b30')
310 self.assertEqual(memoryview(b"\x1a\x2b\x30").hex(), '1a2b30') 324 self.assertEqual(memoryview(b"\x1a\x2b\x30").hex(), '1a2b30')
311 325
312 def test_join(self): 326 def test_join(self):
(...skipping 150 matching lines...) Expand 10 before | Expand all | Expand 10 after
463 self.assertRaises(ValueError, b.rindex, w) 477 self.assertRaises(ValueError, b.rindex, w)
464 478
465 self.assertEqual(b.rindex(b'ss', 3), 5) 479 self.assertEqual(b.rindex(b'ss', 3), 5)
466 self.assertEqual(b.rindex(b'ss', 0, 6), 2) 480 self.assertEqual(b.rindex(b'ss', 0, 6), 2)
467 481
468 self.assertEqual(b.rindex(i, 1, 3), 1) 482 self.assertEqual(b.rindex(i, 1, 3), 1)
469 self.assertEqual(b.rindex(i, 3, 9), 7) 483 self.assertEqual(b.rindex(i, 3, 9), 7)
470 self.assertRaises(ValueError, b.rindex, w, 1, 3) 484 self.assertRaises(ValueError, b.rindex, w, 1, 3)
471 485
472 def test_mod(self): 486 def test_mod(self):
473 b = b'hello, %b!' 487 b = self.type2test(b'hello, %b!')
474 orig = b 488 orig = b
475 b = b % b'world' 489 b = b % b'world'
476 self.assertEqual(b, b'hello, world!') 490 self.assertEqual(b, b'hello, world!')
477 self.assertEqual(orig, b'hello, %b!') 491 self.assertEqual(orig, b'hello, %b!')
478 self.assertFalse(b is orig) 492 self.assertFalse(b is orig)
479 b = b'%s / 100 = %d%%' 493 b = self.type2test(b'%s / 100 = %d%%')
480 a = b % (b'seventy-nine', 79) 494 a = b % (b'seventy-nine', 79)
481 self.assertEqual(a, b'seventy-nine / 100 = 79%') 495 self.assertEqual(a, b'seventy-nine / 100 = 79%')
496 self.assertIs(type(a), self.type2test)
482 497
483 def test_imod(self): 498 def test_imod(self):
484 b = b'hello, %b!' 499 b = self.type2test(b'hello, %b!')
485 orig = b 500 orig = b
486 b %= b'world' 501 b %= b'world'
487 self.assertEqual(b, b'hello, world!') 502 self.assertEqual(b, b'hello, world!')
488 self.assertEqual(orig, b'hello, %b!') 503 self.assertEqual(orig, b'hello, %b!')
489 self.assertFalse(b is orig) 504 self.assertFalse(b is orig)
490 b = b'%s / 100 = %d%%' 505 b = self.type2test(b'%s / 100 = %d%%')
491 b %= (b'seventy-nine', 79) 506 b %= (b'seventy-nine', 79)
492 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)
493 514
494 def test_replace(self): 515 def test_replace(self):
495 b = self.type2test(b'mississippi') 516 b = self.type2test(b'mississippi')
496 self.assertEqual(b.replace(b'i', b'a'), b'massassappa') 517 self.assertEqual(b.replace(b'i', b'a'), b'massassappa')
497 self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi') 518 self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi')
498 519
499 def test_split(self): 520 def test_split_string_error(self):
500 b = self.type2test(b'mississippi') 521 self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
501 self.assertEqual(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b'']) 522
502 self.assertEqual(b.split(b'ss'), [b'mi', b'i', b'ippi']) 523 def test_split_unicodewhitespace(self):
503 self.assertEqual(b.split(b'w'), [b])
504 # with keyword args
505 b = self.type2test(b'a|b|c|d')
506 self.assertEqual(b.split(sep=b'|'), [b'a', b'b', b'c', b'd'])
507 self.assertEqual(b.split(b'|', maxsplit=1), [b'a', b'b|c|d'])
508 self.assertEqual(b.split(sep=b'|', maxsplit=1), [b'a', b'b|c|d'])
509 self.assertEqual(b.split(maxsplit=1, sep=b'|'), [b'a', b'b|c|d'])
510 b = self.type2test(b'a b c d')
511 self.assertEqual(b.split(maxsplit=1), [b'a', b'b c d'])
512
513 def test_split_whitespace(self):
514 for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
515 b'arf\fbarf', b'arf\vbarf'):
516 b = self.type2test(b)
517 self.assertEqual(b.split(), [b'arf', b'barf'])
518 self.assertEqual(b.split(None), [b'arf', b'barf'])
519 self.assertEqual(b.split(None, 2), [b'arf', b'barf'])
520 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'):
521 b = self.type2test(b) 525 b = self.type2test(b)
522 self.assertEqual(b.split(), [b]) 526 self.assertEqual(b.split(), [b])
523 self.assertEqual(self.type2test(b' a bb c ').split(None, 0), [b'a b b c '])
524 self.assertEqual(self.type2test(b' a bb c ').split(None, 1), [b'a', b'bb c '])
525 self.assertEqual(self.type2test(b' a bb c ').split(None, 2), [b'a', b'bb', b'c '])
526 self.assertEqual(self.type2test(b' a bb c ').split(None, 3), [b'a', b'bb', b'c'])
527
528 def test_split_string_error(self):
529 self.assertRaises(TypeError, self.type2test(b'a b').split, ' ')
530
531 def test_split_unicodewhitespace(self):
532 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")
533 self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f']) 528 self.assertEqual(b.split(), [b'\x1c\x1d\x1e\x1f'])
534
535 def test_rsplit(self):
536 b = self.type2test(b'mississippi')
537 self.assertEqual(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b''])
538 self.assertEqual(b.rsplit(b'ss'), [b'mi', b'i', b'ippi'])
539 self.assertEqual(b.rsplit(b'w'), [b])
540 # with keyword args
541 b = self.type2test(b'a|b|c|d')
542 self.assertEqual(b.rsplit(sep=b'|'), [b'a', b'b', b'c', b'd'])
543 self.assertEqual(b.rsplit(b'|', maxsplit=1), [b'a|b|c', b'd'])
544 self.assertEqual(b.rsplit(sep=b'|', maxsplit=1), [b'a|b|c', b'd'])
545 self.assertEqual(b.rsplit(maxsplit=1, sep=b'|'), [b'a|b|c', b'd'])
546 b = self.type2test(b'a b c d')
547 self.assertEqual(b.rsplit(maxsplit=1), [b'a b c', b'd'])
548
549 def test_rsplit_whitespace(self):
550 for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf',
551 b'arf\fbarf', b'arf\vbarf'):
552 b = self.type2test(b)
553 self.assertEqual(b.rsplit(), [b'arf', b'barf'])
554 self.assertEqual(b.rsplit(None), [b'arf', b'barf'])
555 self.assertEqual(b.rsplit(None, 2), [b'arf', b'barf'])
556 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 0), [b' a bb c'])
557 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 1), [b' a bb', b'c'])
558 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 2), [b' a ', b'bb', b'c'])
559 self.assertEqual(self.type2test(b' a bb c ').rsplit(None, 3), [b'a', b'bb', b'c'])
560 529
561 def test_rsplit_string_error(self): 530 def test_rsplit_string_error(self):
562 self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ') 531 self.assertRaises(TypeError, self.type2test(b'a b').rsplit, ' ')
563 532
564 def test_rsplit_unicodewhitespace(self): 533 def test_rsplit_unicodewhitespace(self):
565 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")
566 self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f']) 535 self.assertEqual(b.rsplit(), [b'\x1c\x1d\x1e\x1f'])
567 536
568 def test_partition(self): 537 def test_partition(self):
569 b = self.type2test(b'mississippi') 538 b = self.type2test(b'mississippi')
(...skipping 18 matching lines...) Expand all
588 for proto in range(pickle.HIGHEST_PROTOCOL + 1): 557 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
589 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":
590 it = itorg = iter(self.type2test(b)) 559 it = itorg = iter(self.type2test(b))
591 data = list(self.type2test(b)) 560 data = list(self.type2test(b))
592 d = pickle.dumps(it, proto) 561 d = pickle.dumps(it, proto)
593 it = pickle.loads(d) 562 it = pickle.loads(d)
594 self.assertEqual(type(itorg), type(it)) 563 self.assertEqual(type(itorg), type(it))
595 self.assertEqual(list(it), data) 564 self.assertEqual(list(it), data)
596 565
597 it = pickle.loads(d) 566 it = pickle.loads(d)
598 try: 567 if not b:
599 next(it)
600 except StopIteration:
601 continue 568 continue
569 next(it)
602 d = pickle.dumps(it, proto) 570 d = pickle.dumps(it, proto)
603 it = pickle.loads(d) 571 it = pickle.loads(d)
604 self.assertEqual(list(it), data[1:]) 572 self.assertEqual(list(it), data[1:])
605
606 def test_strip(self):
607 b = self.type2test(b'mississippi')
608 self.assertEqual(b.strip(b'i'), b'mississipp')
609 self.assertEqual(b.strip(b'm'), b'ississippi')
610 self.assertEqual(b.strip(b'pi'), b'mississ')
611 self.assertEqual(b.strip(b'im'), b'ssissipp')
612 self.assertEqual(b.strip(b'pim'), b'ssiss')
613 self.assertEqual(b.strip(b), b'')
614
615 def test_lstrip(self):
616 b = self.type2test(b'mississippi')
617 self.assertEqual(b.lstrip(b'i'), b'mississippi')
618 self.assertEqual(b.lstrip(b'm'), b'ississippi')
619 self.assertEqual(b.lstrip(b'pi'), b'mississippi')
620 self.assertEqual(b.lstrip(b'im'), b'ssissippi')
621 self.assertEqual(b.lstrip(b'pim'), b'ssissippi')
622
623 def test_rstrip(self):
624 b = self.type2test(b'mississippi')
625 self.assertEqual(b.rstrip(b'i'), b'mississipp')
626 self.assertEqual(b.rstrip(b'm'), b'mississippi')
627 self.assertEqual(b.rstrip(b'pi'), b'mississ')
628 self.assertEqual(b.rstrip(b'im'), b'mississipp')
629 self.assertEqual(b.rstrip(b'pim'), b'mississ')
630
631 def test_strip_whitespace(self):
632 b = self.type2test(b' \t\n\r\f\vabc \t\n\r\f\v')
633 self.assertEqual(b.strip(), b'abc')
634 self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v')
635 self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc')
636 573
637 def test_strip_bytearray(self): 574 def test_strip_bytearray(self):
638 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')
639 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' )
640 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' )
641 578
642 def test_strip_string_error(self): 579 def test_strip_string_error(self):
643 self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b') 580 self.assertRaises(TypeError, self.type2test(b'abc').strip, 'b')
644 self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b') 581 self.assertRaises(TypeError, self.type2test(b'abc').lstrip, 'b')
645 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
740 self.assertRaisesRegex(TypeError, r'\bindex\b', b.index, 677 self.assertRaisesRegex(TypeError, r'\bindex\b', b.index,
741 x, None, None, None) 678 x, None, None, None)
742 self.assertRaisesRegex(TypeError, r'\brindex\b', b.rindex, 679 self.assertRaisesRegex(TypeError, r'\brindex\b', b.rindex,
743 x, None, None, None) 680 x, None, None, None)
744 self.assertRaisesRegex(TypeError, r'\bcount\b', b.count, 681 self.assertRaisesRegex(TypeError, r'\bcount\b', b.count,
745 x, None, None, None) 682 x, None, None, None)
746 self.assertRaisesRegex(TypeError, r'\bstartswith\b', b.startswith, 683 self.assertRaisesRegex(TypeError, r'\bstartswith\b', b.startswith,
747 x, None, None, None) 684 x, None, None, None)
748 self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith, 685 self.assertRaisesRegex(TypeError, r'\bendswith\b', b.endswith,
749 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)
750 691
751 692
752 class BytesTest(BaseBytesTest, unittest.TestCase): 693 class BytesTest(BaseBytesTest, unittest.TestCase):
753 type2test = bytes 694 type2test = bytes
754 695
755 def test_getitem_error(self): 696 def test_getitem_error(self):
756 msg = "byte indices must be integers or slices" 697 msg = "byte indices must be integers or slices"
757 with self.assertRaisesRegex(TypeError, msg): 698 with self.assertRaisesRegex(TypeError, msg):
758 b'python'['a'] 699 b'python'['a']
759 700
(...skipping 29 matching lines...) Expand all
789 class A: 730 class A:
790 def __bytes__(self): 731 def __bytes__(self):
791 return OtherBytesSubclass(b'abc') 732 return OtherBytesSubclass(b'abc')
792 self.assertEqual(bytes(A()), b'abc') 733 self.assertEqual(bytes(A()), b'abc')
793 self.assertIs(type(bytes(A())), OtherBytesSubclass) 734 self.assertIs(type(bytes(A())), OtherBytesSubclass)
794 self.assertEqual(BytesSubclass(A()), b'abc') 735 self.assertEqual(BytesSubclass(A()), b'abc')
795 self.assertIs(type(BytesSubclass(A())), BytesSubclass) 736 self.assertIs(type(BytesSubclass(A())), BytesSubclass)
796 737
797 # Test PyBytes_FromFormat() 738 # Test PyBytes_FromFormat()
798 def test_from_format(self): 739 def test_from_format(self):
799 test.support.import_module('ctypes') 740 ctypes = test.support.import_module('ctypes')
800 from ctypes import pythonapi, py_object, c_int, c_char_p 741 _testcapi = test.support.import_module('_testcapi')
742 from ctypes import pythonapi, py_object
743 from ctypes import (
744 c_int, c_uint,
745 c_long, c_ulong,
746 c_size_t, c_ssize_t,
747 c_char_p)
748
801 PyBytes_FromFormat = pythonapi.PyBytes_FromFormat 749 PyBytes_FromFormat = pythonapi.PyBytes_FromFormat
802 PyBytes_FromFormat.restype = py_object 750 PyBytes_FromFormat.restype = py_object
803 751
752 # basic tests
804 self.assertEqual(PyBytes_FromFormat(b'format'), 753 self.assertEqual(PyBytes_FromFormat(b'format'),
805 b'format') 754 b'format')
806 755 self.assertEqual(PyBytes_FromFormat(b'Hello %s !', b'world'),
756 b'Hello world !')
757
758 # test formatters
759 self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(0)),
760 b'c=\0')
761 self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(ord('@'))),
762 b'c=@')
763 self.assertEqual(PyBytes_FromFormat(b'c=%c', c_int(255)),
764 b'c=\xff')
765 self.assertEqual(PyBytes_FromFormat(b'd=%d ld=%ld zd=%zd',
766 c_int(1), c_long(2),
767 c_size_t(3)),
768 b'd=1 ld=2 zd=3')
769 self.assertEqual(PyBytes_FromFormat(b'd=%d ld=%ld zd=%zd',
770 c_int(-1), c_long(-2),
771 c_size_t(-3)),
772 b'd=-1 ld=-2 zd=-3')
773 self.assertEqual(PyBytes_FromFormat(b'u=%u lu=%lu zu=%zu',
774 c_uint(123), c_ulong(456),
775 c_size_t(789)),
776 b'u=123 lu=456 zu=789')
777 self.assertEqual(PyBytes_FromFormat(b'i=%i', c_int(123)),
778 b'i=123')
779 self.assertEqual(PyBytes_FromFormat(b'i=%i', c_int(-123)),
780 b'i=-123')
781 self.assertEqual(PyBytes_FromFormat(b'x=%x', c_int(0xabc)),
782 b'x=abc')
783
784 sizeof_ptr = ctypes.sizeof(c_char_p)
785
786 if os.name == 'nt':
787 # Windows (MSCRT)
788 ptr_format = '0x%0{}X'.format(2 * sizeof_ptr)
789 def ptr_formatter(ptr):
790 return (ptr_format % ptr)
791 else:
792 # UNIX (glibc)
793 def ptr_formatter(ptr):
794 return '%#x' % ptr
795
796 ptr = 0xabcdef
797 self.assertEqual(PyBytes_FromFormat(b'ptr=%p', c_char_p(ptr)),
798 ('ptr=' + ptr_formatter(ptr)).encode('ascii'))
799 self.assertEqual(PyBytes_FromFormat(b's=%s', c_char_p(b'cstr')),
800 b's=cstr')
801
802 # test minimum and maximum integer values
803 size_max = c_size_t(-1).value
804 for formatstr, ctypes_type, value, py_formatter in (
805 (b'%d', c_int, _testcapi.INT_MIN, str),
806 (b'%d', c_int, _testcapi.INT_MAX, str),
807 (b'%ld', c_long, _testcapi.LONG_MIN, str),
808 (b'%ld', c_long, _testcapi.LONG_MAX, str),
809 (b'%lu', c_ulong, _testcapi.ULONG_MAX, str),
810 (b'%zd', c_ssize_t, _testcapi.PY_SSIZE_T_MIN, str),
811 (b'%zd', c_ssize_t, _testcapi.PY_SSIZE_T_MAX, str),
812 (b'%zu', c_size_t, size_max, str),
813 (b'%p', c_char_p, size_max, ptr_formatter),
814 ):
815 self.assertEqual(PyBytes_FromFormat(formatstr, ctypes_type(value)),
816 py_formatter(value).encode('ascii')),
817
818 # width and precision (width is currently ignored)
819 self.assertEqual(PyBytes_FromFormat(b'%5s', b'a'),
820 b'a')
821 self.assertEqual(PyBytes_FromFormat(b'%.3s', b'abcdef'),
822 b'abc')
823
824 # '%%' formatter
825 self.assertEqual(PyBytes_FromFormat(b'%%'),
826 b'%')
827 self.assertEqual(PyBytes_FromFormat(b'[%%]'),
828 b'[%]')
829 self.assertEqual(PyBytes_FromFormat(b'%%%c', c_int(ord('_'))),
830 b'%_')
831 self.assertEqual(PyBytes_FromFormat(b'%%s'),
832 b'%s')
833
834 # Invalid formats and partial formatting
807 self.assertEqual(PyBytes_FromFormat(b'%'), b'%') 835 self.assertEqual(PyBytes_FromFormat(b'%'), b'%')
808 self.assertEqual(PyBytes_FromFormat(b'%%'), b'%') 836 self.assertEqual(PyBytes_FromFormat(b'x=%i y=%', c_int(2), c_int(3)),
809 self.assertEqual(PyBytes_FromFormat(b'%%s'), b'%s') 837 b'x=2 y=%')
810 self.assertEqual(PyBytes_FromFormat(b'[%%]'), b'[%]') 838
811 self.assertEqual(PyBytes_FromFormat(b'%%%c', c_int(ord('_'))), b'%_') 839 # Issue #19969: %c must raise OverflowError for values
812 840 # not in the range [0; 255]
813 self.assertEqual(PyBytes_FromFormat(b'c:%c', c_int(255)),
814 b'c:\xff')
815 self.assertEqual(PyBytes_FromFormat(b's:%s', c_char_p(b'cstr')),
816 b's:cstr')
817
818 # Issue #19969
819 self.assertRaises(OverflowError, 841 self.assertRaises(OverflowError,
820 PyBytes_FromFormat, b'%c', c_int(-1)) 842 PyBytes_FromFormat, b'%c', c_int(-1))
821 self.assertRaises(OverflowError, 843 self.assertRaises(OverflowError,
822 PyBytes_FromFormat, b'%c', c_int(256)) 844 PyBytes_FromFormat, b'%c', c_int(256))
823 845
824
825 def test_bytes_blocking(self): 846 def test_bytes_blocking(self):
826 class Seq: 847 class IterationBlocked(list):
storchaka 2016/01/06 21:55:31 Why not use just list?
abarnert 2016/01/06 23:04:32 Good point. There's no direct fallback from __byte
827 def __getitem__(self, i):
828 if 0 <= i < 4:
829 return i
830 raise IndexError
831 class SeqBlocked(Seq):
832 __bytes__ = None 848 __bytes__ = None
833 s, sb = Seq(), SeqBlocked() 849 i = [0, 1, 2, 3]
834 self.assertEqual(bytes(s), b'\x00\x01\x02\x03') 850 self.assertEqual(bytes(i), b'\x00\x01\x02\x03')
835 self.assertRaises(TypeError, bytes, sb) 851 self.assertRaises(TypeError, bytes, IterationBlocked(i))
852
853 # At least in CPython, because bytes.__new__ and the C API
854 # PyBytes_FromObject have different fallback rules, integer
855 # fallback is handled specially, so test separately.
856 class IntBlocked(int):
857 __bytes__ = None
858 self.assertEqual(bytes(3), b'\0\0\0')
859 self.assertRaises(TypeError, bytes, IntBlocked(3))
836 860
837 class BytesSubclass(bytes): 861 # While there is no separately-defined rule for handling bytes
838 pass 862 # subclasses differently from other buffer-interface classes,
839 class BytesSubclassBlocked(BytesSubclass): 863 # an implementation may well special-case them (as CPython 2.x
storchaka 2016/01/06 21:55:31 Is it needed to inherit from bytes subclass, not j
abarnert 2016/01/06 23:04:32 Yeah, we don't need to test that bytes(BytesSubcla
abarnert 2016/01/07 21:57:37 Looking over the source code a bit more... I think
864 # str did), so test them separately.
865 class BytesSubclassBlocked(bytes):
840 __bytes__ = None 866 __bytes__ = None
841 bs, bsb = BytesSubclass(b'ab'), BytesSubclassBlocked(b'ab') 867 self.assertEqual(bytes(b'ab'), b'ab')
842 self.assertEqual(bytes(bs), b'ab') 868 self.assertRaises(TypeError, bytes, BytesSubclassBlocked(b'ab'))
843 self.assertRaises(TypeError, bytes, bsb) 869
844 870 class BufferBlocked(bytearray):
845 class BytesLikeSubclass(bytearray):
846 pass
847 class BytesLikeSubclassBlocked(BytesLikeSubclass):
848 __bytes__ = None 871 __bytes__ = None
849 bls, blsb = BytesLikeSubclass(b'ab'), BytesLikeSubclassBlocked(b'ab') 872 ba, bb = bytearray(b'ab'), BufferBlocked(b'ab')
850 self.assertEqual(bytes(bls), b'ab') 873 self.assertEqual(bytes(ba), b'ab')
851 self.assertRaises(TypeError, bytes, blsb) 874 self.assertRaises(TypeError, bytes, bb)
875
852 876
853 class ByteArrayTest(BaseBytesTest, unittest.TestCase): 877 class ByteArrayTest(BaseBytesTest, unittest.TestCase):
854 type2test = bytearray 878 type2test = bytearray
855 879
856 def test_getitem_error(self): 880 def test_getitem_error(self):
857 msg = "bytearray indices must be integers or slices" 881 msg = "bytearray indices must be integers or slices"
858 with self.assertRaisesRegex(TypeError, msg): 882 with self.assertRaisesRegex(TypeError, msg):
859 bytearray(b'python')['a'] 883 bytearray(b'python')['a']
860 884
861 def test_setitem_error(self): 885 def test_setitem_error(self):
(...skipping 209 matching lines...) Expand 10 before | Expand all | Expand 10 after
1071 del b[start:stop:step] 1095 del b[start:stop:step]
1072 self.assertEqual(b, bytearray(L)) 1096 self.assertEqual(b, bytearray(L))
1073 1097
1074 def test_setslice_trap(self): 1098 def test_setslice_trap(self):
1075 # This test verifies that we correctly handle assigning self 1099 # This test verifies that we correctly handle assigning self
1076 # to a slice of self (the old Lambert Meertens trap). 1100 # to a slice of self (the old Lambert Meertens trap).
1077 b = bytearray(range(256)) 1101 b = bytearray(range(256))
1078 b[8:] = b 1102 b[8:] = b
1079 self.assertEqual(b, bytearray(list(range(8)) + list(range(256)))) 1103 self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
1080 1104
1081 def test_mod(self):
1082 b = bytearray(b'hello, %b!')
1083 orig = b
1084 b = b % b'world'
1085 self.assertEqual(b, b'hello, world!')
1086 self.assertEqual(orig, bytearray(b'hello, %b!'))
1087 self.assertFalse(b is orig)
1088 b = bytearray(b'%s / 100 = %d%%')
1089 a = b % (b'seventy-nine', 79)
1090 self.assertEqual(a, bytearray(b'seventy-nine / 100 = 79%'))
1091
1092 def test_imod(self):
1093 b = bytearray(b'hello, %b!')
1094 orig = b
1095 b %= b'world'
1096 self.assertEqual(b, b'hello, world!')
1097 self.assertEqual(orig, bytearray(b'hello, %b!'))
1098 self.assertFalse(b is orig)
1099 b = bytearray(b'%s / 100 = %d%%')
1100 b %= (b'seventy-nine', 79)
1101 self.assertEqual(b, bytearray(b'seventy-nine / 100 = 79%'))
1102
1103 def test_iconcat(self): 1105 def test_iconcat(self):
1104 b = bytearray(b"abc") 1106 b = bytearray(b"abc")
1105 b1 = b 1107 b1 = b
1106 b += b"def" 1108 b += b"def"
1107 self.assertEqual(b, b"abcdef") 1109 self.assertEqual(b, b"abcdef")
1108 self.assertEqual(b, b1) 1110 self.assertEqual(b, b1)
1109 self.assertTrue(b is b1) 1111 self.assertTrue(b is b1)
1110 b += b"xyz" 1112 b += b"xyz"
1111 self.assertEqual(b, b"abcdefxyz") 1113 self.assertEqual(b, b"abcdefxyz")
1112 try: 1114 try:
(...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after
1198 self.assertRaises(ValueError, lambda: b.remove(ord('l'))) 1200 self.assertRaises(ValueError, lambda: b.remove(ord('l')))
1199 self.assertRaises(ValueError, lambda: b.remove(400)) 1201 self.assertRaises(ValueError, lambda: b.remove(400))
1200 self.assertRaises(TypeError, lambda: b.remove('e')) 1202 self.assertRaises(TypeError, lambda: b.remove('e'))
1201 # remove first and last 1203 # remove first and last
1202 b.remove(ord('o')) 1204 b.remove(ord('o'))
1203 b.remove(ord('h')) 1205 b.remove(ord('h'))
1204 self.assertEqual(b, b'e') 1206 self.assertEqual(b, b'e')
1205 self.assertRaises(TypeError, lambda: b.remove(b'e')) 1207 self.assertRaises(TypeError, lambda: b.remove(b'e'))
1206 b.remove(Indexable(ord('e'))) 1208 b.remove(Indexable(ord('e')))
1207 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]))
1208 1217
1209 def test_pop(self): 1218 def test_pop(self):
1210 b = bytearray(b'world') 1219 b = bytearray(b'world')
1211 self.assertEqual(b.pop(), ord('d')) 1220 self.assertEqual(b.pop(), ord('d'))
1212 self.assertEqual(b.pop(0), ord('w')) 1221 self.assertEqual(b.pop(0), ord('w'))
1213 self.assertEqual(b.pop(-2), ord('r')) 1222 self.assertEqual(b.pop(-2), ord('r'))
1214 self.assertRaises(IndexError, lambda: b.pop(10)) 1223 self.assertRaises(IndexError, lambda: b.pop(10))
1215 self.assertRaises(IndexError, lambda: bytearray().pop()) 1224 self.assertRaises(IndexError, lambda: bytearray().pop())
1216 # test for issue #6846 1225 # test for issue #6846
1217 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
1305 def delslice(): 1314 def delslice():
1306 b[1:-1:2] = b"" 1315 b[1:-1:2] = b""
1307 self.assertRaises(BufferError, delslice) 1316 self.assertRaises(BufferError, delslice)
1308 self.assertEqual(b, orig) 1317 self.assertEqual(b, orig)
1309 1318
1310 @test.support.cpython_only 1319 @test.support.cpython_only
1311 def test_obsolete_write_lock(self): 1320 def test_obsolete_write_lock(self):
1312 from _testcapi import getbuffer_with_null_view 1321 from _testcapi import getbuffer_with_null_view
1313 self.assertRaises(BufferError, getbuffer_with_null_view, bytearray()) 1322 self.assertRaises(BufferError, getbuffer_with_null_view, bytearray())
1314 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
1315 class AssortedBytesTest(unittest.TestCase): 1372 class AssortedBytesTest(unittest.TestCase):
1316 # 1373 #
1317 # Test various combinations of bytes and bytearray 1374 # Test various combinations of bytes and bytearray
1318 # 1375 #
1319 1376
1320 @check_bytes_warnings 1377 @check_bytes_warnings
1321 def test_repr_str(self): 1378 def test_repr_str(self):
1322 for f in str, repr: 1379 for f in str, repr:
1323 self.assertEqual(f(bytearray()), "bytearray(b'')") 1380 self.assertEqual(f(bytearray()), "bytearray(b'')")
1324 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
1451 with bytes_warning(): 1508 with bytes_warning():
1452 0 != b'\0' 1509 0 != b'\0'
1453 1510
1454 # Optimizations: 1511 # Optimizations:
1455 # __iter__? (optimization) 1512 # __iter__? (optimization)
1456 # __reversed__? (optimization) 1513 # __reversed__? (optimization)
1457 1514
1458 # XXX More string methods? (Those that don't use character properties) 1515 # XXX More string methods? (Those that don't use character properties)
1459 1516
1460 # There are tests in string_tests.py that are more 1517 # There are tests in string_tests.py that are more
1461 # comprehensive for things like split, partition, etc. 1518 # comprehensive for things like partition, etc.
1462 # Unfortunately they are all bundled with tests that 1519 # Unfortunately they are all bundled with tests that
1463 # are not appropriate for bytes 1520 # are not appropriate for bytes
1464 1521
1465 # 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
1466 # 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
1467 # unittest methods at the same time). 1524 # unittest methods at the same time).
1468 1525
1469 class BytearrayPEP3137Test(unittest.TestCase, 1526 class BytearrayPEP3137Test(unittest.TestCase):
1470 test.buffer_tests.MixinBytesBufferCommonTests):
1471 def marshal(self, x): 1527 def marshal(self, x):
1472 return bytearray(x) 1528 return bytearray(x)
1473 1529
1474 def test_returns_new_copy(self): 1530 def test_returns_new_copy(self):
1475 val = self.marshal(b'1234') 1531 val = self.marshal(b'1234')
1476 # On immutable types these MAY return a reference to themselves 1532 # On immutable types these MAY return a reference to themselves
1477 # 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.
1478 for methname in ('zfill', 'rjust', 'ljust', 'center'): 1534 for methname in ('zfill', 'rjust', 'ljust', 'center'):
1479 method = getattr(val, methname) 1535 method = getattr(val, methname)
1480 newval = method(3) 1536 newval = method(3)
1481 self.assertEqual(val, newval) 1537 self.assertEqual(val, newval)
1482 self.assertTrue(val is not newval, 1538 self.assertTrue(val is not newval,
1483 methname+' returned self on a mutable object') 1539 methname+' returned self on a mutable object')
1484 for expr in ('val.split()[0]', 'val.rsplit()[0]', 1540 for expr in ('val.split()[0]', 'val.rsplit()[0]',
1485 'val.partition(b".")[0]', 'val.rpartition(b".")[2]', 1541 'val.partition(b".")[0]', 'val.rpartition(b".")[2]',
1486 'val.splitlines()[0]', 'val.replace(b"", b"")'): 1542 'val.splitlines()[0]', 'val.replace(b"", b"")'):
1487 newval = eval(expr) 1543 newval = eval(expr)
1488 self.assertEqual(val, newval) 1544 self.assertEqual(val, newval)
1489 self.assertTrue(val is not newval, 1545 self.assertTrue(val is not newval,
1490 expr+' returned val on a mutable object') 1546 expr+' returned val on a mutable object')
1491 sep = self.marshal(b'') 1547 sep = self.marshal(b'')
1492 newval = sep.join([val]) 1548 newval = sep.join([val])
1493 self.assertEqual(val, newval) 1549 self.assertEqual(val, newval)
1494 self.assertIsNot(val, newval) 1550 self.assertIsNot(val, newval)
1495 1551
1496 1552
1497 class FixedStringTest(test.string_tests.BaseTest): 1553 class FixedStringTest(test.string_tests.BaseTest):
1498
1499 def fixtype(self, obj): 1554 def fixtype(self, obj):
1500 if isinstance(obj, str): 1555 if isinstance(obj, str):
1501 return obj.encode("utf-8") 1556 return self.type2test(obj.encode("utf-8"))
1502 return super().fixtype(obj) 1557 return super().fixtype(obj)
1503 1558
1504 # Currently the bytes containment testing uses a single integer 1559 contains_bytes = True
1505 # value. This may not be the final design, but until then the
1506 # bytes section with in a bytes containment not valid
1507 def test_contains(self):
1508 pass
1509 def test_expandtabs(self):
1510 pass
1511 def test_upper(self):
1512 pass
1513 def test_lower(self):
1514 pass
1515 1560
1516 class ByteArrayAsStringTest(FixedStringTest, unittest.TestCase): 1561 class ByteArrayAsStringTest(FixedStringTest, unittest.TestCase):
1517 type2test = bytearray 1562 type2test = bytearray
1518 contains_bytes = True
1519 1563
1520 class BytesAsStringTest(FixedStringTest, unittest.TestCase): 1564 class BytesAsStringTest(FixedStringTest, unittest.TestCase):
1521 type2test = bytes 1565 type2test = bytes
1522 contains_bytes = True
1523 1566
1524 1567
1525 class SubclassTest: 1568 class SubclassTest:
1526 1569
1527 def test_basic(self): 1570 def test_basic(self):
1528 self.assertTrue(issubclass(self.subclass2test, self.type2test)) 1571 self.assertTrue(issubclass(self.type2test, self.basetype))
1529 self.assertIsInstance(self.subclass2test(), self.type2test) 1572 self.assertIsInstance(self.type2test(), self.basetype)
1530 1573
1531 a, b = b"abcd", b"efgh" 1574 a, b = b"abcd", b"efgh"
1532 _a, _b = self.subclass2test(a), self.subclass2test(b) 1575 _a, _b = self.type2test(a), self.type2test(b)
1533 1576
1534 # test comparison operators with subclass instances 1577 # test comparison operators with subclass instances
1535 self.assertTrue(_a == _a) 1578 self.assertTrue(_a == _a)
1536 self.assertTrue(_a != _b) 1579 self.assertTrue(_a != _b)
1537 self.assertTrue(_a < _b) 1580 self.assertTrue(_a < _b)
1538 self.assertTrue(_a <= _b) 1581 self.assertTrue(_a <= _b)
1539 self.assertTrue(_b >= _a) 1582 self.assertTrue(_b >= _a)
1540 self.assertTrue(_b > _a) 1583 self.assertTrue(_b > _a)
1541 self.assertTrue(_a is not a) 1584 self.assertTrue(_a is not a)
1542 1585
1543 # test concat of subclass instances 1586 # test concat of subclass instances
1544 self.assertEqual(a + b, _a + _b) 1587 self.assertEqual(a + b, _a + _b)
1545 self.assertEqual(a + b, a + _b) 1588 self.assertEqual(a + b, a + _b)
1546 self.assertEqual(a + b, _a + b) 1589 self.assertEqual(a + b, _a + b)
1547 1590
1548 # test repeat 1591 # test repeat
1549 self.assertTrue(a*5 == _a*5) 1592 self.assertTrue(a*5 == _a*5)
1550 1593
1551 def test_join(self): 1594 def test_join(self):
1552 # Make sure join returns a NEW object for single item sequences 1595 # Make sure join returns a NEW object for single item sequences
1553 # involving a subclass. 1596 # involving a subclass.
1554 # Make sure that it is of the appropriate type. 1597 # Make sure that it is of the appropriate type.
1555 s1 = self.subclass2test(b"abcd") 1598 s1 = self.type2test(b"abcd")
1556 s2 = self.type2test().join([s1]) 1599 s2 = self.basetype().join([s1])
1557 self.assertTrue(s1 is not s2) 1600 self.assertTrue(s1 is not s2)
1558 self.assertTrue(type(s2) is self.type2test, type(s2)) 1601 self.assertTrue(type(s2) is self.basetype, type(s2))
1559 1602
1560 # Test reverse, calling join on subclass 1603 # Test reverse, calling join on subclass
1561 s3 = s1.join([b"abcd"]) 1604 s3 = s1.join([b"abcd"])
1562 self.assertTrue(type(s3) is self.type2test) 1605 self.assertTrue(type(s3) is self.basetype)
1563 1606
1564 def test_pickle(self): 1607 def test_pickle(self):
1565 a = self.subclass2test(b"abcd") 1608 a = self.type2test(b"abcd")
1566 a.x = 10 1609 a.x = 10
1567 a.y = self.subclass2test(b"efgh") 1610 a.y = self.type2test(b"efgh")
1568 for proto in range(pickle.HIGHEST_PROTOCOL + 1): 1611 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1569 b = pickle.loads(pickle.dumps(a, proto)) 1612 b = pickle.loads(pickle.dumps(a, proto))
1570 self.assertNotEqual(id(a), id(b)) 1613 self.assertNotEqual(id(a), id(b))
1571 self.assertEqual(a, b) 1614 self.assertEqual(a, b)
1572 self.assertEqual(a.x, b.x) 1615 self.assertEqual(a.x, b.x)
1573 self.assertEqual(a.y, b.y) 1616 self.assertEqual(a.y, b.y)
1574 self.assertEqual(type(a), type(b)) 1617 self.assertEqual(type(a), type(b))
1575 self.assertEqual(type(a.y), type(b.y)) 1618 self.assertEqual(type(a.y), type(b.y))
1576 1619
1577 def test_copy(self): 1620 def test_copy(self):
1578 a = self.subclass2test(b"abcd") 1621 a = self.type2test(b"abcd")
1579 a.x = 10 1622 a.x = 10
1580 a.y = self.subclass2test(b"efgh") 1623 a.y = self.type2test(b"efgh")
1581 for copy_method in (copy.copy, copy.deepcopy): 1624 for copy_method in (copy.copy, copy.deepcopy):
1582 b = copy_method(a) 1625 b = copy_method(a)
1583 self.assertNotEqual(id(a), id(b)) 1626 self.assertNotEqual(id(a), id(b))
1584 self.assertEqual(a, b) 1627 self.assertEqual(a, b)
1585 self.assertEqual(a.x, b.x) 1628 self.assertEqual(a.x, b.x)
1586 self.assertEqual(a.y, b.y) 1629 self.assertEqual(a.y, b.y)
1587 self.assertEqual(type(a), type(b)) 1630 self.assertEqual(type(a), type(b))
1588 self.assertEqual(type(a.y), type(b.y)) 1631 self.assertEqual(type(a.y), type(b.y))
1589 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
1590 1660
1591 class ByteArraySubclass(bytearray): 1661 class ByteArraySubclass(bytearray):
1592 pass 1662 pass
1593 1663
1594 class BytesSubclass(bytes): 1664 class BytesSubclass(bytes):
1595 pass 1665 pass
1596 1666
1597 class OtherBytesSubclass(bytes): 1667 class OtherBytesSubclass(bytes):
1598 pass 1668 pass
1599 1669
1600 class ByteArraySubclassTest(SubclassTest, unittest.TestCase): 1670 class ByteArraySubclassTest(SubclassTest, unittest.TestCase):
1601 type2test = bytearray 1671 basetype = bytearray
1602 subclass2test = ByteArraySubclass 1672 type2test = ByteArraySubclass
1603 1673
1604 def test_init_override(self): 1674 def test_init_override(self):
1605 class subclass(bytearray): 1675 class subclass(bytearray):
1606 def __init__(me, newarg=1, *args, **kwargs): 1676 def __init__(me, newarg=1, *args, **kwargs):
1607 bytearray.__init__(me, *args, **kwargs) 1677 bytearray.__init__(me, *args, **kwargs)
1608 x = subclass(4, b"abcd") 1678 x = subclass(4, b"abcd")
1609 x = subclass(4, source=b"abcd") 1679 x = subclass(4, source=b"abcd")
1610 self.assertEqual(x, b"abcd") 1680 self.assertEqual(x, b"abcd")
1611 x = subclass(newarg=4, source=b"abcd") 1681 x = subclass(newarg=4, source=b"abcd")
1612 self.assertEqual(x, b"abcd") 1682 self.assertEqual(x, b"abcd")
1613 1683
1614 1684
1615 class BytesSubclassTest(SubclassTest, unittest.TestCase): 1685 class BytesSubclassTest(SubclassTest, unittest.TestCase):
1616 type2test = bytes 1686 basetype = bytes
1617 subclass2test = BytesSubclass 1687 type2test = BytesSubclass
1618 1688
1619 1689
1620 if __name__ == "__main__": 1690 if __name__ == "__main__":
1621 unittest.main() 1691 unittest.main()
LEFTRIGHT

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