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

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

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

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