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