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