blob: ff0d7a5df8f9a15fe50a0c04305cb959895e254f [file] [log] [blame]
Walter Dörwaldc3502462003-02-03 23:03:49 +00001# -*- coding: iso-8859-1 -*-
2import unittest, test.test_support
Robert Schuppenies51df0642008-06-01 16:16:17 +00003import sys, cStringIO, os
Robert Schuppenies41a7ce02008-06-25 09:20:03 +00004import struct
Walter Dörwaldc3502462003-02-03 23:03:49 +00005
6class SysModuleTest(unittest.TestCase):
7
8 def test_original_displayhook(self):
9 import __builtin__
10 savestdout = sys.stdout
11 out = cStringIO.StringIO()
12 sys.stdout = out
13
14 dh = sys.__displayhook__
15
16 self.assertRaises(TypeError, dh)
17 if hasattr(__builtin__, "_"):
18 del __builtin__._
19
20 dh(None)
21 self.assertEqual(out.getvalue(), "")
22 self.assert_(not hasattr(__builtin__, "_"))
23 dh(42)
24 self.assertEqual(out.getvalue(), "42\n")
25 self.assertEqual(__builtin__._, 42)
26
27 del sys.stdout
28 self.assertRaises(RuntimeError, dh, 42)
29
30 sys.stdout = savestdout
31
32 def test_lost_displayhook(self):
33 olddisplayhook = sys.displayhook
34 del sys.displayhook
35 code = compile("42", "<string>", "single")
36 self.assertRaises(RuntimeError, eval, code)
37 sys.displayhook = olddisplayhook
38
39 def test_custom_displayhook(self):
40 olddisplayhook = sys.displayhook
41 def baddisplayhook(obj):
42 raise ValueError
43 sys.displayhook = baddisplayhook
44 code = compile("42", "<string>", "single")
45 self.assertRaises(ValueError, eval, code)
46 sys.displayhook = olddisplayhook
47
48 def test_original_excepthook(self):
49 savestderr = sys.stderr
50 err = cStringIO.StringIO()
51 sys.stderr = err
52
53 eh = sys.__excepthook__
54
55 self.assertRaises(TypeError, eh)
56 try:
57 raise ValueError(42)
58 except ValueError, exc:
59 eh(*sys.exc_info())
60
61 sys.stderr = savestderr
62 self.assert_(err.getvalue().endswith("ValueError: 42\n"))
63
Walter Dörwalde7028ac2003-02-03 23:05:27 +000064 # FIXME: testing the code for a lost or replaced excepthook in
Walter Dörwaldc3502462003-02-03 23:03:49 +000065 # Python/pythonrun.c::PyErr_PrintEx() is tricky.
66
Guido van Rossum46d3dc32003-03-01 03:20:41 +000067 def test_exc_clear(self):
68 self.assertRaises(TypeError, sys.exc_clear, 42)
69
70 # Verify that exc_info is present and matches exc, then clear it, and
71 # check that it worked.
72 def clear_check(exc):
Guido van Rossumd6473d12003-03-01 03:25:41 +000073 typ, value, traceback = sys.exc_info()
74 self.assert_(typ is not None)
75 self.assert_(value is exc)
76 self.assert_(traceback is not None)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000077
Guido van Rossumd6473d12003-03-01 03:25:41 +000078 sys.exc_clear()
Guido van Rossum46d3dc32003-03-01 03:20:41 +000079
Guido van Rossumd6473d12003-03-01 03:25:41 +000080 typ, value, traceback = sys.exc_info()
81 self.assert_(typ is None)
82 self.assert_(value is None)
83 self.assert_(traceback is None)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000084
85 def clear():
Guido van Rossumd6473d12003-03-01 03:25:41 +000086 try:
87 raise ValueError, 42
88 except ValueError, exc:
89 clear_check(exc)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000090
91 # Raise an exception and check that it can be cleared
92 clear()
93
94 # Verify that a frame currently handling an exception is
95 # unaffected by calling exc_clear in a nested frame.
96 try:
Guido van Rossumd6473d12003-03-01 03:25:41 +000097 raise ValueError, 13
Guido van Rossum46d3dc32003-03-01 03:20:41 +000098 except ValueError, exc:
Guido van Rossumd6473d12003-03-01 03:25:41 +000099 typ1, value1, traceback1 = sys.exc_info()
100 clear()
101 typ2, value2, traceback2 = sys.exc_info()
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000102
Guido van Rossumd6473d12003-03-01 03:25:41 +0000103 self.assert_(typ1 is typ2)
104 self.assert_(value1 is exc)
105 self.assert_(value1 is value2)
106 self.assert_(traceback1 is traceback2)
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000107
108 # Check that an exception can be cleared outside of an except block
109 clear_check(exc)
110
Walter Dörwaldc3502462003-02-03 23:03:49 +0000111 def test_exit(self):
112 self.assertRaises(TypeError, sys.exit, 42, 42)
113
114 # call without argument
115 try:
116 sys.exit(0)
117 except SystemExit, exc:
118 self.assertEquals(exc.code, 0)
119 except:
120 self.fail("wrong exception")
121 else:
122 self.fail("no exception")
123
124 # call with tuple argument with one entry
125 # entry will be unpacked
126 try:
127 sys.exit(42)
128 except SystemExit, exc:
129 self.assertEquals(exc.code, 42)
130 except:
131 self.fail("wrong exception")
132 else:
133 self.fail("no exception")
134
135 # call with integer argument
136 try:
137 sys.exit((42,))
138 except SystemExit, exc:
139 self.assertEquals(exc.code, 42)
140 except:
141 self.fail("wrong exception")
142 else:
143 self.fail("no exception")
144
145 # call with string argument
146 try:
147 sys.exit("exit")
148 except SystemExit, exc:
149 self.assertEquals(exc.code, "exit")
150 except:
151 self.fail("wrong exception")
152 else:
153 self.fail("no exception")
154
155 # call with tuple argument with two entries
156 try:
157 sys.exit((17, 23))
158 except SystemExit, exc:
159 self.assertEquals(exc.code, (17, 23))
160 except:
161 self.fail("wrong exception")
162 else:
163 self.fail("no exception")
164
Michael W. Hudsonf0588582005-02-15 15:26:11 +0000165 # 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)
Tim Petersf0db38d2005-02-15 21:50:12 +0000175
176
Walter Dörwaldc3502462003-02-03 23:03:49 +0000177 def test_getdefaultencoding(self):
178 if test.test_support.have_unicode:
179 self.assertRaises(TypeError, sys.getdefaultencoding, 42)
180 # can't check more than the type, as the user might have changed it
181 self.assert_(isinstance(sys.getdefaultencoding(), str))
182
183 # testing sys.settrace() is done in test_trace.py
184 # testing sys.setprofile() is done in test_profile.py
185
186 def test_setcheckinterval(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000187 self.assertRaises(TypeError, sys.setcheckinterval)
Tim Peterse5e065b2003-07-06 18:36:54 +0000188 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)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000192
193 def test_recursionlimit(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000194 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)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000201
202 def test_getwindowsversion(self):
203 if hasattr(sys, "getwindowsversion"):
204 v = sys.getwindowsversion()
205 self.assert_(isinstance(v, tuple))
206 self.assertEqual(len(v), 5)
207 self.assert_(isinstance(v[0], int))
208 self.assert_(isinstance(v[1], int))
209 self.assert_(isinstance(v[2], int))
210 self.assert_(isinstance(v[3], int))
211 self.assert_(isinstance(v[4], str))
212
213 def test_dlopenflags(self):
214 if hasattr(sys, "setdlopenflags"):
215 self.assert_(hasattr(sys, "getdlopenflags"))
216 self.assertRaises(TypeError, sys.getdlopenflags, 42)
217 oldflags = sys.getdlopenflags()
218 self.assertRaises(TypeError, sys.setdlopenflags)
219 sys.setdlopenflags(oldflags+1)
220 self.assertEqual(sys.getdlopenflags(), oldflags+1)
221 sys.setdlopenflags(oldflags)
222
223 def test_refcount(self):
224 self.assertRaises(TypeError, sys.getrefcount)
225 c = sys.getrefcount(None)
226 n = None
227 self.assertEqual(sys.getrefcount(None), c+1)
228 del n
229 self.assertEqual(sys.getrefcount(None), c)
230 if hasattr(sys, "gettotalrefcount"):
231 self.assert_(isinstance(sys.gettotalrefcount(), int))
232
233 def test_getframe(self):
234 self.assertRaises(TypeError, sys._getframe, 42, 42)
Neal Norwitzeb2a5ef2003-02-18 15:22:10 +0000235 self.assertRaises(ValueError, sys._getframe, 2000000000)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000236 self.assert_(
237 SysModuleTest.test_getframe.im_func.func_code \
238 is sys._getframe().f_code
239 )
240
Tim Peters32a83612006-07-10 21:08:24 +0000241 # sys._current_frames() is a CPython-only gimmick.
242 def test_current_frames(self):
Tim Peters112aad32006-07-19 00:03:19 +0000243 have_threads = True
244 try:
245 import thread
246 except ImportError:
247 have_threads = False
248
249 if have_threads:
250 self.current_frames_with_threads()
251 else:
252 self.current_frames_without_threads()
253
254 # Test sys._current_frames() in a WITH_THREADS build.
255 def current_frames_with_threads(self):
Tim Peters32a83612006-07-10 21:08:24 +0000256 import threading, thread
257 import traceback
258
259 # Spawn a thread that blocks at a known place. Then the main
260 # thread does sys._current_frames(), and verifies that the frames
261 # returned make sense.
262 entered_g = threading.Event()
263 leave_g = threading.Event()
264 thread_info = [] # the thread's id
265
266 def f123():
267 g456()
268
269 def g456():
270 thread_info.append(thread.get_ident())
271 entered_g.set()
272 leave_g.wait()
273
274 t = threading.Thread(target=f123)
275 t.start()
276 entered_g.wait()
277
Tim Peters0c4a3b32006-07-25 04:07:22 +0000278 # At this point, t has finished its entered_g.set(), although it's
279 # impossible to guess whether it's still on that line or has moved on
280 # to its leave_g.wait().
Tim Peters32a83612006-07-10 21:08:24 +0000281 self.assertEqual(len(thread_info), 1)
282 thread_id = thread_info[0]
283
284 d = sys._current_frames()
285
286 main_id = thread.get_ident()
287 self.assert_(main_id in d)
288 self.assert_(thread_id in d)
289
290 # Verify that the captured main-thread frame is _this_ frame.
291 frame = d.pop(main_id)
292 self.assert_(frame is sys._getframe())
293
294 # Verify that the captured thread frame is blocked in g456, called
295 # from f123. This is a litte tricky, since various bits of
296 # threading.py are also in the thread's call stack.
297 frame = d.pop(thread_id)
298 stack = traceback.extract_stack(frame)
299 for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
300 if funcname == "f123":
301 break
302 else:
303 self.fail("didn't find f123() on thread's call stack")
304
305 self.assertEqual(sourceline, "g456()")
306
307 # And the next record must be for g456().
308 filename, lineno, funcname, sourceline = stack[i+1]
309 self.assertEqual(funcname, "g456")
Tim Peters0c4a3b32006-07-25 04:07:22 +0000310 self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"])
Tim Peters32a83612006-07-10 21:08:24 +0000311
312 # Reap the spawned thread.
313 leave_g.set()
314 t.join()
315
Tim Peters112aad32006-07-19 00:03:19 +0000316 # Test sys._current_frames() when thread support doesn't exist.
317 def current_frames_without_threads(self):
318 # Not much happens here: there is only one thread, with artificial
319 # "thread id" 0.
320 d = sys._current_frames()
321 self.assertEqual(len(d), 1)
322 self.assert_(0 in d)
323 self.assert_(d[0] is sys._getframe())
324
Walter Dörwaldc3502462003-02-03 23:03:49 +0000325 def test_attributes(self):
326 self.assert_(isinstance(sys.api_version, int))
327 self.assert_(isinstance(sys.argv, list))
328 self.assert_(sys.byteorder in ("little", "big"))
329 self.assert_(isinstance(sys.builtin_module_names, tuple))
330 self.assert_(isinstance(sys.copyright, basestring))
331 self.assert_(isinstance(sys.exec_prefix, basestring))
332 self.assert_(isinstance(sys.executable, basestring))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000333 self.assertEqual(len(sys.float_info), 11)
Christian Heimesc94e2b52008-01-14 04:13:37 +0000334 self.assertEqual(sys.float_info.radix, 2)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000335 self.assert_(isinstance(sys.hexversion, int))
336 self.assert_(isinstance(sys.maxint, int))
Walter Dörwald4e41a4b2005-08-03 17:09:04 +0000337 if test.test_support.have_unicode:
338 self.assert_(isinstance(sys.maxunicode, int))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000339 self.assert_(isinstance(sys.platform, basestring))
340 self.assert_(isinstance(sys.prefix, basestring))
341 self.assert_(isinstance(sys.version, basestring))
342 vi = sys.version_info
343 self.assert_(isinstance(vi, tuple))
344 self.assertEqual(len(vi), 5)
345 self.assert_(isinstance(vi[0], int))
346 self.assert_(isinstance(vi[1], int))
347 self.assert_(isinstance(vi[2], int))
348 self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
349 self.assert_(isinstance(vi[4], int))
350
Martin v. Löwisa8cd7a22006-04-03 11:05:39 +0000351 def test_43581(self):
352 # Can't use sys.stdout, as this is a cStringIO object when
353 # the test runs under regrtest.
354 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
355
Christian Heimesf31b69f2008-01-14 03:42:48 +0000356 def test_sys_flags(self):
357 self.failUnless(sys.flags)
358 attrs = ("debug", "py3k_warning", "division_warning", "division_new",
359 "inspect", "interactive", "optimize", "dont_write_bytecode",
Andrew M. Kuchling7ce9b182008-01-15 01:29:16 +0000360 "no_site", "ignore_environment", "tabcheck", "verbose",
Brett Cannonbe1501b2008-05-08 20:23:06 +0000361 "unicode", "bytes_warning")
Christian Heimesf31b69f2008-01-14 03:42:48 +0000362 for attr in attrs:
363 self.assert_(hasattr(sys.flags, attr), attr)
364 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
365 self.assert_(repr(sys.flags))
366
Christian Heimes422051a2008-02-04 18:00:12 +0000367 def test_clear_type_cache(self):
368 sys._clear_type_cache()
369
Martin v. Löwis99815892008-06-01 07:20:46 +0000370 def test_ioencoding(self):
371 import subprocess,os
372 env = dict(os.environ)
373
374 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
375 # not representable in ASCII.
376
377 env["PYTHONIOENCODING"] = "cp424"
378 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
379 stdout = subprocess.PIPE, env=env)
380 out = p.stdout.read().strip()
381 self.assertEqual(out, unichr(0xa2).encode("cp424"))
382
383 env["PYTHONIOENCODING"] = "ascii:replace"
384 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
385 stdout = subprocess.PIPE, env=env)
386 out = p.stdout.read().strip()
387 self.assertEqual(out, '?')
388
389
Robert Schuppenies51df0642008-06-01 16:16:17 +0000390class SizeofTest(unittest.TestCase):
391
392 def setUp(self):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000393 self.c = len(struct.pack('c', ' '))
394 self.H = len(struct.pack('H', 0))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000395 self.i = len(struct.pack('i', 0))
396 self.l = len(struct.pack('l', 0))
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000397 self.P = len(struct.pack('P', 0))
398 # due to missing size_t information from struct, it is assumed that
399 # sizeof(Py_ssize_t) = sizeof(void*)
Robert Schuppenies161b9212008-06-26 15:20:35 +0000400 self.header = 'PP'
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000401 self.vheader = self.header + 'P'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000402 if hasattr(sys, "gettotalrefcount"):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000403 self.header += '2P'
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000404 self.vheader += '2P'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000405 self.file = open(test.test_support.TESTFN, 'wb')
406
407 def tearDown(self):
408 self.file.close()
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000409 test.test_support.unlink(test.test_support.TESTFN)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000410
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000411 def check_sizeof(self, o, size):
Robert Schuppenies51df0642008-06-01 16:16:17 +0000412 result = sys.getsizeof(o)
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000413 msg = 'wrong size for %s: got %d, expected %d' \
414 % (type(o), result, size)
415 self.assertEqual(result, size, msg)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000416
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000417 def calcsize(self, fmt):
418 """Wrapper around struct.calcsize which enforces the alignment of the
419 end of a structure to the alignment requirement of pointer.
Robert Schuppenies51df0642008-06-01 16:16:17 +0000420
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000421 Note: This wrapper should only be used if a pointer member is included
422 and no member with a size larger than a pointer exists.
423 """
424 return struct.calcsize(fmt + '0P')
Robert Schuppenies51df0642008-06-01 16:16:17 +0000425
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000426 def test_objecttypes(self):
427 # check all types defined in Objects/
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000428 h = self.header
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000429 vh = self.vheader
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000430 size = self.calcsize
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000431 check = self.check_sizeof
Robert Schuppenies51df0642008-06-01 16:16:17 +0000432 # bool
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000433 check(True, size(h + 'l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000434 # buffer
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000435 check(buffer(''), size(h + '2P2Pil'))
436 # builtin_function_or_method
437 check(len, size(h + '3P'))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000438 # bytearray
439 samples = ['', 'u'*100000]
440 for sample in samples:
441 x = bytearray(sample)
442 check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
443 # bytearray_iterator
444 check(iter(bytearray()), size(h + 'PP'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000445 # cell
446 def get_cell():
447 x = 42
448 def inner():
449 return x
450 return inner
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000451 check(get_cell().func_closure[0], size(h + 'P'))
452 # classobj (old-style class)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000453 class class_oldstyle():
454 def method():
455 pass
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000456 check(class_oldstyle, size(h + '6P'))
457 # instance (old-style class)
458 check(class_oldstyle(), size(h + '3P'))
459 # instancemethod (old-style class)
460 check(class_oldstyle().method, size(h + '4P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000461 # complex
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000462 check(complex(0,1), size(h + '2d'))
463 # code
464 check(get_cell().func_code, size(h + '4i8Pi2P'))
465 # BaseException
466 check(BaseException(), size(h + '3P'))
467 # UnicodeEncodeError
468 check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP'))
469 # UnicodeDecodeError
470 check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
471 # UnicodeTranslateError
472 check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP'))
473 # method_descriptor (descriptor object)
474 check(str.lower, size(h + '2PP'))
475 # classmethod_descriptor (descriptor object)
476 # XXX
477 # member_descriptor (descriptor object)
478 import datetime
479 check(datetime.timedelta.days, size(h + '2PP'))
480 # getset_descriptor (descriptor object)
481 import __builtin__
482 check(__builtin__.file.closed, size(h + '2PP'))
483 # wrapper_descriptor (descriptor object)
484 check(int.__add__, size(h + '2P2P'))
485 # dictproxy
486 class C(object): pass
487 check(C.__dict__, size(h + 'P'))
488 # method-wrapper (descriptor object)
489 check({}.__iter__, size(h + '2P'))
490 # dict
491 check({}, size(h + '3P2P') + 8*size('P2P'))
492 x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
493 check(x, size(h + '3P2P') + (8+16)*size('P2P'))
494 # dictionary-keyiterator
495 check({}.iterkeys(), size(h + 'P2PPP'))
496 # dictionary-valueiterator
497 check({}.itervalues(), size(h + 'P2PPP'))
498 # dictionary-itemiterator
499 check({}.iteritems(), size(h + 'P2PPP'))
500 # ellipses
501 check(Ellipsis, size(h + ''))
502 # EncodingMap
503 import codecs, encodings.iso8859_3
504 x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
505 check(x, size(h + '32B2iB'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000506 # enumerate
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000507 check(enumerate([]), size(h + 'l3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000508 # file
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000509 check(self.file, size(h + '4P2i4P3i3Pi'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000510 # float
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000511 check(float(0), size(h + 'd'))
512 # sys.floatinfo
513 check(sys.float_info, size(vh) + self.P * len(sys.float_info))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000514 # frame
515 import inspect
516 CO_MAXBLOCKS = 20
517 x = inspect.currentframe()
518 ncells = len(x.f_code.co_cellvars)
519 nfrees = len(x.f_code.co_freevars)
520 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
521 ncells + nfrees - 1
522 check(x, size(vh + '12P3i') +\
523 CO_MAXBLOCKS*struct.calcsize('3i') +\
524 self.P + extras*self.P)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000525 # function
526 def func(): pass
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000527 check(func, size(h + '9P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000528 class c():
529 @staticmethod
530 def foo():
531 pass
532 @classmethod
533 def bar(cls):
534 pass
535 # staticmethod
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000536 check(foo, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000537 # classmethod
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000538 check(bar, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000539 # generator
540 def get_gen(): yield 1
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000541 check(get_gen(), size(h + 'Pi2P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000542 # integer
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000543 check(1, size(h + 'l'))
544 check(100, size(h + 'l'))
545 # iterator
546 check(iter('abc'), size(h + 'lP'))
547 # callable-iterator
548 import re
549 check(re.finditer('',''), size(h + '2P'))
550 # list
551 samples = [[], [1,2,3], ['1', '2', '3']]
552 for sample in samples:
553 check(sample, size(vh + 'PP') + len(sample)*self.P)
554 # sortwrapper (list)
555 # XXX
556 # cmpwrapper (list)
557 # XXX
558 # listiterator (list)
559 check(iter([]), size(h + 'lP'))
560 # listreverseiterator (list)
561 check(reversed([]), size(h + 'lP'))
562 # long
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000563 check(0L, size(vh + 'H') - self.H)
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000564 check(1L, size(vh + 'H'))
565 check(-1L, size(vh + 'H'))
566 check(32768L, size(vh + 'H') + self.H)
567 check(32768L*32768L-1, size(vh + 'H') + self.H)
568 check(32768L*32768L, size(vh + 'H') + 2*self.H)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000569 # module
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000570 check(unittest, size(h + 'P'))
571 # None
572 check(None, size(h + ''))
573 # object
574 check(object(), size(h + ''))
575 # property (descriptor object)
576 class C(object):
577 def getx(self): return self.__x
578 def setx(self, value): self.__x = value
579 def delx(self): del self.__x
580 x = property(getx, setx, delx, "")
581 check(x, size(h + '4Pi'))
582 # PyCObject
583 # XXX
584 # rangeiterator
585 check(iter(xrange(1)), size(h + '4l'))
586 # reverse
587 check(reversed(''), size(h + 'PP'))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000588 # set
589 # frozenset
590 PySet_MINSIZE = 8
591 samples = [[], range(10), range(50)]
592 s = size(h + '3P2P') +\
593 PySet_MINSIZE*struct.calcsize('lP') + self.l + self.P
594 for sample in samples:
595 minused = len(sample)
596 if minused == 0: tmp = 1
597 # the computation of minused is actually a bit more complicated
598 # but this suffices for the sizeof test
599 minused = minused*2
600 newsize = PySet_MINSIZE
601 while newsize <= minused:
602 newsize = newsize << 1
603 if newsize <= 8:
604 check(set(sample), s)
605 check(frozenset(sample), s)
606 else:
607 check(set(sample), s + newsize*struct.calcsize('lP'))
608 check(frozenset(sample), s + newsize*struct.calcsize('lP'))
609 # setiterator
610 check(iter(set()), size(h + 'P3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000611 # slice
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000612 check(slice(1), size(h + '3P'))
613 # str
614 check('', size(vh + 'lic'))
615 check('abc', size(vh + 'lic') + 3*self.c)
616 # super
617 check(super(int), size(h + '3P'))
618 # tuple
619 check((), size(vh))
620 check((1,2,3), size(vh) + 3*self.P)
621 # tupleiterator
622 check(iter(()), size(h + 'lP'))
623 # type
624 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
625 # PySequenceMethods + PyBufferProcs)
626 s = size('P2P15Pl4PP9PP11PI') + size(vh + '41P 10P 3P 6P')
627 class newstyleclass(object):
628 pass
629 check(newstyleclass, s)
630 # builtin type
631 check(int, s)
632 # NotImplementedType
633 import types
634 check(types.NotImplementedType, s)
Robert Schuppenies901c9972008-06-10 10:10:31 +0000635 # unicode
Robert Schuppenies59f3ade2008-06-17 08:42:15 +0000636 usize = len(u'\0'.encode('unicode-internal'))
Robert Schuppenies901c9972008-06-10 10:10:31 +0000637 samples = [u'', u'1'*100]
638 # we need to test for both sizes, because we don't know if the string
639 # has been cached
640 for s in samples:
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000641 check(s, size(h + 'PPlP') + usize * (len(s) + 1))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000642 # weakref
643 import weakref
644 check(weakref.ref(int), size(h + '2Pl2P'))
645 # weakproxy
646 # XXX
647 # weakcallableproxy
648 check(weakref.proxy(int), size(h + '2Pl2P'))
649 # xrange
650 check(xrange(1), size(h + '3l'))
651 check(xrange(66000), size(h + '3l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000652
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000653 def test_pythontypes(self):
654 # check all types defined in Python/
655 h = self.header
656 vh = self.vheader
657 size = self.calcsize
658 check = self.check_sizeof
659 # _ast.AST
660 import _ast
661 check(_ast.AST(), size(h + ''))
662 # imp.NullImporter
663 import imp
664 check(imp.NullImporter(self.file.name), size(h + ''))
665 try:
666 raise TypeError
667 except TypeError:
668 tb = sys.exc_info()[2]
669 # traceback
670 if tb != None:
671 check(tb, size(h + '2P2i'))
672 # symtable entry
673 # XXX
674 # sys.flags
675 check(sys.flags, size(vh) + self.P * len(sys.flags))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000676
677
Walter Dörwaldc3502462003-02-03 23:03:49 +0000678def test_main():
Robert Schuppenies51df0642008-06-01 16:16:17 +0000679 test_classes = (SysModuleTest, SizeofTest)
680
681 test.test_support.run_unittest(*test_classes)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000682
683if __name__ == "__main__":
684 test_main()