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