Home | History | Annotate | Download | only in test
      1 # -*- coding: iso-8859-1 -*-
      2 import unittest, test.test_support
      3 from test.script_helper import assert_python_ok, assert_python_failure
      4 import cStringIO
      5 import gc
      6 import operator
      7 import os
      8 import struct
      9 import sys
     10 
     11 class SysModuleTest(unittest.TestCase):
     12 
     13     def tearDown(self):
     14         test.test_support.reap_children()
     15 
     16     def test_original_displayhook(self):
     17         import __builtin__
     18         savestdout = sys.stdout
     19         out = cStringIO.StringIO()
     20         sys.stdout = out
     21 
     22         dh = sys.__displayhook__
     23 
     24         self.assertRaises(TypeError, dh)
     25         if hasattr(__builtin__, "_"):
     26             del __builtin__._
     27 
     28         dh(None)
     29         self.assertEqual(out.getvalue(), "")
     30         self.assertTrue(not hasattr(__builtin__, "_"))
     31         dh(42)
     32         self.assertEqual(out.getvalue(), "42\n")
     33         self.assertEqual(__builtin__._, 42)
     34 
     35         del sys.stdout
     36         self.assertRaises(RuntimeError, dh, 42)
     37 
     38         sys.stdout = savestdout
     39 
     40     def test_lost_displayhook(self):
     41         olddisplayhook = sys.displayhook
     42         del sys.displayhook
     43         code = compile("42", "<string>", "single")
     44         self.assertRaises(RuntimeError, eval, code)
     45         sys.displayhook = olddisplayhook
     46 
     47     def test_custom_displayhook(self):
     48         olddisplayhook = sys.displayhook
     49         def baddisplayhook(obj):
     50             raise ValueError
     51         sys.displayhook = baddisplayhook
     52         code = compile("42", "<string>", "single")
     53         self.assertRaises(ValueError, eval, code)
     54         sys.displayhook = olddisplayhook
     55 
     56     def test_original_excepthook(self):
     57         savestderr = sys.stderr
     58         err = cStringIO.StringIO()
     59         sys.stderr = err
     60 
     61         eh = sys.__excepthook__
     62 
     63         self.assertRaises(TypeError, eh)
     64         try:
     65             raise ValueError(42)
     66         except ValueError, exc:
     67             eh(*sys.exc_info())
     68 
     69         sys.stderr = savestderr
     70         self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))
     71 
     72     # FIXME: testing the code for a lost or replaced excepthook in
     73     # Python/pythonrun.c::PyErr_PrintEx() is tricky.
     74 
     75     def test_exc_clear(self):
     76         self.assertRaises(TypeError, sys.exc_clear, 42)
     77 
     78         # Verify that exc_info is present and matches exc, then clear it, and
     79         # check that it worked.
     80         def clear_check(exc):
     81             typ, value, traceback = sys.exc_info()
     82             self.assertTrue(typ is not None)
     83             self.assertTrue(value is exc)
     84             self.assertTrue(traceback is not None)
     85 
     86             with test.test_support.check_py3k_warnings():
     87                 sys.exc_clear()
     88 
     89             typ, value, traceback = sys.exc_info()
     90             self.assertTrue(typ is None)
     91             self.assertTrue(value is None)
     92             self.assertTrue(traceback is None)
     93 
     94         def clear():
     95             try:
     96                 raise ValueError, 42
     97             except ValueError, exc:
     98                 clear_check(exc)
     99 
    100         # Raise an exception and check that it can be cleared
    101         clear()
    102 
    103         # Verify that a frame currently handling an exception is
    104         # unaffected by calling exc_clear in a nested frame.
    105         try:
    106             raise ValueError, 13
    107         except ValueError, exc:
    108             typ1, value1, traceback1 = sys.exc_info()
    109             clear()
    110             typ2, value2, traceback2 = sys.exc_info()
    111 
    112             self.assertTrue(typ1 is typ2)
    113             self.assertTrue(value1 is exc)
    114             self.assertTrue(value1 is value2)
    115             self.assertTrue(traceback1 is traceback2)
    116 
    117         # Check that an exception can be cleared outside of an except block
    118         clear_check(exc)
    119 
    120     def test_exit(self):
    121         # call with two arguments
    122         self.assertRaises(TypeError, sys.exit, 42, 42)
    123 
    124         # call without argument
    125         with self.assertRaises(SystemExit) as cm:
    126             sys.exit()
    127         self.assertIsNone(cm.exception.code)
    128 
    129         rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()')
    130         self.assertEqual(rc, 0)
    131         self.assertEqual(out, b'')
    132         self.assertEqual(err, b'')
    133 
    134         # call with integer argument
    135         with self.assertRaises(SystemExit) as cm:
    136             sys.exit(42)
    137         self.assertEqual(cm.exception.code, 42)
    138 
    139         # call with tuple argument with one entry
    140         # entry will be unpacked
    141         with self.assertRaises(SystemExit) as cm:
    142             sys.exit((42,))
    143         self.assertEqual(cm.exception.code, 42)
    144 
    145         # call with string argument
    146         with self.assertRaises(SystemExit) as cm:
    147             sys.exit("exit")
    148         self.assertEqual(cm.exception.code, "exit")
    149 
    150         # call with tuple argument with two entries
    151         with self.assertRaises(SystemExit) as cm:
    152             sys.exit((17, 23))
    153         self.assertEqual(cm.exception.code, (17, 23))
    154 
    155         # test that the exit machinery handles SystemExits properly
    156         # both unnormalized...
    157         rc, out, err = assert_python_failure('-c', 'raise SystemExit, 46')
    158         self.assertEqual(rc, 46)
    159         self.assertEqual(out, b'')
    160         self.assertEqual(err, b'')
    161         # ... and normalized
    162         rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)')
    163         self.assertEqual(rc, 47)
    164         self.assertEqual(out, b'')
    165         self.assertEqual(err, b'')
    166 
    167         def check_exit_message(code, expected, **env_vars):
    168             rc, out, err = assert_python_failure('-c', code, **env_vars)
    169             self.assertEqual(rc, 1)
    170             self.assertEqual(out, b'')
    171             self.assertTrue(err.startswith(expected),
    172                 "%s doesn't start with %s" % (repr(err), repr(expected)))
    173 
    174         # test that stderr buffer is flushed before the exit message is written
    175         # into stderr
    176         check_exit_message(
    177             r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
    178             b"unflushed,message")
    179 
    180         # test that the unicode message is encoded to the stderr encoding
    181         check_exit_message(
    182             r'import sys; sys.exit(u"h\xe9")',
    183             b"h\xe9", PYTHONIOENCODING='latin-1')
    184 
    185     def test_getdefaultencoding(self):
    186         if test.test_support.have_unicode:
    187             self.assertRaises(TypeError, sys.getdefaultencoding, 42)
    188             # can't check more than the type, as the user might have changed it
    189             self.assertIsInstance(sys.getdefaultencoding(), str)
    190 
    191     # testing sys.settrace() is done in test_sys_settrace.py
    192     # testing sys.setprofile() is done in test_sys_setprofile.py
    193 
    194     def test_setcheckinterval(self):
    195         self.assertRaises(TypeError, sys.setcheckinterval)
    196         orig = sys.getcheckinterval()
    197         for n in 0, 100, 120, orig: # orig last to restore starting state
    198             sys.setcheckinterval(n)
    199             self.assertEqual(sys.getcheckinterval(), n)
    200 
    201     def test_recursionlimit(self):
    202         self.assertRaises(TypeError, sys.getrecursionlimit, 42)
    203         oldlimit = sys.getrecursionlimit()
    204         self.assertRaises(TypeError, sys.setrecursionlimit)
    205         self.assertRaises(ValueError, sys.setrecursionlimit, -42)
    206         sys.setrecursionlimit(10000)
    207         self.assertEqual(sys.getrecursionlimit(), 10000)
    208         sys.setrecursionlimit(oldlimit)
    209 
    210         self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
    211         try:
    212             sys.setrecursionlimit((1 << 31) - 5)
    213             try:
    214                 # issue13546: isinstance(e, ValueError) used to fail
    215                 # when the recursion limit is close to 1<<31
    216                 raise ValueError()
    217             except ValueError, e:
    218                 pass
    219         finally:
    220             sys.setrecursionlimit(oldlimit)
    221 
    222     def test_getwindowsversion(self):
    223         # Raise SkipTest if sys doesn't have getwindowsversion attribute
    224         test.test_support.get_attribute(sys, "getwindowsversion")
    225         v = sys.getwindowsversion()
    226         self.assertEqual(len(v), 5)
    227         self.assertIsInstance(v[0], int)
    228         self.assertIsInstance(v[1], int)
    229         self.assertIsInstance(v[2], int)
    230         self.assertIsInstance(v[3], int)
    231         self.assertIsInstance(v[4], str)
    232         self.assertRaises(IndexError, operator.getitem, v, 5)
    233         self.assertIsInstance(v.major, int)
    234         self.assertIsInstance(v.minor, int)
    235         self.assertIsInstance(v.build, int)
    236         self.assertIsInstance(v.platform, int)
    237         self.assertIsInstance(v.service_pack, str)
    238         self.assertIsInstance(v.service_pack_minor, int)
    239         self.assertIsInstance(v.service_pack_major, int)
    240         self.assertIsInstance(v.suite_mask, int)
    241         self.assertIsInstance(v.product_type, int)
    242         self.assertEqual(v[0], v.major)
    243         self.assertEqual(v[1], v.minor)
    244         self.assertEqual(v[2], v.build)
    245         self.assertEqual(v[3], v.platform)
    246         self.assertEqual(v[4], v.service_pack)
    247 
    248         # This is how platform.py calls it. Make sure tuple
    249         #  still has 5 elements
    250         maj, min, buildno, plat, csd = sys.getwindowsversion()
    251 
    252     @unittest.skipUnless(hasattr(sys, "setdlopenflags"),
    253                          'test needs sys.setdlopenflags()')
    254     def test_dlopenflags(self):
    255         self.assertTrue(hasattr(sys, "getdlopenflags"))
    256         self.assertRaises(TypeError, sys.getdlopenflags, 42)
    257         oldflags = sys.getdlopenflags()
    258         self.assertRaises(TypeError, sys.setdlopenflags)
    259         sys.setdlopenflags(oldflags+1)
    260         self.assertEqual(sys.getdlopenflags(), oldflags+1)
    261         sys.setdlopenflags(oldflags)
    262 
    263     def test_refcount(self):
    264         # n here must be a global in order for this test to pass while
    265         # tracing with a python function.  Tracing calls PyFrame_FastToLocals
    266         # which will add a copy of any locals to the frame object, causing
    267         # the reference count to increase by 2 instead of 1.
    268         global n
    269         self.assertRaises(TypeError, sys.getrefcount)
    270         c = sys.getrefcount(None)
    271         n = None
    272         self.assertEqual(sys.getrefcount(None), c+1)
    273         del n
    274         self.assertEqual(sys.getrefcount(None), c)
    275         if hasattr(sys, "gettotalrefcount"):
    276             self.assertIsInstance(sys.gettotalrefcount(), int)
    277 
    278     def test_getframe(self):
    279         self.assertRaises(TypeError, sys._getframe, 42, 42)
    280         self.assertRaises(ValueError, sys._getframe, 2000000000)
    281         self.assertTrue(
    282             SysModuleTest.test_getframe.im_func.func_code \
    283             is sys._getframe().f_code
    284         )
    285 
    286     # sys._current_frames() is a CPython-only gimmick.
    287     def test_current_frames(self):
    288         have_threads = True
    289         try:
    290             import thread
    291         except ImportError:
    292             have_threads = False
    293 
    294         if have_threads:
    295             self.current_frames_with_threads()
    296         else:
    297             self.current_frames_without_threads()
    298 
    299     # Test sys._current_frames() in a WITH_THREADS build.
    300     @test.test_support.reap_threads
    301     def current_frames_with_threads(self):
    302         import threading, thread
    303         import traceback
    304 
    305         # Spawn a thread that blocks at a known place.  Then the main
    306         # thread does sys._current_frames(), and verifies that the frames
    307         # returned make sense.
    308         entered_g = threading.Event()
    309         leave_g = threading.Event()
    310         thread_info = []  # the thread's id
    311 
    312         def f123():
    313             g456()
    314 
    315         def g456():
    316             thread_info.append(thread.get_ident())
    317             entered_g.set()
    318             leave_g.wait()
    319 
    320         t = threading.Thread(target=f123)
    321         t.start()
    322         entered_g.wait()
    323 
    324         # At this point, t has finished its entered_g.set(), although it's
    325         # impossible to guess whether it's still on that line or has moved on
    326         # to its leave_g.wait().
    327         self.assertEqual(len(thread_info), 1)
    328         thread_id = thread_info[0]
    329 
    330         d = sys._current_frames()
    331 
    332         main_id = thread.get_ident()
    333         self.assertIn(main_id, d)
    334         self.assertIn(thread_id, d)
    335 
    336         # Verify that the captured main-thread frame is _this_ frame.
    337         frame = d.pop(main_id)
    338         self.assertTrue(frame is sys._getframe())
    339 
    340         # Verify that the captured thread frame is blocked in g456, called
    341         # from f123.  This is a litte tricky, since various bits of
    342         # threading.py are also in the thread's call stack.
    343         frame = d.pop(thread_id)
    344         stack = traceback.extract_stack(frame)
    345         for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
    346             if funcname == "f123":
    347                 break
    348         else:
    349             self.fail("didn't find f123() on thread's call stack")
    350 
    351         self.assertEqual(sourceline, "g456()")
    352 
    353         # And the next record must be for g456().
    354         filename, lineno, funcname, sourceline = stack[i+1]
    355         self.assertEqual(funcname, "g456")
    356         self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
    357 
    358         # Reap the spawned thread.
    359         leave_g.set()
    360         t.join()
    361 
    362     # Test sys._current_frames() when thread support doesn't exist.
    363     def current_frames_without_threads(self):
    364         # Not much happens here:  there is only one thread, with artificial
    365         # "thread id" 0.
    366         d = sys._current_frames()
    367         self.assertEqual(len(d), 1)
    368         self.assertIn(0, d)
    369         self.assertTrue(d[0] is sys._getframe())
    370 
    371     def test_attributes(self):
    372         self.assertIsInstance(sys.api_version, int)
    373         self.assertIsInstance(sys.argv, list)
    374         self.assertIn(sys.byteorder, ("little", "big"))
    375         self.assertIsInstance(sys.builtin_module_names, tuple)
    376         self.assertIsInstance(sys.copyright, basestring)
    377         self.assertIsInstance(sys.exec_prefix, basestring)
    378         self.assertIsInstance(sys.executable, basestring)
    379         self.assertEqual(len(sys.float_info), 11)
    380         self.assertEqual(sys.float_info.radix, 2)
    381         self.assertEqual(len(sys.long_info), 2)
    382         self.assertTrue(sys.long_info.bits_per_digit % 5 == 0)
    383         self.assertTrue(sys.long_info.sizeof_digit >= 1)
    384         self.assertEqual(type(sys.long_info.bits_per_digit), int)
    385         self.assertEqual(type(sys.long_info.sizeof_digit), int)
    386         self.assertIsInstance(sys.hexversion, int)
    387         self.assertIsInstance(sys.maxint, int)
    388         if test.test_support.have_unicode:
    389             self.assertIsInstance(sys.maxunicode, int)
    390         self.assertIsInstance(sys.platform, basestring)
    391         self.assertIsInstance(sys.prefix, basestring)
    392         self.assertIsInstance(sys.version, basestring)
    393         vi = sys.version_info
    394         self.assertIsInstance(vi[:], tuple)
    395         self.assertEqual(len(vi), 5)
    396         self.assertIsInstance(vi[0], int)
    397         self.assertIsInstance(vi[1], int)
    398         self.assertIsInstance(vi[2], int)
    399         self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
    400         self.assertIsInstance(vi[4], int)
    401         self.assertIsInstance(vi.major, int)
    402         self.assertIsInstance(vi.minor, int)
    403         self.assertIsInstance(vi.micro, int)
    404         self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
    405         self.assertIsInstance(vi.serial, int)
    406         self.assertEqual(vi[0], vi.major)
    407         self.assertEqual(vi[1], vi.minor)
    408         self.assertEqual(vi[2], vi.micro)
    409         self.assertEqual(vi[3], vi.releaselevel)
    410         self.assertEqual(vi[4], vi.serial)
    411         self.assertTrue(vi > (1,0,0))
    412         self.assertIsInstance(sys.float_repr_style, str)
    413         self.assertIn(sys.float_repr_style, ('short', 'legacy'))
    414 
    415     def test_43581(self):
    416         # Can't use sys.stdout, as this is a cStringIO object when
    417         # the test runs under regrtest.
    418         if not (os.environ.get('PYTHONIOENCODING') or
    419                 (sys.__stdout__.isatty() and sys.__stderr__.isatty())):
    420             self.skipTest('stdout/stderr encoding is not set')
    421         self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding)
    422 
    423     def test_sys_flags(self):
    424         self.assertTrue(sys.flags)
    425         attrs = ("debug", "py3k_warning", "division_warning", "division_new",
    426                  "inspect", "interactive", "optimize", "dont_write_bytecode",
    427                  "no_site", "ignore_environment", "tabcheck", "verbose",
    428                  "unicode", "bytes_warning", "hash_randomization")
    429         for attr in attrs:
    430             self.assertTrue(hasattr(sys.flags, attr), attr)
    431             self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
    432         self.assertTrue(repr(sys.flags))
    433 
    434     @test.test_support.cpython_only
    435     def test_clear_type_cache(self):
    436         sys._clear_type_cache()
    437 
    438     def test_ioencoding(self):
    439         import subprocess
    440         env = dict(os.environ)
    441 
    442         # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
    443         # not representable in ASCII.
    444 
    445         env["PYTHONIOENCODING"] = "cp424"
    446         p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
    447                              stdout = subprocess.PIPE, env=env)
    448         out = p.communicate()[0].strip()
    449         self.assertEqual(out, unichr(0xa2).encode("cp424"))
    450 
    451         env["PYTHONIOENCODING"] = "ascii:replace"
    452         p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
    453                              stdout = subprocess.PIPE, env=env)
    454         out = p.communicate()[0].strip()
    455         self.assertEqual(out, '?')
    456 
    457     def test_call_tracing(self):
    458         self.assertEqual(sys.call_tracing(str, (2,)), "2")
    459         self.assertRaises(TypeError, sys.call_tracing, str, 2)
    460 
    461     def test_executable(self):
    462         # sys.executable should be absolute
    463         self.assertEqual(os.path.abspath(sys.executable), sys.executable)
    464 
    465         # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
    466         # has been set to a non existent program name and Python is unable to
    467         # retrieve the real program name
    468         import subprocess
    469         # For a normal installation, it should work without 'cwd'
    470         # argument. For test runs in the build directory, see #7774.
    471         python_dir = os.path.dirname(os.path.realpath(sys.executable))
    472         p = subprocess.Popen(
    473             ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
    474             executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
    475         executable = p.communicate()[0].strip()
    476         p.wait()
    477         self.assertIn(executable, ["''", repr(sys.executable)])
    478 
    479 @test.test_support.cpython_only
    480 class SizeofTest(unittest.TestCase):
    481 
    482     def setUp(self):
    483         self.P = struct.calcsize('P')
    484         self.longdigit = sys.long_info.sizeof_digit
    485         import _testcapi
    486         self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
    487 
    488     check_sizeof = test.test_support.check_sizeof
    489 
    490     def test_gc_head_size(self):
    491         # Check that the gc header size is added to objects tracked by the gc.
    492         size = test.test_support.calcobjsize
    493         gc_header_size = self.gc_headsize
    494         # bool objects are not gc tracked
    495         self.assertEqual(sys.getsizeof(True), size('l'))
    496         # but lists are
    497         self.assertEqual(sys.getsizeof([]), size('P PP') + gc_header_size)
    498 
    499     def test_errors(self):
    500         class BadSizeof(object):
    501             def __sizeof__(self):
    502                 raise ValueError
    503         self.assertRaises(ValueError, sys.getsizeof, BadSizeof())
    504 
    505         class InvalidSizeof(object):
    506             def __sizeof__(self):
    507                 return None
    508         self.assertRaises(TypeError, sys.getsizeof, InvalidSizeof())
    509         sentinel = ["sentinel"]
    510         self.assertIs(sys.getsizeof(InvalidSizeof(), sentinel), sentinel)
    511 
    512         class OverflowSizeof(long):
    513             def __sizeof__(self):
    514                 return int(self)
    515         self.assertEqual(sys.getsizeof(OverflowSizeof(sys.maxsize)),
    516                          sys.maxsize + self.gc_headsize)
    517         with self.assertRaises(OverflowError):
    518             sys.getsizeof(OverflowSizeof(sys.maxsize + 1))
    519         with self.assertRaises(ValueError):
    520             sys.getsizeof(OverflowSizeof(-1))
    521         with self.assertRaises((ValueError, OverflowError)):
    522             sys.getsizeof(OverflowSizeof(-sys.maxsize - 1))
    523 
    524     def test_default(self):
    525         size = test.test_support.calcobjsize
    526         self.assertEqual(sys.getsizeof(True, -1), size('l'))
    527 
    528     def test_objecttypes(self):
    529         # check all types defined in Objects/
    530         calcsize = struct.calcsize
    531         size = test.test_support.calcobjsize
    532         vsize = test.test_support.calcvobjsize
    533         check = self.check_sizeof
    534         # bool
    535         check(True, size('l'))
    536         # buffer
    537         with test.test_support.check_py3k_warnings():
    538             check(buffer(''), size('2P2Pil'))
    539         # builtin_function_or_method
    540         check(len, size('3P'))
    541         # bytearray
    542         samples = ['', 'u'*100000]
    543         for sample in samples:
    544             x = bytearray(sample)
    545             check(x, vsize('iPP') + x.__alloc__())
    546         # bytearray_iterator
    547         check(iter(bytearray()), size('PP'))
    548         # cell
    549         def get_cell():
    550             x = 42
    551             def inner():
    552                 return x
    553             return inner
    554         check(get_cell().func_closure[0], size('P'))
    555         # classobj (old-style class)
    556         class class_oldstyle():
    557             def method():
    558                 pass
    559         check(class_oldstyle, size('7P'))
    560         # instance (old-style class)
    561         check(class_oldstyle(), size('3P'))
    562         # instancemethod (old-style class)
    563         check(class_oldstyle().method, size('4P'))
    564         # complex
    565         check(complex(0,1), size('2d'))
    566         # code
    567         check(get_cell().func_code, size('4i8Pi3P'))
    568         # BaseException
    569         check(BaseException(), size('3P'))
    570         # UnicodeEncodeError
    571         check(UnicodeEncodeError("", u"", 0, 0, ""), size('5P2PP'))
    572         # UnicodeDecodeError
    573         check(UnicodeDecodeError("", "", 0, 0, ""), size('5P2PP'))
    574         # UnicodeTranslateError
    575         check(UnicodeTranslateError(u"", 0, 1, ""), size('5P2PP'))
    576         # method_descriptor (descriptor object)
    577         check(str.lower, size('2PP'))
    578         # classmethod_descriptor (descriptor object)
    579         # XXX
    580         # member_descriptor (descriptor object)
    581         import datetime
    582         check(datetime.timedelta.days, size('2PP'))
    583         # getset_descriptor (descriptor object)
    584         import __builtin__
    585         check(__builtin__.file.closed, size('2PP'))
    586         # wrapper_descriptor (descriptor object)
    587         check(int.__add__, size('2P2P'))
    588         # dictproxy
    589         class C(object): pass
    590         check(C.__dict__, size('P'))
    591         # method-wrapper (descriptor object)
    592         check({}.__iter__, size('2P'))
    593         # dict
    594         check({}, size('3P2P') + 8*calcsize('P2P'))
    595         x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
    596         check(x, size('3P2P') + 8*calcsize('P2P') + 16*calcsize('P2P'))
    597         # dictionary-keyview
    598         check({}.viewkeys(), size('P'))
    599         # dictionary-valueview
    600         check({}.viewvalues(), size('P'))
    601         # dictionary-itemview
    602         check({}.viewitems(), size('P'))
    603         # dictionary iterator
    604         check(iter({}), size('P2PPP'))
    605         # dictionary-keyiterator
    606         check({}.iterkeys(), size('P2PPP'))
    607         # dictionary-valueiterator
    608         check({}.itervalues(), size('P2PPP'))
    609         # dictionary-itemiterator
    610         check({}.iteritems(), size('P2PPP'))
    611         # ellipses
    612         check(Ellipsis, size(''))
    613         # EncodingMap
    614         import codecs, encodings.iso8859_3
    615         x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
    616         check(x, size('32B2iB'))
    617         # enumerate
    618         check(enumerate([]), size('l3P'))
    619         # file
    620         f = file(test.test_support.TESTFN, 'wb')
    621         try:
    622             check(f, size('4P2i4P3i3P3i'))
    623         finally:
    624             f.close()
    625             test.test_support.unlink(test.test_support.TESTFN)
    626         # float
    627         check(float(0), size('d'))
    628         # sys.floatinfo
    629         check(sys.float_info, vsize('') + self.P * len(sys.float_info))
    630         # frame
    631         import inspect
    632         CO_MAXBLOCKS = 20
    633         x = inspect.currentframe()
    634         ncells = len(x.f_code.co_cellvars)
    635         nfrees = len(x.f_code.co_freevars)
    636         extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
    637                  ncells + nfrees - 1
    638         check(x, vsize('12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
    639         # function
    640         def func(): pass
    641         check(func, size('9P'))
    642         class c():
    643             @staticmethod
    644             def foo():
    645                 pass
    646             @classmethod
    647             def bar(cls):
    648                 pass
    649             # staticmethod
    650             check(foo, size('P'))
    651             # classmethod
    652             check(bar, size('P'))
    653         # generator
    654         def get_gen(): yield 1
    655         check(get_gen(), size('Pi2P'))
    656         # integer
    657         check(1, size('l'))
    658         check(100, size('l'))
    659         # iterator
    660         check(iter('abc'), size('lP'))
    661         # callable-iterator
    662         import re
    663         check(re.finditer('',''), size('2P'))
    664         # list
    665         samples = [[], [1,2,3], ['1', '2', '3']]
    666         for sample in samples:
    667             check(sample, vsize('PP') + len(sample)*self.P)
    668         # sortwrapper (list)
    669         # XXX
    670         # cmpwrapper (list)
    671         # XXX
    672         # listiterator (list)
    673         check(iter([]), size('lP'))
    674         # listreverseiterator (list)
    675         check(reversed([]), size('lP'))
    676         # long
    677         check(0L, vsize(''))
    678         check(1L, vsize('') + self.longdigit)
    679         check(-1L, vsize('') + self.longdigit)
    680         PyLong_BASE = 2**sys.long_info.bits_per_digit
    681         check(long(PyLong_BASE), vsize('') + 2*self.longdigit)
    682         check(long(PyLong_BASE**2-1), vsize('') + 2*self.longdigit)
    683         check(long(PyLong_BASE**2), vsize('') + 3*self.longdigit)
    684         # module
    685         check(unittest, size('P'))
    686         # None
    687         check(None, size(''))
    688         # object
    689         check(object(), size(''))
    690         # property (descriptor object)
    691         class C(object):
    692             def getx(self): return self.__x
    693             def setx(self, value): self.__x = value
    694             def delx(self): del self.__x
    695             x = property(getx, setx, delx, "")
    696             check(x, size('4Pi'))
    697         # PyCObject
    698         # PyCapsule
    699         # XXX
    700         # rangeiterator
    701         check(iter(xrange(1)), size('4l'))
    702         # reverse
    703         check(reversed(''), size('PP'))
    704         # set
    705         # frozenset
    706         PySet_MINSIZE = 8
    707         samples = [[], range(10), range(50)]
    708         s = size('3P2P' + PySet_MINSIZE*'lP' + 'lP')
    709         for sample in samples:
    710             minused = len(sample)
    711             if minused == 0: tmp = 1
    712             # the computation of minused is actually a bit more complicated
    713             # but this suffices for the sizeof test
    714             minused = minused*2
    715             newsize = PySet_MINSIZE
    716             while newsize <= minused:
    717                 newsize = newsize << 1
    718             if newsize <= 8:
    719                 check(set(sample), s)
    720                 check(frozenset(sample), s)
    721             else:
    722                 check(set(sample), s + newsize*calcsize('lP'))
    723                 check(frozenset(sample), s + newsize*calcsize('lP'))
    724         # setiterator
    725         check(iter(set()), size('P3P'))
    726         # slice
    727         check(slice(1), size('3P'))
    728         # str
    729         vh = test.test_support._vheader
    730         check('', calcsize(vh + 'lic'))
    731         check('abc', calcsize(vh + 'lic') + 3)
    732         # super
    733         check(super(int), size('3P'))
    734         # tuple
    735         check((), vsize(''))
    736         check((1,2,3), vsize('') + 3*self.P)
    737         # tupleiterator
    738         check(iter(()), size('lP'))
    739         # type
    740         s = vsize('P2P15Pl4PP9PP11PI'   # PyTypeObject
    741                   '39P'                 # PyNumberMethods
    742                   '3P'                  # PyMappingMethods
    743                   '10P'                 # PySequenceMethods
    744                   '6P'                  # PyBufferProcs
    745                   '2P')
    746         class newstyleclass(object):
    747             pass
    748         check(newstyleclass, s)
    749         # builtin type
    750         check(int, s)
    751         # NotImplementedType
    752         import types
    753         check(types.NotImplementedType, s)
    754         # unicode
    755         usize = len(u'\0'.encode('unicode-internal'))
    756         samples = [u'', u'1'*100]
    757         # we need to test for both sizes, because we don't know if the string
    758         # has been cached
    759         for s in samples:
    760             check(s, size('PPlP') + usize * (len(s) + 1))
    761         # weakref
    762         import weakref
    763         check(weakref.ref(int), size('2Pl2P'))
    764         # weakproxy
    765         # XXX
    766         # weakcallableproxy
    767         check(weakref.proxy(int), size('2Pl2P'))
    768         # xrange
    769         check(xrange(1), size('3l'))
    770         check(xrange(66000), size('3l'))
    771 
    772     def check_slots(self, obj, base, extra):
    773         expected = sys.getsizeof(base) + struct.calcsize(extra)
    774         if gc.is_tracked(obj) and not gc.is_tracked(base):
    775             expected += self.gc_headsize
    776         self.assertEqual(sys.getsizeof(obj), expected)
    777 
    778     def test_slots(self):
    779         # check all subclassable types defined in Objects/ that allow
    780         # non-empty __slots__
    781         check = self.check_slots
    782         class BA(bytearray):
    783             __slots__ = 'a', 'b', 'c'
    784         check(BA(), bytearray(), '3P')
    785         class D(dict):
    786             __slots__ = 'a', 'b', 'c'
    787         check(D(x=[]), {'x': []}, '3P')
    788         class L(list):
    789             __slots__ = 'a', 'b', 'c'
    790         check(L(), [], '3P')
    791         class S(set):
    792             __slots__ = 'a', 'b', 'c'
    793         check(S(), set(), '3P')
    794         class FS(frozenset):
    795             __slots__ = 'a', 'b', 'c'
    796         check(FS(), frozenset(), '3P')
    797 
    798     def test_pythontypes(self):
    799         # check all types defined in Python/
    800         size = test.test_support.calcobjsize
    801         vsize = test.test_support.calcvobjsize
    802         check = self.check_sizeof
    803         # _ast.AST
    804         import _ast
    805         check(_ast.AST(), size(''))
    806         # imp.NullImporter
    807         import imp
    808         f = open(test.test_support.TESTFN, 'wb')
    809         try:
    810             check(imp.NullImporter(f.name), size(''))
    811         finally:
    812             f.close()
    813             test.test_support.unlink(test.test_support.TESTFN)
    814         try:
    815             raise TypeError
    816         except TypeError:
    817             tb = sys.exc_info()[2]
    818             # traceback
    819             if tb != None:
    820                 check(tb, size('2P2i'))
    821         # symtable entry
    822         # XXX
    823         # sys.flags
    824         check(sys.flags, vsize('') + self.P * len(sys.flags))
    825 
    826 
    827 def test_main():
    828     test_classes = (SysModuleTest, SizeofTest)
    829 
    830     test.test_support.run_unittest(*test_classes)
    831 
    832 if __name__ == "__main__":
    833     test_main()
    834