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

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

Issue 13390: Hunt memory allocations in addition to reference leaks
Left Patch Set: Created 7 years, 10 months ago
Right Patch Set: Created 6 years, 9 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/support.py ('k') | Objects/obmalloc.c » ('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 import unittest, test.support 1 import unittest, test.support
2 import sys, io, os 2 import sys, io, os
3 import struct 3 import struct
4 import subprocess 4 import subprocess
5 import textwrap 5 import textwrap
6 import warnings 6 import warnings
7 import operator 7 import operator
8 import codecs 8 import codecs
9 import gc 9 import gc
10 10
(...skipping 402 matching lines...) Expand 10 before | Expand all | Expand 10 after
413 self.assertIn(0, d) 413 self.assertIn(0, d)
414 self.assertTrue(d[0] is sys._getframe()) 414 self.assertTrue(d[0] is sys._getframe())
415 415
416 def test_attributes(self): 416 def test_attributes(self):
417 self.assertIsInstance(sys.api_version, int) 417 self.assertIsInstance(sys.api_version, int)
418 self.assertIsInstance(sys.argv, list) 418 self.assertIsInstance(sys.argv, list)
419 self.assertIn(sys.byteorder, ("little", "big")) 419 self.assertIn(sys.byteorder, ("little", "big"))
420 self.assertIsInstance(sys.builtin_module_names, tuple) 420 self.assertIsInstance(sys.builtin_module_names, tuple)
421 self.assertIsInstance(sys.copyright, str) 421 self.assertIsInstance(sys.copyright, str)
422 self.assertIsInstance(sys.exec_prefix, str) 422 self.assertIsInstance(sys.exec_prefix, str)
423 self.assertIsInstance(sys.base_exec_prefix, str)
423 self.assertIsInstance(sys.executable, str) 424 self.assertIsInstance(sys.executable, str)
424 self.assertEqual(len(sys.float_info), 11) 425 self.assertEqual(len(sys.float_info), 11)
425 self.assertEqual(sys.float_info.radix, 2) 426 self.assertEqual(sys.float_info.radix, 2)
426 self.assertEqual(len(sys.int_info), 2) 427 self.assertEqual(len(sys.int_info), 2)
427 self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) 428 self.assertTrue(sys.int_info.bits_per_digit % 5 == 0)
428 self.assertTrue(sys.int_info.sizeof_digit >= 1) 429 self.assertTrue(sys.int_info.sizeof_digit >= 1)
429 self.assertEqual(type(sys.int_info.bits_per_digit), int) 430 self.assertEqual(type(sys.int_info.bits_per_digit), int)
430 self.assertEqual(type(sys.int_info.sizeof_digit), int) 431 self.assertEqual(type(sys.int_info.sizeof_digit), int)
431 self.assertIsInstance(sys.hexversion, int) 432 self.assertIsInstance(sys.hexversion, int)
432 433
(...skipping 11 matching lines...) Expand all
444 ) 445 )
445 self.assertIsInstance(sys.hash_info.inf, int) 446 self.assertIsInstance(sys.hash_info.inf, int)
446 self.assertIsInstance(sys.hash_info.nan, int) 447 self.assertIsInstance(sys.hash_info.nan, int)
447 self.assertIsInstance(sys.hash_info.imag, int) 448 self.assertIsInstance(sys.hash_info.imag, int)
448 449
449 self.assertIsInstance(sys.maxsize, int) 450 self.assertIsInstance(sys.maxsize, int)
450 self.assertIsInstance(sys.maxunicode, int) 451 self.assertIsInstance(sys.maxunicode, int)
451 self.assertEqual(sys.maxunicode, 0x10FFFF) 452 self.assertEqual(sys.maxunicode, 0x10FFFF)
452 self.assertIsInstance(sys.platform, str) 453 self.assertIsInstance(sys.platform, str)
453 self.assertIsInstance(sys.prefix, str) 454 self.assertIsInstance(sys.prefix, str)
455 self.assertIsInstance(sys.base_prefix, str)
454 self.assertIsInstance(sys.version, str) 456 self.assertIsInstance(sys.version, str)
455 vi = sys.version_info 457 vi = sys.version_info
456 self.assertIsInstance(vi[:], tuple) 458 self.assertIsInstance(vi[:], tuple)
457 self.assertEqual(len(vi), 5) 459 self.assertEqual(len(vi), 5)
458 self.assertIsInstance(vi[0], int) 460 self.assertIsInstance(vi[0], int)
459 self.assertIsInstance(vi[1], int) 461 self.assertIsInstance(vi[1], int)
460 self.assertIsInstance(vi[2], int) 462 self.assertIsInstance(vi[2], int)
461 self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) 463 self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
462 self.assertIsInstance(vi[4], int) 464 self.assertIsInstance(vi[4], int)
463 self.assertIsInstance(vi.major, int) 465 self.assertIsInstance(vi.major, int)
(...skipping 10 matching lines...) Expand all
474 self.assertIsInstance(sys.float_repr_style, str) 476 self.assertIsInstance(sys.float_repr_style, str)
475 self.assertIn(sys.float_repr_style, ('short', 'legacy')) 477 self.assertIn(sys.float_repr_style, ('short', 'legacy'))
476 if not sys.platform.startswith('win'): 478 if not sys.platform.startswith('win'):
477 self.assertIsInstance(sys.abiflags, str) 479 self.assertIsInstance(sys.abiflags, str)
478 480
479 @unittest.skipUnless(hasattr(sys, 'thread_info'), 481 @unittest.skipUnless(hasattr(sys, 'thread_info'),
480 'Threading required for this test.') 482 'Threading required for this test.')
481 def test_thread_info(self): 483 def test_thread_info(self):
482 info = sys.thread_info 484 info = sys.thread_info
483 self.assertEqual(len(info), 3) 485 self.assertEqual(len(info), 3)
484 self.assertIn(info.name, ('nt', 'os2', 'pthread', 'solaris', None)) 486 self.assertIn(info.name, ('nt', 'pthread', 'solaris', None))
485 self.assertIn(info.lock, ('semaphore', 'mutex+cond', None)) 487 self.assertIn(info.lock, ('semaphore', 'mutex+cond', None))
486 488
487 def test_43581(self): 489 def test_43581(self):
488 # Can't use sys.stdout, as this is a StringIO object when 490 # Can't use sys.stdout, as this is a StringIO object when
489 # the test runs under regrtest. 491 # the test runs under regrtest.
490 self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) 492 self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding)
491 493
492 def test_intern(self): 494 def test_intern(self):
493 global numruns 495 global numruns
494 numruns += 1 496 numruns += 1
(...skipping 12 matching lines...) Expand all
507 def __hash__(self): 509 def __hash__(self):
508 return 123 510 return 123
509 511
510 self.assertRaises(TypeError, sys.intern, S("abc")) 512 self.assertRaises(TypeError, sys.intern, S("abc"))
511 513
512 def test_sys_flags(self): 514 def test_sys_flags(self):
513 self.assertTrue(sys.flags) 515 self.assertTrue(sys.flags)
514 attrs = ("debug", 516 attrs = ("debug",
515 "inspect", "interactive", "optimize", "dont_write_bytecode", 517 "inspect", "interactive", "optimize", "dont_write_bytecode",
516 "no_user_site", "no_site", "ignore_environment", "verbose", 518 "no_user_site", "no_site", "ignore_environment", "verbose",
517 "bytes_warning", "quiet") 519 "bytes_warning", "quiet", "hash_randomization")
518 for attr in attrs: 520 for attr in attrs:
519 self.assertTrue(hasattr(sys.flags, attr), attr) 521 self.assertTrue(hasattr(sys.flags, attr), attr)
520 self.assertEqual(type(getattr(sys.flags, attr)), int, attr) 522 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
521 self.assertTrue(repr(sys.flags)) 523 self.assertTrue(repr(sys.flags))
522 self.assertEqual(len(sys.flags), len(attrs)) 524 self.assertEqual(len(sys.flags), len(attrs))
523 525
524 def test_clear_type_cache(self): 526 def test_clear_type_cache(self):
525 sys._clear_type_cache() 527 sys._clear_type_cache()
526 528
527 def test_ioencoding(self): 529 def test_ioencoding(self):
528 env = dict(os.environ) 530 env = dict(os.environ)
529 531
530 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, 532 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
531 # not representable in ASCII. 533 # not representable in ASCII.
532 534
533 env["PYTHONIOENCODING"] = "cp424" 535 env["PYTHONIOENCODING"] = "cp424"
534 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], 536 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
535 stdout = subprocess.PIPE, env=env) 537 stdout = subprocess.PIPE, env=env)
536 out = p.communicate()[0].strip() 538 out = p.communicate()[0].strip()
537 self.assertEqual(out, "\xa2\n".encode("cp424")) 539 expected = ("\xa2" + os.linesep).encode("cp424")
540 self.assertEqual(out, expected)
538 541
539 env["PYTHONIOENCODING"] = "ascii:replace" 542 env["PYTHONIOENCODING"] = "ascii:replace"
540 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], 543 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
541 stdout = subprocess.PIPE, env=env) 544 stdout = subprocess.PIPE, env=env)
542 out = p.communicate()[0].strip() 545 out = p.communicate()[0].strip()
543 self.assertEqual(out, b'?') 546 self.assertEqual(out, b'?')
544 547
548 @unittest.skipIf(sys.base_prefix != sys.prefix,
549 'Test is not venv-compatible')
545 def test_executable(self): 550 def test_executable(self):
551 # sys.executable should be absolute
552 self.assertEqual(os.path.abspath(sys.executable), sys.executable)
553
546 # Issue #7774: Ensure that sys.executable is an empty string if argv[0] 554 # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
547 # has been set to an non existent program name and Python is unable to 555 # has been set to an non existent program name and Python is unable to
548 # retrieve the real program name 556 # retrieve the real program name
549 557
550 # For a normal installation, it should work without 'cwd' 558 # For a normal installation, it should work without 'cwd'
551 # argument. For test runs in the build directory, see #7774. 559 # argument. For test runs in the build directory, see #7774.
552 python_dir = os.path.dirname(os.path.realpath(sys.executable)) 560 python_dir = os.path.dirname(os.path.realpath(sys.executable))
553 p = subprocess.Popen( 561 p = subprocess.Popen(
554 ["nonexistent", "-c", 562 ["nonexistent", "-c",
555 'import sys; print(sys.executable.encode("ascii", "backslashreplace "))'], 563 'import sys; print(sys.executable.encode("ascii", "backslashreplace "))'],
(...skipping 12 matching lines...) Expand all
568 def test_getfilesystemencoding(self): 576 def test_getfilesystemencoding(self):
569 fs_encoding = sys.getfilesystemencoding() 577 fs_encoding = sys.getfilesystemencoding()
570 if sys.platform == 'darwin': 578 if sys.platform == 'darwin':
571 expected = 'utf-8' 579 expected = 'utf-8'
572 elif sys.platform == 'win32': 580 elif sys.platform == 'win32':
573 expected = 'mbcs' 581 expected = 'mbcs'
574 else: 582 else:
575 expected = None 583 expected = None
576 self.check_fsencoding(fs_encoding, expected) 584 self.check_fsencoding(fs_encoding, expected)
577 585
586 def test_implementation(self):
587 # This test applies to all implementations equally.
588
589 levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF}
590
591 self.assertTrue(hasattr(sys.implementation, 'name'))
592 self.assertTrue(hasattr(sys.implementation, 'version'))
593 self.assertTrue(hasattr(sys.implementation, 'hexversion'))
594 self.assertTrue(hasattr(sys.implementation, 'cache_tag'))
595
596 version = sys.implementation.version
597 self.assertEqual(version[:2], (version.major, version.minor))
598
599 hexversion = (version.major << 24 | version.minor << 16 |
600 version.micro << 8 | levels[version.releaselevel] << 4 |
601 version.serial << 0)
602 self.assertEqual(sys.implementation.hexversion, hexversion)
603
604 # PEP 421 requires that .name be lower case.
605 self.assertEqual(sys.implementation.name,
606 sys.implementation.name.lower())
607
608 def test_debugmallocstats(self):
609 # Test sys._debugmallocstats()
610 from test.script_helper import assert_python_ok
611 args = ['-c', 'import sys; sys._debugmallocstats()']
612 ret, out, err = assert_python_ok(*args)
613 self.assertIn(b"free PyDictObjects", err)
614
615 @unittest.skipUnless(hasattr(sys, "getallocatedblocks"),
616 "sys.getallocatedblocks unavailable on this build")
617 def test_getallocatedblocks(self):
618 # Some sanity checks
619 a = sys.getallocatedblocks()
620 self.assertIs(type(a), int)
621 self.assertGreater(a, 0)
622 try:
623 # While we could imagine a Python session where the number of
624 # multiple buffer objects would exceed the sharing of references,
625 # it is unlikely to happen in a normal test run.
626 self.assertLess(a, sys.gettotalrefcount())
627 except AttributeError:
628 # gettotalrefcount() not available
629 pass
630 gc.collect()
631 b = sys.getallocatedblocks()
632 self.assertLessEqual(b, a)
633 gc.collect()
634 c = sys.getallocatedblocks()
635 self.assertIn(c, range(b - 50, b + 50))
636
578 637
579 class SizeofTest(unittest.TestCase): 638 class SizeofTest(unittest.TestCase):
580 639
581 TPFLAGS_HAVE_GC = 1<<14
582 TPFLAGS_HEAPTYPE = 1<<9
583
584 def setUp(self): 640 def setUp(self):
585 self.c = len(struct.pack('c', b' ')) 641 self.P = struct.calcsize('P')
586 self.H = len(struct.pack('H', 0))
587 self.i = len(struct.pack('i', 0))
588 self.l = len(struct.pack('l', 0))
589 self.P = len(struct.pack('P', 0))
590 # due to missing size_t information from struct, it is assumed that
591 # sizeof(Py_ssize_t) = sizeof(void*)
592 self.header = 'PP'
593 self.vheader = self.header + 'P'
594 if hasattr(sys, "gettotalrefcount"):
595 self.header += '2P'
596 self.vheader += '2P'
597 self.longdigit = sys.int_info.sizeof_digit 642 self.longdigit = sys.int_info.sizeof_digit
598 import _testcapi 643 import _testcapi
599 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD 644 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
600 self.file = open(test.support.TESTFN, 'wb') 645 self.file = open(test.support.TESTFN, 'wb')
601 646
602 def tearDown(self): 647 def tearDown(self):
603 self.file.close() 648 self.file.close()
604 test.support.unlink(test.support.TESTFN) 649 test.support.unlink(test.support.TESTFN)
605 650
606 def check_sizeof(self, o, size): 651 check_sizeof = test.support.check_sizeof
607 result = sys.getsizeof(o)
608 # add GC header size
609 if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
610 ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
611 size += self.gc_headsize
612 msg = 'wrong size for %s: got %d, expected %d' \
613 % (type(o), result, size)
614 self.assertEqual(result, size, msg)
615
616 def calcsize(self, fmt):
617 """Wrapper around struct.calcsize which enforces the alignment of the
618 end of a structure to the alignment requirement of pointer.
619
620 Note: This wrapper should only be used if a pointer member is included
621 and no member with a size larger than a pointer exists.
622 """
623 return struct.calcsize(fmt + '0P')
624 652
625 def test_gc_head_size(self): 653 def test_gc_head_size(self):
626 # Check that the gc header size is added to objects tracked by the gc. 654 # Check that the gc header size is added to objects tracked by the gc.
627 h = self.header 655 vsize = test.support.calcvobjsize
628 vh = self.vheader
629 size = self.calcsize
630 gc_header_size = self.gc_headsize 656 gc_header_size = self.gc_headsize
631 # bool objects are not gc tracked 657 # bool objects are not gc tracked
632 self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit) 658 self.assertEqual(sys.getsizeof(True), vsize('') + self.longdigit)
633 # but lists are 659 # but lists are
634 self.assertEqual(sys.getsizeof([]), size(vh + 'PP') + gc_header_size) 660 self.assertEqual(sys.getsizeof([]), vsize('Pn') + gc_header_size)
635 661
636 def test_default(self): 662 def test_default(self):
637 h = self.header 663 size = test.support.calcvobjsize
638 vh = self.vheader 664 self.assertEqual(sys.getsizeof(True), size('') + self.longdigit)
639 size = self.calcsize 665 self.assertEqual(sys.getsizeof(True, -1), size('') + self.longdigit)
640 self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit)
641 self.assertEqual(sys.getsizeof(True, -1), size(vh) + self.longdigit)
642 666
643 def test_objecttypes(self): 667 def test_objecttypes(self):
644 # check all types defined in Objects/ 668 # check all types defined in Objects/
645 h = self.header 669 size = test.support.calcobjsize
646 vh = self.vheader 670 vsize = test.support.calcvobjsize
647 size = self.calcsize
648 check = self.check_sizeof 671 check = self.check_sizeof
649 # bool 672 # bool
650 check(True, size(vh) + self.longdigit) 673 check(True, vsize('') + self.longdigit)
651 # buffer 674 # buffer
652 # XXX 675 # XXX
653 # builtin_function_or_method 676 # builtin_function_or_method
654 check(len, size(h + '3P')) 677 check(len, size('3P')) # XXX check layout
655 # bytearray 678 # bytearray
656 samples = [b'', b'u'*100000] 679 samples = [b'', b'u'*100000]
657 for sample in samples: 680 for sample in samples:
658 x = bytearray(sample) 681 x = bytearray(sample)
659 check(x, size(vh + 'iPP') + x.__alloc__() * self.c) 682 check(x, vsize('inP') + x.__alloc__())
660 # bytearray_iterator 683 # bytearray_iterator
661 check(iter(bytearray()), size(h + 'PP')) 684 check(iter(bytearray()), size('nP'))
662 # cell 685 # cell
663 def get_cell(): 686 def get_cell():
664 x = 42 687 x = 42
665 def inner(): 688 def inner():
666 return x 689 return x
667 return inner 690 return inner
668 check(get_cell().__closure__[0], size(h + 'P')) 691 check(get_cell().__closure__[0], size('P'))
669 # code 692 # code
670 check(get_cell().__code__, size(h + '5i9Pi3P')) 693 check(get_cell().__code__, size('5i9Pi3P'))
694 check(get_cell.__code__, size('5i9Pi3P'))
695 def get_cell2(x):
696 def inner():
697 return x
698 return inner
699 check(get_cell2.__code__, size('5i9Pi3P') + 1)
671 # complex 700 # complex
672 check(complex(0,1), size(h + '2d')) 701 check(complex(0,1), size('2d'))
673 # method_descriptor (descriptor object) 702 # method_descriptor (descriptor object)
674 check(str.lower, size(h + '2PP')) 703 check(str.lower, size('3PP'))
675 # classmethod_descriptor (descriptor object) 704 # classmethod_descriptor (descriptor object)
676 # XXX 705 # XXX
677 # member_descriptor (descriptor object) 706 # member_descriptor (descriptor object)
678 import datetime 707 import datetime
679 check(datetime.timedelta.days, size(h + '2PP')) 708 check(datetime.timedelta.days, size('3PP'))
680 # getset_descriptor (descriptor object) 709 # getset_descriptor (descriptor object)
681 import collections 710 import collections
682 check(collections.defaultdict.default_factory, size(h + '2PP')) 711 check(collections.defaultdict.default_factory, size('3PP'))
683 # wrapper_descriptor (descriptor object) 712 # wrapper_descriptor (descriptor object)
684 check(int.__add__, size(h + '2P2P')) 713 check(int.__add__, size('3P2P'))
685 # method-wrapper (descriptor object) 714 # method-wrapper (descriptor object)
686 check({}.__iter__, size(h + '2P')) 715 check({}.__iter__, size('2P'))
687 # dict 716 # dict
688 check({}, size(h + '3P2P' + 8*'P2P')) 717 check({}, size('n2P' + '2nPn' + 8*'n2P'))
689 longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} 718 longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
690 check(longdict, size(h + '3P2P' + 8*'P2P') + 16*size('P2P')) 719 check(longdict, size('n2P' + '2nPn') + 16*struct.calcsize('n2P'))
691 # dictionary-keyiterator 720 # dictionary-keyiterator
692 check({}.keys(), size(h + 'P')) 721 check({}.keys(), size('P'))
693 # dictionary-valueiterator 722 # dictionary-valueiterator
694 check({}.values(), size(h + 'P')) 723 check({}.values(), size('P'))
695 # dictionary-itemiterator 724 # dictionary-itemiterator
696 check({}.items(), size(h + 'P')) 725 check({}.items(), size('P'))
726 # dictionary iterator
727 check(iter({}), size('P2nPn'))
697 # dictproxy 728 # dictproxy
698 class C(object): pass 729 class C(object): pass
699 check(C.__dict__, size(h + 'P')) 730 check(C.__dict__, size('P'))
700 # BaseException 731 # BaseException
701 check(BaseException(), size(h + '5P')) 732 check(BaseException(), size('5Pi'))
702 # UnicodeEncodeError 733 # UnicodeEncodeError
703 check(UnicodeEncodeError("", "", 0, 0, ""), size(h + '5P 2P2PP')) 734 check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pi 2P2nP'))
704 # UnicodeDecodeError 735 # UnicodeDecodeError
705 # XXX 736 check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pi 2P2nP'))
706 # check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
707 # UnicodeTranslateError 737 # UnicodeTranslateError
708 check(UnicodeTranslateError("", 0, 1, ""), size(h + '5P 2P2PP')) 738 check(UnicodeTranslateError("", 0, 1, ""), size('5Pi 2P2nP'))
709 # ellipses 739 # ellipses
710 check(Ellipsis, size(h + '')) 740 check(Ellipsis, size(''))
711 # EncodingMap 741 # EncodingMap
712 import codecs, encodings.iso8859_3 742 import codecs, encodings.iso8859_3
713 x = codecs.charmap_build(encodings.iso8859_3.decoding_table) 743 x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
714 check(x, size(h + '32B2iB')) 744 check(x, size('32B2iB'))
715 # enumerate 745 # enumerate
716 check(enumerate([]), size(h + 'l3P')) 746 check(enumerate([]), size('n3P'))
717 # reverse 747 # reverse
718 check(reversed(''), size(h + 'PP')) 748 check(reversed(''), size('nP'))
719 # float 749 # float
720 check(float(0), size(h + 'd')) 750 check(float(0), size('d'))
721 # sys.floatinfo 751 # sys.floatinfo
722 check(sys.float_info, size(vh) + self.P * len(sys.float_info)) 752 check(sys.float_info, vsize('') + self.P * len(sys.float_info))
723 # frame 753 # frame
724 import inspect 754 import inspect
725 CO_MAXBLOCKS = 20 755 CO_MAXBLOCKS = 20
726 x = inspect.currentframe() 756 x = inspect.currentframe()
727 ncells = len(x.f_code.co_cellvars) 757 ncells = len(x.f_code.co_cellvars)
728 nfrees = len(x.f_code.co_freevars) 758 nfrees = len(x.f_code.co_freevars)
729 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ 759 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
730 ncells + nfrees - 1 760 ncells + nfrees - 1
731 check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P')) 761 check(x, vsize('12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
732 # function 762 # function
733 def func(): pass 763 def func(): pass
734 check(func, size(h + '11P')) 764 check(func, size('12P'))
735 class c(): 765 class c():
736 @staticmethod 766 @staticmethod
737 def foo(): 767 def foo():
738 pass 768 pass
739 @classmethod 769 @classmethod
740 def bar(cls): 770 def bar(cls):
741 pass 771 pass
742 # staticmethod 772 # staticmethod
743 check(foo, size(h + 'P')) 773 check(foo, size('PP'))
744 # classmethod 774 # classmethod
745 check(bar, size(h + 'P')) 775 check(bar, size('PP'))
746 # generator 776 # generator
747 def get_gen(): yield 1 777 def get_gen(): yield 1
748 check(get_gen(), size(h + 'Pi2P')) 778 check(get_gen(), size('Pb2P'))
749 # iterator 779 # iterator
750 check(iter('abc'), size(h + 'lP')) 780 check(iter('abc'), size('lP'))
751 # callable-iterator 781 # callable-iterator
752 import re 782 import re
753 check(re.finditer('',''), size(h + '2P')) 783 check(re.finditer('',''), size('2P'))
754 # list 784 # list
755 samples = [[], [1,2,3], ['1', '2', '3']] 785 samples = [[], [1,2,3], ['1', '2', '3']]
756 for sample in samples: 786 for sample in samples:
757 check(sample, size(vh + 'PP') + len(sample)*self.P) 787 check(sample, vsize('Pn') + len(sample)*self.P)
758 # sortwrapper (list) 788 # sortwrapper (list)
759 # XXX 789 # XXX
760 # cmpwrapper (list) 790 # cmpwrapper (list)
761 # XXX 791 # XXX
762 # listiterator (list) 792 # listiterator (list)
763 check(iter([]), size(h + 'lP')) 793 check(iter([]), size('lP'))
764 # listreverseiterator (list) 794 # listreverseiterator (list)
765 check(reversed([]), size(h + 'lP')) 795 check(reversed([]), size('nP'))
766 # long 796 # long
767 check(0, size(vh)) 797 check(0, vsize(''))
768 check(1, size(vh) + self.longdigit) 798 check(1, vsize('') + self.longdigit)
769 check(-1, size(vh) + self.longdigit) 799 check(-1, vsize('') + self.longdigit)
770 PyLong_BASE = 2**sys.int_info.bits_per_digit 800 PyLong_BASE = 2**sys.int_info.bits_per_digit
771 check(int(PyLong_BASE), size(vh) + 2*self.longdigit) 801 check(int(PyLong_BASE), vsize('') + 2*self.longdigit)
772 check(int(PyLong_BASE**2-1), size(vh) + 2*self.longdigit) 802 check(int(PyLong_BASE**2-1), vsize('') + 2*self.longdigit)
773 check(int(PyLong_BASE**2), size(vh) + 3*self.longdigit) 803 check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit)
774 # memory 804 # memoryview
775 check(memoryview(b''), size(h + 'PP2P2i7P')) 805 check(memoryview(b''), size('Pnin 2P2n2i5P 3cPn'))
776 # module 806 # module
777 check(unittest, size(h + '3P')) 807 check(unittest, size('PnP'))
778 # None 808 # None
779 check(None, size(h + '')) 809 check(None, size(''))
780 # NotImplementedType 810 # NotImplementedType
781 check(NotImplemented, size(h)) 811 check(NotImplemented, size(''))
782 # object 812 # object
783 check(object(), size(h + '')) 813 check(object(), size(''))
784 # property (descriptor object) 814 # property (descriptor object)
785 class C(object): 815 class C(object):
786 def getx(self): return self.__x 816 def getx(self): return self.__x
787 def setx(self, value): self.__x = value 817 def setx(self, value): self.__x = value
788 def delx(self): del self.__x 818 def delx(self): del self.__x
789 x = property(getx, setx, delx, "") 819 x = property(getx, setx, delx, "")
790 check(x, size(h + '4Pi')) 820 check(x, size('4Pi'))
791 # PyCapsule 821 # PyCapsule
792 # XXX 822 # XXX
793 # rangeiterator 823 # rangeiterator
794 check(iter(range(1)), size(h + '4l')) 824 check(iter(range(1)), size('4l'))
795 # reverse 825 # reverse
796 check(reversed(''), size(h + 'PP')) 826 check(reversed(''), size('nP'))
797 # range 827 # range
798 check(range(1), size(h + '4P')) 828 check(range(1), size('4P'))
799 check(range(66000), size(h + '4P')) 829 check(range(66000), size('4P'))
800 # set 830 # set
801 # frozenset 831 # frozenset
802 PySet_MINSIZE = 8 832 PySet_MINSIZE = 8
803 samples = [[], range(10), range(50)] 833 samples = [[], range(10), range(50)]
804 s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP') 834 s = size('3n2P' + PySet_MINSIZE*'nP' + 'nP')
805 for sample in samples: 835 for sample in samples:
806 minused = len(sample) 836 minused = len(sample)
807 if minused == 0: tmp = 1 837 if minused == 0: tmp = 1
808 # the computation of minused is actually a bit more complicated 838 # the computation of minused is actually a bit more complicated
809 # but this suffices for the sizeof test 839 # but this suffices for the sizeof test
810 minused = minused*2 840 minused = minused*2
811 newsize = PySet_MINSIZE 841 newsize = PySet_MINSIZE
812 while newsize <= minused: 842 while newsize <= minused:
813 newsize = newsize << 1 843 newsize = newsize << 1
814 if newsize <= 8: 844 if newsize <= 8:
815 check(set(sample), s) 845 check(set(sample), s)
816 check(frozenset(sample), s) 846 check(frozenset(sample), s)
817 else: 847 else:
818 check(set(sample), s + newsize*struct.calcsize('lP')) 848 check(set(sample), s + newsize*struct.calcsize('nP'))
819 check(frozenset(sample), s + newsize*struct.calcsize('lP')) 849 check(frozenset(sample), s + newsize*struct.calcsize('nP'))
820 # setiterator 850 # setiterator
821 check(iter(set()), size(h + 'P3P')) 851 check(iter(set()), size('P3n'))
822 # slice 852 # slice
823 check(slice(0), size(h + '3P')) 853 check(slice(0), size('3P'))
824 # super 854 # super
825 check(super(int), size(h + '3P')) 855 check(super(int), size('3P'))
826 # tuple 856 # tuple
827 check((), size(vh)) 857 check((), vsize(''))
828 check((1,2,3), size(vh) + 3*self.P) 858 check((1,2,3), vsize('') + 3*self.P)
829 # type 859 # type
860 # static type: PyTypeObject
861 s = vsize('P2n15Pl4Pn9Pn11PI')
862 check(int, s)
830 # (PyTypeObject + PyNumberMethods + PyMappingMethods + 863 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
831 # PySequenceMethods + PyBufferProcs) 864 # PySequenceMethods + PyBufferProcs + 4P)
832 s = size(vh + 'P2P15Pl4PP9PP11PI') + size('16Pi17P 3P 10P 2P 2P') 865 s = vsize('P2n15Pl4Pn9Pn11PI') + struct.calcsize('34P 3P 10P 2P 4P')
833 check(int, s) 866 # Separate block for PyDictKeysObject with 4 entries
867 s += struct.calcsize("2nPn") + 4*struct.calcsize("n2P")
834 # class 868 # class
835 class newstyleclass(object): pass 869 class newstyleclass(object): pass
836 check(newstyleclass, s) 870 check(newstyleclass, s)
871 # dict with shared keys
872 check(newstyleclass().__dict__, size('n2P' + '2nPn'))
837 # unicode 873 # unicode
838 # each tuple contains a string and its expected character size 874 # each tuple contains a string and its expected character size
839 # don't put any static strings here, as they may contain 875 # don't put any static strings here, as they may contain
840 # wchar_t or UTF-8 representations 876 # wchar_t or UTF-8 representations
841 samples = ['1'*100, '\xff'*50, 877 samples = ['1'*100, '\xff'*50,
842 '\u0100'*40, '\uffff'*100, 878 '\u0100'*40, '\uffff'*100,
843 '\U00010000'*30, '\U0010ffff'*100] 879 '\U00010000'*30, '\U0010ffff'*100]
844 asciifields = h + "PPiP" 880 asciifields = "nniP"
845 compactfields = asciifields + "PPP" 881 compactfields = asciifields + "nPn"
846 unicodefields = compactfields + "P" 882 unicodefields = compactfields + "P"
847 for s in samples: 883 for s in samples:
848 maxchar = ord(max(s)) 884 maxchar = ord(max(s))
849 if maxchar < 128: 885 if maxchar < 128:
850 L = size(asciifields) + len(s) + 1 886 L = size(asciifields) + len(s) + 1
851 elif maxchar < 256: 887 elif maxchar < 256:
852 L = size(compactfields) + len(s) + 1 888 L = size(compactfields) + len(s) + 1
853 elif maxchar < 65536: 889 elif maxchar < 65536:
854 L = size(compactfields) + 2*(len(s) + 1) 890 L = size(compactfields) + 2*(len(s) + 1)
855 else: 891 else:
856 L = size(compactfields) + 4*(len(s) + 1) 892 L = size(compactfields) + 4*(len(s) + 1)
857 check(s, L) 893 check(s, L)
858 # verify that the UTF-8 size is accounted for 894 # verify that the UTF-8 size is accounted for
859 s = chr(0x4000) # 4 bytes canonical representation 895 s = chr(0x4000) # 4 bytes canonical representation
860 check(s, size(compactfields) + 4) 896 check(s, size(compactfields) + 4)
861 # compile() will trigger the generation of the UTF-8 897 # compile() will trigger the generation of the UTF-8
862 # representation as a side effect 898 # representation as a side effect
863 compile(s, "<stdin>", "eval") 899 compile(s, "<stdin>", "eval")
864 check(s, size(compactfields) + 4 + 4) 900 check(s, size(compactfields) + 4 + 4)
865 # TODO: add check that forces the presence of wchar_t representation 901 # TODO: add check that forces the presence of wchar_t representation
866 # TODO: add check that forces layout of unicodefields 902 # TODO: add check that forces layout of unicodefields
867 # weakref 903 # weakref
868 import weakref 904 import weakref
869 check(weakref.ref(int), size(h + '2Pl2P')) 905 check(weakref.ref(int), size('2Pn2P'))
870 # weakproxy 906 # weakproxy
871 # XXX 907 # XXX
872 # weakcallableproxy 908 # weakcallableproxy
873 check(weakref.proxy(int), size(h + '2Pl2P')) 909 check(weakref.proxy(int), size('2Pn2P'))
874 910
875 def test_pythontypes(self): 911 def test_pythontypes(self):
876 # check all types defined in Python/ 912 # check all types defined in Python/
877 h = self.header 913 size = test.support.calcobjsize
878 vh = self.vheader 914 vsize = test.support.calcvobjsize
879 size = self.calcsize
880 check = self.check_sizeof 915 check = self.check_sizeof
881 # _ast.AST 916 # _ast.AST
882 import _ast 917 import _ast
883 check(_ast.AST(), size(h + '')) 918 check(_ast.AST(), size('P'))
884 # imp.NullImporter
885 import imp
886 check(imp.NullImporter(self.file.name), size(h + ''))
887 try: 919 try:
888 raise TypeError 920 raise TypeError
889 except TypeError: 921 except TypeError:
890 tb = sys.exc_info()[2] 922 tb = sys.exc_info()[2]
891 # traceback 923 # traceback
892 if tb != None: 924 if tb is not None:
893 check(tb, size(h + '2P2i')) 925 check(tb, size('2P2i'))
894 # symtable entry 926 # symtable entry
895 # XXX 927 # XXX
896 # sys.flags 928 # sys.flags
897 check(sys.flags, size(vh) + self.P * len(sys.flags)) 929 check(sys.flags, vsize('') + self.P * len(sys.flags))
898
899 @unittest.skipUnless(hasattr(sys, "getallocatedblocks"),
900 "sys.getallocatedblocks unavailable on this build")
901 def test_getallocatedblocks(self):
902 # Some sanity checks
903 a = sys.getallocatedblocks()
904 self.assertIs(type(a), int)
905 self.assertGreater(a, 0)
906 try:
907 # While we could imagine a Python session where the number of
908 # multiple buffer objects would exceed the sharing of references,
909 # it is unlikely to happen in a normal test run.
910 self.assertLess(a, sys.gettotalrefcount())
911 except AttributeError:
912 # gettotalrefcount() not available
913 pass
914 gc.collect()
915 b = sys.getallocatedblocks()
916 self.assertLessEqual(b, a)
917 gc.collect()
918 c = sys.getallocatedblocks()
919 self.assertIn(c, range(b - 50, b + 50))
920 930
921 931
922 def test_main(): 932 def test_main():
923 test.support.run_unittest(SysModuleTest, SizeofTest) 933 test.support.run_unittest(SysModuleTest, SizeofTest)
924 934
925 if __name__ == "__main__": 935 if __name__ == "__main__":
926 test_main() 936 test_main()
LEFTRIGHT

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