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

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

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 7 years ago
Right Patch Set: Created 5 years, 10 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_sysconfig.py ('k') | Lib/test/test_telnetlib.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 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
10 import sysconfig
11 import platform
9 12
10 # count the number of test runs, used to create unique 13 # count the number of test runs, used to create unique
11 # strings to intern in test_intern() 14 # strings to intern in test_intern()
12 numruns = 0 15 numruns = 0
13 16
14 try: 17 try:
15 import threading 18 import threading
16 except ImportError: 19 except ImportError:
17 threading = None 20 threading = None
18 21
(...skipping 211 matching lines...) Expand 10 before | Expand all | Expand 10 after
230 # Issue #5392: stack overflow after hitting recursion limit twic e 233 # Issue #5392: stack overflow after hitting recursion limit twic e
231 sys.setrecursionlimit(i) 234 sys.setrecursionlimit(i)
232 self.assertRaises(RuntimeError, f) 235 self.assertRaises(RuntimeError, f)
233 self.assertRaises(RuntimeError, f) 236 self.assertRaises(RuntimeError, f)
234 finally: 237 finally:
235 sys.setrecursionlimit(oldlimit) 238 sys.setrecursionlimit(oldlimit)
236 239
237 def test_recursionlimit_fatalerror(self): 240 def test_recursionlimit_fatalerror(self):
238 # A fatal error occurs if a second recursion limit is hit when recoverin g 241 # A fatal error occurs if a second recursion limit is hit when recoverin g
239 # from a first one. 242 # from a first one.
240 if os.name == "nt":
241 raise unittest.SkipTest(
242 "under Windows, test would generate a spurious crash dialog")
243 code = textwrap.dedent(""" 243 code = textwrap.dedent("""
244 import sys 244 import sys
245 245
246 def f(): 246 def f():
247 try: 247 try:
248 f() 248 f()
249 except RuntimeError: 249 except RuntimeError:
250 f() 250 f()
251 251
252 sys.setrecursionlimit(%d) 252 sys.setrecursionlimit(%d)
253 f()""") 253 f()""")
254 for i in (50, 1000): 254 with test.support.SuppressCrashReport():
255 sub = subprocess.Popen([sys.executable, '-c', code % i], 255 for i in (50, 1000):
256 stderr=subprocess.PIPE) 256 sub = subprocess.Popen([sys.executable, '-c', code % i],
257 err = sub.communicate()[1] 257 stderr=subprocess.PIPE)
258 self.assertTrue(sub.returncode, sub.returncode) 258 err = sub.communicate()[1]
259 self.assertTrue( 259 self.assertTrue(sub.returncode, sub.returncode)
260 b"Fatal Python error: Cannot recover from stack overflow" in err , 260 self.assertIn(
261 err) 261 b"Fatal Python error: Cannot recover from stack overflow",
262 err)
262 263
263 def test_getwindowsversion(self): 264 def test_getwindowsversion(self):
264 # Raise SkipTest if sys doesn't have getwindowsversion attribute 265 # Raise SkipTest if sys doesn't have getwindowsversion attribute
265 test.support.get_attribute(sys, "getwindowsversion") 266 test.support.get_attribute(sys, "getwindowsversion")
266 v = sys.getwindowsversion() 267 v = sys.getwindowsversion()
267 self.assertEqual(len(v), 5) 268 self.assertEqual(len(v), 5)
268 self.assertIsInstance(v[0], int) 269 self.assertIsInstance(v[0], int)
269 self.assertIsInstance(v[1], int) 270 self.assertIsInstance(v[1], int)
270 self.assertIsInstance(v[2], int) 271 self.assertIsInstance(v[2], int)
271 self.assertIsInstance(v[3], int) 272 self.assertIsInstance(v[3], int)
(...skipping 14 matching lines...) Expand all
286 self.assertEqual(v[3], v.platform) 287 self.assertEqual(v[3], v.platform)
287 self.assertEqual(v[4], v.service_pack) 288 self.assertEqual(v[4], v.service_pack)
288 289
289 # This is how platform.py calls it. Make sure tuple 290 # This is how platform.py calls it. Make sure tuple
290 # still has 5 elements 291 # still has 5 elements
291 maj, min, buildno, plat, csd = sys.getwindowsversion() 292 maj, min, buildno, plat, csd = sys.getwindowsversion()
292 293
293 def test_call_tracing(self): 294 def test_call_tracing(self):
294 self.assertRaises(TypeError, sys.call_tracing, type, 2) 295 self.assertRaises(TypeError, sys.call_tracing, type, 2)
295 296
297 @unittest.skipUnless(hasattr(sys, "setdlopenflags"),
298 'test needs sys.setdlopenflags()')
296 def test_dlopenflags(self): 299 def test_dlopenflags(self):
297 if hasattr(sys, "setdlopenflags"): 300 self.assertTrue(hasattr(sys, "getdlopenflags"))
298 self.assertTrue(hasattr(sys, "getdlopenflags")) 301 self.assertRaises(TypeError, sys.getdlopenflags, 42)
299 self.assertRaises(TypeError, sys.getdlopenflags, 42) 302 oldflags = sys.getdlopenflags()
300 oldflags = sys.getdlopenflags() 303 self.assertRaises(TypeError, sys.setdlopenflags)
301 self.assertRaises(TypeError, sys.setdlopenflags) 304 sys.setdlopenflags(oldflags+1)
302 sys.setdlopenflags(oldflags+1) 305 self.assertEqual(sys.getdlopenflags(), oldflags+1)
303 self.assertEqual(sys.getdlopenflags(), oldflags+1) 306 sys.setdlopenflags(oldflags)
304 sys.setdlopenflags(oldflags)
305 307
306 @test.support.refcount_test 308 @test.support.refcount_test
307 def test_refcount(self): 309 def test_refcount(self):
308 # n here must be a global in order for this test to pass while 310 # n here must be a global in order for this test to pass while
309 # tracing with a python function. Tracing calls PyFrame_FastToLocals 311 # tracing with a python function. Tracing calls PyFrame_FastToLocals
310 # which will add a copy of any locals to the frame object, causing 312 # which will add a copy of any locals to the frame object, causing
311 # the reference count to increase by 2 instead of 1. 313 # the reference count to increase by 2 instead of 1.
312 global n 314 global n
313 self.assertRaises(TypeError, sys.getrefcount) 315 self.assertRaises(TypeError, sys.getrefcount)
314 c = sys.getrefcount(None) 316 c = sys.getrefcount(None)
(...skipping 108 matching lines...) Expand 10 before | Expand all | Expand 10 after
423 self.assertIsInstance(sys.executable, str) 425 self.assertIsInstance(sys.executable, str)
424 self.assertEqual(len(sys.float_info), 11) 426 self.assertEqual(len(sys.float_info), 11)
425 self.assertEqual(sys.float_info.radix, 2) 427 self.assertEqual(sys.float_info.radix, 2)
426 self.assertEqual(len(sys.int_info), 2) 428 self.assertEqual(len(sys.int_info), 2)
427 self.assertEqual(sys.int_info.bits_per_digit % 5, 0) 429 self.assertEqual(sys.int_info.bits_per_digit % 5, 0)
428 self.assertGreaterEqual(sys.int_info.sizeof_digit, 1) 430 self.assertGreaterEqual(sys.int_info.sizeof_digit, 1)
429 self.assertEqual(type(sys.int_info.bits_per_digit), int) 431 self.assertEqual(type(sys.int_info.bits_per_digit), int)
430 self.assertEqual(type(sys.int_info.sizeof_digit), int) 432 self.assertEqual(type(sys.int_info.sizeof_digit), int)
431 self.assertIsInstance(sys.hexversion, int) 433 self.assertIsInstance(sys.hexversion, int)
432 434
433 self.assertEqual(len(sys.hash_info), 5) 435 self.assertEqual(len(sys.hash_info), 9)
434 self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) 436 self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width)
435 # sys.hash_info.modulus should be a prime; we do a quick 437 # sys.hash_info.modulus should be a prime; we do a quick
436 # probable primality test (doesn't exclude the possibility of 438 # probable primality test (doesn't exclude the possibility of
437 # a Carmichael number) 439 # a Carmichael number)
438 for x in range(1, 100): 440 for x in range(1, 100):
439 self.assertEqual( 441 self.assertEqual(
440 pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), 442 pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus),
441 1, 443 1,
442 "sys.hash_info.modulus {} is a non-prime".format( 444 "sys.hash_info.modulus {} is a non-prime".format(
443 sys.hash_info.modulus) 445 sys.hash_info.modulus)
444 ) 446 )
445 self.assertIsInstance(sys.hash_info.inf, int) 447 self.assertIsInstance(sys.hash_info.inf, int)
446 self.assertIsInstance(sys.hash_info.nan, int) 448 self.assertIsInstance(sys.hash_info.nan, int)
447 self.assertIsInstance(sys.hash_info.imag, int) 449 self.assertIsInstance(sys.hash_info.imag, int)
450 algo = sysconfig.get_config_var("Py_HASH_ALGORITHM")
451 if sys.hash_info.algorithm in {"fnv", "siphash24"}:
452 self.assertIn(sys.hash_info.hash_bits, {32, 64})
453 self.assertIn(sys.hash_info.seed_bits, {32, 64, 128})
454
455 if algo == 1:
456 self.assertEqual(sys.hash_info.algorithm, "siphash24")
457 elif algo == 2:
458 self.assertEqual(sys.hash_info.algorithm, "fnv")
459 else:
460 self.assertIn(sys.hash_info.algorithm, {"fnv", "siphash24"})
461 else:
462 # PY_HASH_EXTERNAL
463 self.assertEqual(algo, 0)
464 self.assertGreaterEqual(sys.hash_info.cutoff, 0)
465 self.assertLess(sys.hash_info.cutoff, 8)
448 466
449 self.assertIsInstance(sys.maxsize, int) 467 self.assertIsInstance(sys.maxsize, int)
450 self.assertIsInstance(sys.maxunicode, int) 468 self.assertIsInstance(sys.maxunicode, int)
451 self.assertEqual(sys.maxunicode, 0x10FFFF) 469 self.assertEqual(sys.maxunicode, 0x10FFFF)
452 self.assertIsInstance(sys.platform, str) 470 self.assertIsInstance(sys.platform, str)
453 self.assertIsInstance(sys.prefix, str) 471 self.assertIsInstance(sys.prefix, str)
454 self.assertIsInstance(sys.base_prefix, str) 472 self.assertIsInstance(sys.base_prefix, str)
455 self.assertIsInstance(sys.version, str) 473 self.assertIsInstance(sys.version, str)
456 vi = sys.version_info 474 vi = sys.version_info
457 self.assertIsInstance(vi[:], tuple) 475 self.assertIsInstance(vi[:], tuple)
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
508 def __hash__(self): 526 def __hash__(self):
509 return 123 527 return 123
510 528
511 self.assertRaises(TypeError, sys.intern, S("abc")) 529 self.assertRaises(TypeError, sys.intern, S("abc"))
512 530
513 def test_sys_flags(self): 531 def test_sys_flags(self):
514 self.assertTrue(sys.flags) 532 self.assertTrue(sys.flags)
515 attrs = ("debug", 533 attrs = ("debug",
516 "inspect", "interactive", "optimize", "dont_write_bytecode", 534 "inspect", "interactive", "optimize", "dont_write_bytecode",
517 "no_user_site", "no_site", "ignore_environment", "verbose", 535 "no_user_site", "no_site", "ignore_environment", "verbose",
518 "bytes_warning", "quiet", "hash_randomization") 536 "bytes_warning", "quiet", "hash_randomization", "isolated")
519 for attr in attrs: 537 for attr in attrs:
520 self.assertTrue(hasattr(sys.flags, attr), attr) 538 self.assertTrue(hasattr(sys.flags, attr), attr)
521 self.assertEqual(type(getattr(sys.flags, attr)), int, attr) 539 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
522 self.assertTrue(repr(sys.flags)) 540 self.assertTrue(repr(sys.flags))
523 self.assertEqual(len(sys.flags), len(attrs)) 541 self.assertEqual(len(sys.flags), len(attrs))
524 542
525 def test_clear_type_cache(self): 543 def test_clear_type_cache(self):
526 sys._clear_type_cache() 544 sys._clear_type_cache()
527 545
528 def test_ioencoding(self): 546 def test_ioencoding(self):
529 env = dict(os.environ) 547 env = dict(os.environ)
530 548
531 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, 549 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
532 # not representable in ASCII. 550 # not representable in ASCII.
533 551
534 env["PYTHONIOENCODING"] = "cp424" 552 env["PYTHONIOENCODING"] = "cp424"
535 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], 553 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
536 stdout = subprocess.PIPE, env=env) 554 stdout = subprocess.PIPE, env=env)
537 out = p.communicate()[0].strip() 555 out = p.communicate()[0].strip()
538 expected = ("\xa2" + os.linesep).encode("cp424") 556 expected = ("\xa2" + os.linesep).encode("cp424")
539 self.assertEqual(out, expected) 557 self.assertEqual(out, expected)
540 558
541 env["PYTHONIOENCODING"] = "ascii:replace" 559 env["PYTHONIOENCODING"] = "ascii:replace"
542 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], 560 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
543 stdout = subprocess.PIPE, env=env) 561 stdout = subprocess.PIPE, env=env)
544 out = p.communicate()[0].strip() 562 out = p.communicate()[0].strip()
545 self.assertEqual(out, b'?') 563 self.assertEqual(out, b'?')
564
565 env["PYTHONIOENCODING"] = "ascii"
566 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
567 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
568 env=env)
569 out, err = p.communicate()
570 self.assertEqual(out, b'')
571 self.assertIn(b'UnicodeEncodeError:', err)
572 self.assertIn(rb"'\xa2'", err)
573
574 env["PYTHONIOENCODING"] = "ascii:"
575 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
576 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
577 env=env)
578 out, err = p.communicate()
579 self.assertEqual(out, b'')
580 self.assertIn(b'UnicodeEncodeError:', err)
581 self.assertIn(rb"'\xa2'", err)
582
583 env["PYTHONIOENCODING"] = ":surrogateescape"
584 p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xdcbd))'],
585 stdout=subprocess.PIPE, env=env)
586 out = p.communicate()[0].strip()
587 self.assertEqual(out, b'\xbd')
588
589 @unittest.skipUnless(test.support.FS_NONASCII,
590 'requires OS support of non-ASCII encodings')
591 def test_ioencoding_nonascii(self):
592 env = dict(os.environ)
593
594 env["PYTHONIOENCODING"] = ""
595 p = subprocess.Popen([sys.executable, "-c",
596 'print(%a)' % test.support.FS_NONASCII],
597 stdout=subprocess.PIPE, env=env)
598 out = p.communicate()[0].strip()
599 self.assertEqual(out, os.fsencode(test.support.FS_NONASCII))
546 600
547 @unittest.skipIf(sys.base_prefix != sys.prefix, 601 @unittest.skipIf(sys.base_prefix != sys.prefix,
548 'Test is not venv-compatible') 602 'Test is not venv-compatible')
549 def test_executable(self): 603 def test_executable(self):
550 # sys.executable should be absolute 604 # sys.executable should be absolute
551 self.assertEqual(os.path.abspath(sys.executable), sys.executable) 605 self.assertEqual(os.path.abspath(sys.executable), sys.executable)
552 606
553 # Issue #7774: Ensure that sys.executable is an empty string if argv[0] 607 # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
554 # has been set to an non existent program name and Python is unable to 608 # has been set to an non existent program name and Python is unable to
555 # retrieve the real program name 609 # retrieve the real program name
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after
604 self.assertEqual(sys.implementation.name, 658 self.assertEqual(sys.implementation.name,
605 sys.implementation.name.lower()) 659 sys.implementation.name.lower())
606 660
607 def test_debugmallocstats(self): 661 def test_debugmallocstats(self):
608 # Test sys._debugmallocstats() 662 # Test sys._debugmallocstats()
609 from test.script_helper import assert_python_ok 663 from test.script_helper import assert_python_ok
610 args = ['-c', 'import sys; sys._debugmallocstats()'] 664 args = ['-c', 'import sys; sys._debugmallocstats()']
611 ret, out, err = assert_python_ok(*args) 665 ret, out, err = assert_python_ok(*args)
612 self.assertIn(b"free PyDictObjects", err) 666 self.assertIn(b"free PyDictObjects", err)
613 667
668 # The function has no parameter
669 self.assertRaises(TypeError, sys._debugmallocstats, True)
670
671 @unittest.skipUnless(hasattr(sys, "getallocatedblocks"),
672 "sys.getallocatedblocks unavailable on this build")
673 def test_getallocatedblocks(self):
674 # Some sanity checks
675 with_pymalloc = sysconfig.get_config_var('WITH_PYMALLOC')
676 a = sys.getallocatedblocks()
677 self.assertIs(type(a), int)
678 if with_pymalloc:
679 self.assertGreater(a, 0)
680 else:
681 # When WITH_PYMALLOC isn't available, we don't know anything
682 # about the underlying implementation: the function might
683 # return 0 or something greater.
684 self.assertGreaterEqual(a, 0)
685 try:
686 # While we could imagine a Python session where the number of
687 # multiple buffer objects would exceed the sharing of references,
688 # it is unlikely to happen in a normal test run.
689 self.assertLess(a, sys.gettotalrefcount())
690 except AttributeError:
691 # gettotalrefcount() not available
692 pass
693 gc.collect()
694 b = sys.getallocatedblocks()
695 self.assertLessEqual(b, a)
696 gc.collect()
697 c = sys.getallocatedblocks()
698 self.assertIn(c, range(b - 50, b + 50))
699
700
701 @test.support.cpython_only
614 class SizeofTest(unittest.TestCase): 702 class SizeofTest(unittest.TestCase):
615 703
616 def setUp(self): 704 def setUp(self):
617 self.P = struct.calcsize('P') 705 self.P = struct.calcsize('P')
618 self.longdigit = sys.int_info.sizeof_digit 706 self.longdigit = sys.int_info.sizeof_digit
619 import _testcapi 707 import _testcapi
620 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD 708 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
621 self.file = open(test.support.TESTFN, 'wb') 709 self.file = open(test.support.TESTFN, 'wb')
622 710
623 def tearDown(self): 711 def tearDown(self):
(...skipping 24 matching lines...) Expand all
648 # bool 736 # bool
649 check(True, vsize('') + self.longdigit) 737 check(True, vsize('') + self.longdigit)
650 # buffer 738 # buffer
651 # XXX 739 # XXX
652 # builtin_function_or_method 740 # builtin_function_or_method
653 check(len, size('3P')) # XXX check layout 741 check(len, size('3P')) # XXX check layout
654 # bytearray 742 # bytearray
655 samples = [b'', b'u'*100000] 743 samples = [b'', b'u'*100000]
656 for sample in samples: 744 for sample in samples:
657 x = bytearray(sample) 745 x = bytearray(sample)
658 check(x, vsize('inP') + x.__alloc__()) 746 check(x, vsize('n2Pi') + x.__alloc__())
659 # bytearray_iterator 747 # bytearray_iterator
660 check(iter(bytearray()), size('nP')) 748 check(iter(bytearray()), size('nP'))
661 # cell 749 # cell
662 def get_cell(): 750 def get_cell():
663 x = 42 751 x = 42
664 def inner(): 752 def inner():
665 return x 753 return x
666 return inner 754 return inner
667 check(get_cell().__closure__[0], size('P')) 755 check(get_cell().__closure__[0], size('P'))
668 # code 756 # code
(...skipping 29 matching lines...) Expand all
698 # dictionary-valueiterator 786 # dictionary-valueiterator
699 check({}.values(), size('P')) 787 check({}.values(), size('P'))
700 # dictionary-itemiterator 788 # dictionary-itemiterator
701 check({}.items(), size('P')) 789 check({}.items(), size('P'))
702 # dictionary iterator 790 # dictionary iterator
703 check(iter({}), size('P2nPn')) 791 check(iter({}), size('P2nPn'))
704 # dictproxy 792 # dictproxy
705 class C(object): pass 793 class C(object): pass
706 check(C.__dict__, size('P')) 794 check(C.__dict__, size('P'))
707 # BaseException 795 # BaseException
708 check(BaseException(), size('5Pi')) 796 check(BaseException(), size('5Pb'))
709 # UnicodeEncodeError 797 # UnicodeEncodeError
710 check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pi 2P2nP')) 798 check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pb 2P2nP'))
711 # UnicodeDecodeError 799 # UnicodeDecodeError
712 check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pi 2P2nP')) 800 check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pb 2P2nP'))
713 # UnicodeTranslateError 801 # UnicodeTranslateError
714 check(UnicodeTranslateError("", 0, 1, ""), size('5Pi 2P2nP')) 802 check(UnicodeTranslateError("", 0, 1, ""), size('5Pb 2P2nP'))
715 # ellipses 803 # ellipses
716 check(Ellipsis, size('')) 804 check(Ellipsis, size(''))
717 # EncodingMap 805 # EncodingMap
718 import codecs, encodings.iso8859_3 806 import codecs, encodings.iso8859_3
719 x = codecs.charmap_build(encodings.iso8859_3.decoding_table) 807 x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
720 check(x, size('32B2iB')) 808 check(x, size('32B2iB'))
721 # enumerate 809 # enumerate
722 check(enumerate([]), size('n3P')) 810 check(enumerate([]), size('n3P'))
723 # reverse 811 # reverse
724 check(reversed(''), size('nP')) 812 check(reversed(''), size('nP'))
725 # float 813 # float
726 check(float(0), size('d')) 814 check(float(0), size('d'))
727 # sys.floatinfo 815 # sys.floatinfo
728 check(sys.float_info, vsize('') + self.P * len(sys.float_info)) 816 check(sys.float_info, vsize('') + self.P * len(sys.float_info))
729 # frame 817 # frame
730 import inspect 818 import inspect
731 CO_MAXBLOCKS = 20 819 CO_MAXBLOCKS = 20
732 x = inspect.currentframe() 820 x = inspect.currentframe()
733 ncells = len(x.f_code.co_cellvars) 821 ncells = len(x.f_code.co_cellvars)
734 nfrees = len(x.f_code.co_freevars) 822 nfrees = len(x.f_code.co_freevars)
735 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ 823 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
736 ncells + nfrees - 1 824 ncells + nfrees - 1
737 check(x, vsize('12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P')) 825 check(x, vsize('12P3ic' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
738 # function 826 # function
739 def func(): pass 827 def func(): pass
740 check(func, size('12P')) 828 check(func, size('12P'))
741 class c(): 829 class c():
742 @staticmethod 830 @staticmethod
743 def foo(): 831 def foo():
744 pass 832 pass
745 @classmethod 833 @classmethod
746 def bar(cls): 834 def bar(cls):
747 pass 835 pass
(...skipping 14 matching lines...) Expand all
762 for sample in samples: 850 for sample in samples:
763 check(sample, vsize('Pn') + len(sample)*self.P) 851 check(sample, vsize('Pn') + len(sample)*self.P)
764 # sortwrapper (list) 852 # sortwrapper (list)
765 # XXX 853 # XXX
766 # cmpwrapper (list) 854 # cmpwrapper (list)
767 # XXX 855 # XXX
768 # listiterator (list) 856 # listiterator (list)
769 check(iter([]), size('lP')) 857 check(iter([]), size('lP'))
770 # listreverseiterator (list) 858 # listreverseiterator (list)
771 check(reversed([]), size('nP')) 859 check(reversed([]), size('nP'))
772 # long 860 # int
773 check(0, vsize('')) 861 check(0, vsize(''))
774 check(1, vsize('') + self.longdigit) 862 check(1, vsize('') + self.longdigit)
775 check(-1, vsize('') + self.longdigit) 863 check(-1, vsize('') + self.longdigit)
776 PyLong_BASE = 2**sys.int_info.bits_per_digit 864 PyLong_BASE = 2**sys.int_info.bits_per_digit
777 check(int(PyLong_BASE), vsize('') + 2*self.longdigit) 865 check(int(PyLong_BASE), vsize('') + 2*self.longdigit)
778 check(int(PyLong_BASE**2-1), vsize('') + 2*self.longdigit) 866 check(int(PyLong_BASE**2-1), vsize('') + 2*self.longdigit)
779 check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit) 867 check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit)
780 # memoryview 868 # memoryview
781 check(memoryview(b''), size('Pnin 2P2n2i5P 3cPn')) 869 check(memoryview(b''), size('Pnin 2P2n2i5P 3cPn'))
782 # module 870 # module
783 check(unittest, size('PnP')) 871 check(unittest, size('PnPPP'))
784 # None 872 # None
785 check(None, size('')) 873 check(None, size(''))
786 # NotImplementedType 874 # NotImplementedType
787 check(NotImplemented, size('')) 875 check(NotImplemented, size(''))
788 # object 876 # object
789 check(object(), size('')) 877 check(object(), size(''))
790 # property (descriptor object) 878 # property (descriptor object)
791 class C(object): 879 class C(object):
792 def getx(self): return self.__x 880 def getx(self): return self.__x
793 def setx(self, value): self.__x = value 881 def setx(self, value): self.__x = value
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
827 check(iter(set()), size('P3n')) 915 check(iter(set()), size('P3n'))
828 # slice 916 # slice
829 check(slice(0), size('3P')) 917 check(slice(0), size('3P'))
830 # super 918 # super
831 check(super(int), size('3P')) 919 check(super(int), size('3P'))
832 # tuple 920 # tuple
833 check((), vsize('')) 921 check((), vsize(''))
834 check((1,2,3), vsize('') + 3*self.P) 922 check((1,2,3), vsize('') + 3*self.P)
835 # type 923 # type
836 # static type: PyTypeObject 924 # static type: PyTypeObject
837 s = vsize('P2n15Pl4Pn9Pn11PI') 925 s = vsize('P2n15Pl4Pn9Pn11PIP')
838 check(int, s) 926 check(int, s)
839 # (PyTypeObject + PyNumberMethods + PyMappingMethods + 927 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
840 # PySequenceMethods + PyBufferProcs + 4P) 928 # PySequenceMethods + PyBufferProcs + 4P)
841 s = vsize('P2n15Pl4Pn9Pn11PI') + struct.calcsize('34P 3P 10P 2P 4P') 929 s = vsize('P2n15Pl4Pn9Pn11PIP') + struct.calcsize('34P 3P 10P 2P 4P')
842 # Separate block for PyDictKeysObject with 4 entries 930 # Separate block for PyDictKeysObject with 4 entries
843 s += struct.calcsize("2nPn") + 4*struct.calcsize("n2P") 931 s += struct.calcsize("2nPn") + 4*struct.calcsize("n2P")
844 # class 932 # class
845 class newstyleclass(object): pass 933 class newstyleclass(object): pass
846 check(newstyleclass, s) 934 check(newstyleclass, s)
847 # dict with shared keys 935 # dict with shared keys
848 check(newstyleclass().__dict__, size('n2P' + '2nPn')) 936 check(newstyleclass().__dict__, size('n2P' + '2nPn'))
849 # unicode 937 # unicode
850 # each tuple contains a string and its expected character size 938 # each tuple contains a string and its expected character size
851 # don't put any static strings here, as they may contain 939 # don't put any static strings here, as they may contain
852 # wchar_t or UTF-8 representations 940 # wchar_t or UTF-8 representations
853 samples = ['1'*100, '\xff'*50, 941 samples = ['1'*100, '\xff'*50,
854 '\u0100'*40, '\uffff'*100, 942 '\u0100'*40, '\uffff'*100,
855 '\U00010000'*30, '\U0010ffff'*100] 943 '\U00010000'*30, '\U0010ffff'*100]
856 asciifields = "nniP" 944 asciifields = "nnbP"
857 compactfields = asciifields + "nPn" 945 compactfields = asciifields + "nPn"
858 unicodefields = compactfields + "P" 946 unicodefields = compactfields + "P"
859 for s in samples: 947 for s in samples:
860 maxchar = ord(max(s)) 948 maxchar = ord(max(s))
861 if maxchar < 128: 949 if maxchar < 128:
862 L = size(asciifields) + len(s) + 1 950 L = size(asciifields) + len(s) + 1
863 elif maxchar < 256: 951 elif maxchar < 256:
864 L = size(compactfields) + len(s) + 1 952 L = size(compactfields) + len(s) + 1
865 elif maxchar < 65536: 953 elif maxchar < 65536:
866 L = size(compactfields) + 2*(len(s) + 1) 954 L = size(compactfields) + 2*(len(s) + 1)
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
903 # XXX 991 # XXX
904 # sys.flags 992 # sys.flags
905 check(sys.flags, vsize('') + self.P * len(sys.flags)) 993 check(sys.flags, vsize('') + self.P * len(sys.flags))
906 994
907 995
908 def test_main(): 996 def test_main():
909 test.support.run_unittest(SysModuleTest, SizeofTest) 997 test.support.run_unittest(SysModuleTest, SizeofTest)
910 998
911 if __name__ == "__main__": 999 if __name__ == "__main__":
912 test_main() 1000 test_main()
LEFTRIGHT

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