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