home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 July / maximum-cd-2011-07.iso / DiscContents / LibO_3.3.2_Win_x86_install_multi.exe / libreoffice1.cab / test_sys.py < prev    next >
Encoding:
Python Source  |  2011-03-15  |  24.0 KB  |  705 lines

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