blob: 980606d70d6444249fedc43e4164fd150dadd8f8 [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
Victor Stinnerc3e40e02010-05-25 22:40:38 +0000176 def check_exit_message(code, expected, env=None):
177 process = subprocess.Popen([sys.executable, "-c", code],
178 stderr=subprocess.PIPE, env=env)
179 stdout, stderr = process.communicate()
180 self.assertEqual(process.returncode, 1)
181 self.assertTrue(stderr.startswith(expected),
182 "%s doesn't start with %s" % (repr(stderr), repr(expected)))
183
184 # test that stderr buffer if flushed before the exit message is written
185 # into stderr
186 check_exit_message(
187 r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
188 b"unflushed,message")
189
190 # test that the unicode message is encoded to the stderr encoding
191 env = os.environ.copy()
192 env['PYTHONIOENCODING'] = 'latin-1'
193 check_exit_message(
194 r'import sys; sys.exit(u"h\xe9")',
195 b"h\xe9", env=env)
Tim Petersf0db38d2005-02-15 21:50:12 +0000196
Walter Dörwaldc3502462003-02-03 23:03:49 +0000197 def test_getdefaultencoding(self):
198 if test.test_support.have_unicode:
199 self.assertRaises(TypeError, sys.getdefaultencoding, 42)
200 # can't check more than the type, as the user might have changed it
201 self.assert_(isinstance(sys.getdefaultencoding(), str))
202
203 # testing sys.settrace() is done in test_trace.py
204 # testing sys.setprofile() is done in test_profile.py
205
206 def test_setcheckinterval(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000207 self.assertRaises(TypeError, sys.setcheckinterval)
Tim Peterse5e065b2003-07-06 18:36:54 +0000208 orig = sys.getcheckinterval()
209 for n in 0, 100, 120, orig: # orig last to restore starting state
210 sys.setcheckinterval(n)
211 self.assertEquals(sys.getcheckinterval(), n)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000212
213 def test_recursionlimit(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000214 self.assertRaises(TypeError, sys.getrecursionlimit, 42)
215 oldlimit = sys.getrecursionlimit()
216 self.assertRaises(TypeError, sys.setrecursionlimit)
217 self.assertRaises(ValueError, sys.setrecursionlimit, -42)
218 sys.setrecursionlimit(10000)
219 self.assertEqual(sys.getrecursionlimit(), 10000)
220 sys.setrecursionlimit(oldlimit)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000221
222 def test_getwindowsversion(self):
223 if hasattr(sys, "getwindowsversion"):
224 v = sys.getwindowsversion()
225 self.assert_(isinstance(v, tuple))
226 self.assertEqual(len(v), 5)
227 self.assert_(isinstance(v[0], int))
228 self.assert_(isinstance(v[1], int))
229 self.assert_(isinstance(v[2], int))
230 self.assert_(isinstance(v[3], int))
231 self.assert_(isinstance(v[4], str))
232
233 def test_dlopenflags(self):
234 if hasattr(sys, "setdlopenflags"):
235 self.assert_(hasattr(sys, "getdlopenflags"))
236 self.assertRaises(TypeError, sys.getdlopenflags, 42)
237 oldflags = sys.getdlopenflags()
238 self.assertRaises(TypeError, sys.setdlopenflags)
239 sys.setdlopenflags(oldflags+1)
240 self.assertEqual(sys.getdlopenflags(), oldflags+1)
241 sys.setdlopenflags(oldflags)
242
243 def test_refcount(self):
Georg Brandl9b08e052009-04-05 21:21:05 +0000244 # n here must be a global in order for this test to pass while
245 # tracing with a python function. Tracing calls PyFrame_FastToLocals
246 # which will add a copy of any locals to the frame object, causing
247 # the reference count to increase by 2 instead of 1.
248 global n
Walter Dörwaldc3502462003-02-03 23:03:49 +0000249 self.assertRaises(TypeError, sys.getrefcount)
250 c = sys.getrefcount(None)
251 n = None
252 self.assertEqual(sys.getrefcount(None), c+1)
253 del n
254 self.assertEqual(sys.getrefcount(None), c)
255 if hasattr(sys, "gettotalrefcount"):
256 self.assert_(isinstance(sys.gettotalrefcount(), int))
257
258 def test_getframe(self):
259 self.assertRaises(TypeError, sys._getframe, 42, 42)
Neal Norwitzeb2a5ef2003-02-18 15:22:10 +0000260 self.assertRaises(ValueError, sys._getframe, 2000000000)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000261 self.assert_(
262 SysModuleTest.test_getframe.im_func.func_code \
263 is sys._getframe().f_code
264 )
265
Tim Peters32a83612006-07-10 21:08:24 +0000266 # sys._current_frames() is a CPython-only gimmick.
267 def test_current_frames(self):
Tim Peters112aad32006-07-19 00:03:19 +0000268 have_threads = True
269 try:
270 import thread
271 except ImportError:
272 have_threads = False
273
274 if have_threads:
275 self.current_frames_with_threads()
276 else:
277 self.current_frames_without_threads()
278
279 # Test sys._current_frames() in a WITH_THREADS build.
280 def current_frames_with_threads(self):
Tim Peters32a83612006-07-10 21:08:24 +0000281 import threading, thread
282 import traceback
283
284 # Spawn a thread that blocks at a known place. Then the main
285 # thread does sys._current_frames(), and verifies that the frames
286 # returned make sense.
287 entered_g = threading.Event()
288 leave_g = threading.Event()
289 thread_info = [] # the thread's id
290
291 def f123():
292 g456()
293
294 def g456():
295 thread_info.append(thread.get_ident())
296 entered_g.set()
297 leave_g.wait()
298
299 t = threading.Thread(target=f123)
300 t.start()
301 entered_g.wait()
302
Tim Peters0c4a3b32006-07-25 04:07:22 +0000303 # At this point, t has finished its entered_g.set(), although it's
304 # impossible to guess whether it's still on that line or has moved on
305 # to its leave_g.wait().
Tim Peters32a83612006-07-10 21:08:24 +0000306 self.assertEqual(len(thread_info), 1)
307 thread_id = thread_info[0]
308
309 d = sys._current_frames()
310
311 main_id = thread.get_ident()
312 self.assert_(main_id in d)
313 self.assert_(thread_id in d)
314
315 # Verify that the captured main-thread frame is _this_ frame.
316 frame = d.pop(main_id)
317 self.assert_(frame is sys._getframe())
318
319 # Verify that the captured thread frame is blocked in g456, called
320 # from f123. This is a litte tricky, since various bits of
321 # threading.py are also in the thread's call stack.
322 frame = d.pop(thread_id)
323 stack = traceback.extract_stack(frame)
324 for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
325 if funcname == "f123":
326 break
327 else:
328 self.fail("didn't find f123() on thread's call stack")
329
330 self.assertEqual(sourceline, "g456()")
331
332 # And the next record must be for g456().
333 filename, lineno, funcname, sourceline = stack[i+1]
334 self.assertEqual(funcname, "g456")
Tim Peters0c4a3b32006-07-25 04:07:22 +0000335 self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"])
Tim Peters32a83612006-07-10 21:08:24 +0000336
337 # Reap the spawned thread.
338 leave_g.set()
339 t.join()
340
Tim Peters112aad32006-07-19 00:03:19 +0000341 # Test sys._current_frames() when thread support doesn't exist.
342 def current_frames_without_threads(self):
343 # Not much happens here: there is only one thread, with artificial
344 # "thread id" 0.
345 d = sys._current_frames()
346 self.assertEqual(len(d), 1)
347 self.assert_(0 in d)
348 self.assert_(d[0] is sys._getframe())
349
Walter Dörwaldc3502462003-02-03 23:03:49 +0000350 def test_attributes(self):
351 self.assert_(isinstance(sys.api_version, int))
352 self.assert_(isinstance(sys.argv, list))
353 self.assert_(sys.byteorder in ("little", "big"))
354 self.assert_(isinstance(sys.builtin_module_names, tuple))
355 self.assert_(isinstance(sys.copyright, basestring))
356 self.assert_(isinstance(sys.exec_prefix, basestring))
357 self.assert_(isinstance(sys.executable, basestring))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000358 self.assertEqual(len(sys.float_info), 11)
Christian Heimesc94e2b52008-01-14 04:13:37 +0000359 self.assertEqual(sys.float_info.radix, 2)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000360 self.assert_(isinstance(sys.hexversion, int))
361 self.assert_(isinstance(sys.maxint, int))
Walter Dörwald4e41a4b2005-08-03 17:09:04 +0000362 if test.test_support.have_unicode:
363 self.assert_(isinstance(sys.maxunicode, int))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000364 self.assert_(isinstance(sys.platform, basestring))
365 self.assert_(isinstance(sys.prefix, basestring))
366 self.assert_(isinstance(sys.version, basestring))
367 vi = sys.version_info
368 self.assert_(isinstance(vi, tuple))
369 self.assertEqual(len(vi), 5)
370 self.assert_(isinstance(vi[0], int))
371 self.assert_(isinstance(vi[1], int))
372 self.assert_(isinstance(vi[2], int))
373 self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
374 self.assert_(isinstance(vi[4], int))
375
Martin v. Löwisa8cd7a22006-04-03 11:05:39 +0000376 def test_43581(self):
377 # Can't use sys.stdout, as this is a cStringIO object when
378 # the test runs under regrtest.
379 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
380
Christian Heimesf31b69f2008-01-14 03:42:48 +0000381 def test_sys_flags(self):
382 self.failUnless(sys.flags)
383 attrs = ("debug", "py3k_warning", "division_warning", "division_new",
384 "inspect", "interactive", "optimize", "dont_write_bytecode",
Andrew M. Kuchling7ce9b182008-01-15 01:29:16 +0000385 "no_site", "ignore_environment", "tabcheck", "verbose",
Brett Cannonbe1501b2008-05-08 20:23:06 +0000386 "unicode", "bytes_warning")
Christian Heimesf31b69f2008-01-14 03:42:48 +0000387 for attr in attrs:
388 self.assert_(hasattr(sys.flags, attr), attr)
389 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
390 self.assert_(repr(sys.flags))
391
Christian Heimes422051a2008-02-04 18:00:12 +0000392 def test_clear_type_cache(self):
393 sys._clear_type_cache()
394
Martin v. Löwis99815892008-06-01 07:20:46 +0000395 def test_ioencoding(self):
396 import subprocess,os
397 env = dict(os.environ)
398
399 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
400 # not representable in ASCII.
401
402 env["PYTHONIOENCODING"] = "cp424"
403 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
404 stdout = subprocess.PIPE, env=env)
405 out = p.stdout.read().strip()
406 self.assertEqual(out, unichr(0xa2).encode("cp424"))
407
408 env["PYTHONIOENCODING"] = "ascii:replace"
409 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
410 stdout = subprocess.PIPE, env=env)
411 out = p.stdout.read().strip()
412 self.assertEqual(out, '?')
413
Victor Stinnerd85f1c02010-01-31 22:33:22 +0000414 def test_call_tracing(self):
415 self.assertEqual(sys.call_tracing(str, (2,)), "2")
416 self.assertRaises(TypeError, sys.call_tracing, str, 2)
417
Victor Stinner872d6362010-03-21 13:47:28 +0000418 def test_executable(self):
419 # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
420 # has been set to an non existent program name and Python is unable to
421 # retrieve the real program name
422 import subprocess
423 # For a normal installation, it should work without 'cwd'
424 # argument. For test runs in the build directory, see #7774.
425 python_dir = os.path.dirname(os.path.realpath(sys.executable))
426 p = subprocess.Popen(
427 ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
428 executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
429 executable = p.communicate()[0].strip()
430 p.wait()
431 self.assert_(executable in ["''", repr(sys.executable)], executable)
Martin v. Löwis99815892008-06-01 07:20:46 +0000432
Robert Schuppenies51df0642008-06-01 16:16:17 +0000433class SizeofTest(unittest.TestCase):
434
Robert Schuppenies47629022008-07-10 17:13:55 +0000435 TPFLAGS_HAVE_GC = 1<<14
436 TPFLAGS_HEAPTYPE = 1L<<9
437
Robert Schuppenies51df0642008-06-01 16:16:17 +0000438 def setUp(self):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000439 self.c = len(struct.pack('c', ' '))
440 self.H = len(struct.pack('H', 0))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000441 self.i = len(struct.pack('i', 0))
442 self.l = len(struct.pack('l', 0))
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000443 self.P = len(struct.pack('P', 0))
444 # due to missing size_t information from struct, it is assumed that
445 # sizeof(Py_ssize_t) = sizeof(void*)
Robert Schuppenies161b9212008-06-26 15:20:35 +0000446 self.header = 'PP'
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000447 self.vheader = self.header + 'P'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000448 if hasattr(sys, "gettotalrefcount"):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000449 self.header += '2P'
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000450 self.vheader += '2P'
Robert Schuppenies47629022008-07-10 17:13:55 +0000451 import _testcapi
452 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
Robert Schuppenies51df0642008-06-01 16:16:17 +0000453 self.file = open(test.test_support.TESTFN, 'wb')
454
455 def tearDown(self):
456 self.file.close()
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000457 test.test_support.unlink(test.test_support.TESTFN)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000458
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000459 def check_sizeof(self, o, size):
Robert Schuppenies51df0642008-06-01 16:16:17 +0000460 result = sys.getsizeof(o)
Robert Schuppenies47629022008-07-10 17:13:55 +0000461 if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
462 ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
463 size += self.gc_headsize
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000464 msg = 'wrong size for %s: got %d, expected %d' \
465 % (type(o), result, size)
466 self.assertEqual(result, size, msg)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000467
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000468 def calcsize(self, fmt):
469 """Wrapper around struct.calcsize which enforces the alignment of the
470 end of a structure to the alignment requirement of pointer.
Robert Schuppenies51df0642008-06-01 16:16:17 +0000471
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000472 Note: This wrapper should only be used if a pointer member is included
473 and no member with a size larger than a pointer exists.
474 """
475 return struct.calcsize(fmt + '0P')
Robert Schuppenies51df0642008-06-01 16:16:17 +0000476
Robert Schuppenies47629022008-07-10 17:13:55 +0000477 def test_gc_head_size(self):
478 # Check that the gc header size is added to objects tracked by the gc.
479 h = self.header
480 size = self.calcsize
481 gc_header_size = self.gc_headsize
482 # bool objects are not gc tracked
483 self.assertEqual(sys.getsizeof(True), size(h + 'l'))
484 # but lists are
485 self.assertEqual(sys.getsizeof([]), size(h + 'P PP') + gc_header_size)
486
487 def test_default(self):
488 h = self.header
489 size = self.calcsize
490 self.assertEqual(sys.getsizeof(True, -1), size(h + 'l'))
491
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000492 def test_objecttypes(self):
493 # check all types defined in Objects/
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000494 h = self.header
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000495 vh = self.vheader
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000496 size = self.calcsize
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000497 check = self.check_sizeof
Robert Schuppenies51df0642008-06-01 16:16:17 +0000498 # bool
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000499 check(True, size(h + 'l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000500 # buffer
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000501 check(buffer(''), size(h + '2P2Pil'))
502 # builtin_function_or_method
503 check(len, size(h + '3P'))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000504 # bytearray
505 samples = ['', 'u'*100000]
506 for sample in samples:
507 x = bytearray(sample)
508 check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
509 # bytearray_iterator
510 check(iter(bytearray()), size(h + 'PP'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000511 # cell
512 def get_cell():
513 x = 42
514 def inner():
515 return x
516 return inner
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000517 check(get_cell().func_closure[0], size(h + 'P'))
518 # classobj (old-style class)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000519 class class_oldstyle():
520 def method():
521 pass
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000522 check(class_oldstyle, size(h + '6P'))
523 # instance (old-style class)
524 check(class_oldstyle(), size(h + '3P'))
525 # instancemethod (old-style class)
526 check(class_oldstyle().method, size(h + '4P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000527 # complex
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000528 check(complex(0,1), size(h + '2d'))
529 # code
530 check(get_cell().func_code, size(h + '4i8Pi2P'))
531 # BaseException
532 check(BaseException(), size(h + '3P'))
533 # UnicodeEncodeError
534 check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP'))
535 # UnicodeDecodeError
536 check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
537 # UnicodeTranslateError
538 check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP'))
539 # method_descriptor (descriptor object)
540 check(str.lower, size(h + '2PP'))
541 # classmethod_descriptor (descriptor object)
542 # XXX
543 # member_descriptor (descriptor object)
544 import datetime
545 check(datetime.timedelta.days, size(h + '2PP'))
546 # getset_descriptor (descriptor object)
547 import __builtin__
548 check(__builtin__.file.closed, size(h + '2PP'))
549 # wrapper_descriptor (descriptor object)
550 check(int.__add__, size(h + '2P2P'))
551 # dictproxy
552 class C(object): pass
553 check(C.__dict__, size(h + 'P'))
554 # method-wrapper (descriptor object)
555 check({}.__iter__, size(h + '2P'))
556 # dict
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000557 check({}, size(h + '3P2P' + 8*'P2P'))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000558 x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000559 check(x, size(h + '3P2P' + 8*'P2P') + 16*size('P2P'))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000560 # dictionary-keyiterator
561 check({}.iterkeys(), size(h + 'P2PPP'))
562 # dictionary-valueiterator
563 check({}.itervalues(), size(h + 'P2PPP'))
564 # dictionary-itemiterator
565 check({}.iteritems(), size(h + 'P2PPP'))
566 # ellipses
567 check(Ellipsis, size(h + ''))
568 # EncodingMap
569 import codecs, encodings.iso8859_3
570 x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
571 check(x, size(h + '32B2iB'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000572 # enumerate
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000573 check(enumerate([]), size(h + 'l3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000574 # file
Antoine Pitrou24837282010-02-05 17:11:32 +0000575 check(self.file, size(h + '4P2i4P3i3P3i'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000576 # float
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000577 check(float(0), size(h + 'd'))
578 # sys.floatinfo
579 check(sys.float_info, size(vh) + self.P * len(sys.float_info))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000580 # frame
581 import inspect
582 CO_MAXBLOCKS = 20
583 x = inspect.currentframe()
584 ncells = len(x.f_code.co_cellvars)
585 nfrees = len(x.f_code.co_freevars)
586 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
587 ncells + nfrees - 1
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000588 check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000589 # function
590 def func(): pass
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000591 check(func, size(h + '9P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000592 class c():
593 @staticmethod
594 def foo():
595 pass
596 @classmethod
597 def bar(cls):
598 pass
599 # staticmethod
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000600 check(foo, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000601 # classmethod
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000602 check(bar, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000603 # generator
604 def get_gen(): yield 1
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000605 check(get_gen(), size(h + 'Pi2P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000606 # integer
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000607 check(1, size(h + 'l'))
608 check(100, size(h + 'l'))
609 # iterator
610 check(iter('abc'), size(h + 'lP'))
611 # callable-iterator
612 import re
613 check(re.finditer('',''), size(h + '2P'))
614 # list
615 samples = [[], [1,2,3], ['1', '2', '3']]
616 for sample in samples:
617 check(sample, size(vh + 'PP') + len(sample)*self.P)
618 # sortwrapper (list)
619 # XXX
620 # cmpwrapper (list)
621 # XXX
622 # listiterator (list)
623 check(iter([]), size(h + 'lP'))
624 # listreverseiterator (list)
625 check(reversed([]), size(h + 'lP'))
626 # long
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000627 check(0L, size(vh + 'H') - self.H)
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000628 check(1L, size(vh + 'H'))
629 check(-1L, size(vh + 'H'))
630 check(32768L, size(vh + 'H') + self.H)
631 check(32768L*32768L-1, size(vh + 'H') + self.H)
632 check(32768L*32768L, size(vh + 'H') + 2*self.H)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000633 # module
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000634 check(unittest, size(h + 'P'))
635 # None
636 check(None, size(h + ''))
637 # object
638 check(object(), size(h + ''))
639 # property (descriptor object)
640 class C(object):
641 def getx(self): return self.__x
642 def setx(self, value): self.__x = value
643 def delx(self): del self.__x
644 x = property(getx, setx, delx, "")
645 check(x, size(h + '4Pi'))
646 # PyCObject
647 # XXX
648 # rangeiterator
649 check(iter(xrange(1)), size(h + '4l'))
650 # reverse
651 check(reversed(''), size(h + 'PP'))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000652 # set
653 # frozenset
654 PySet_MINSIZE = 8
655 samples = [[], range(10), range(50)]
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000656 s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP')
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000657 for sample in samples:
658 minused = len(sample)
659 if minused == 0: tmp = 1
660 # the computation of minused is actually a bit more complicated
661 # but this suffices for the sizeof test
662 minused = minused*2
663 newsize = PySet_MINSIZE
664 while newsize <= minused:
665 newsize = newsize << 1
666 if newsize <= 8:
667 check(set(sample), s)
668 check(frozenset(sample), s)
669 else:
670 check(set(sample), s + newsize*struct.calcsize('lP'))
671 check(frozenset(sample), s + newsize*struct.calcsize('lP'))
672 # setiterator
673 check(iter(set()), size(h + 'P3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000674 # slice
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000675 check(slice(1), size(h + '3P'))
676 # str
677 check('', size(vh + 'lic'))
678 check('abc', size(vh + 'lic') + 3*self.c)
679 # super
680 check(super(int), size(h + '3P'))
681 # tuple
682 check((), size(vh))
683 check((1,2,3), size(vh) + 3*self.P)
684 # tupleiterator
685 check(iter(()), size(h + 'lP'))
686 # type
687 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
688 # PySequenceMethods + PyBufferProcs)
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000689 s = size(vh + 'P2P15Pl4PP9PP11PI') + size('41P 10P 3P 6P')
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000690 class newstyleclass(object):
691 pass
692 check(newstyleclass, s)
693 # builtin type
694 check(int, s)
695 # NotImplementedType
696 import types
697 check(types.NotImplementedType, s)
Robert Schuppenies901c9972008-06-10 10:10:31 +0000698 # unicode
Robert Schuppenies59f3ade2008-06-17 08:42:15 +0000699 usize = len(u'\0'.encode('unicode-internal'))
Robert Schuppenies901c9972008-06-10 10:10:31 +0000700 samples = [u'', u'1'*100]
701 # we need to test for both sizes, because we don't know if the string
702 # has been cached
703 for s in samples:
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000704 check(s, size(h + 'PPlP') + usize * (len(s) + 1))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000705 # weakref
706 import weakref
707 check(weakref.ref(int), size(h + '2Pl2P'))
708 # weakproxy
709 # XXX
710 # weakcallableproxy
711 check(weakref.proxy(int), size(h + '2Pl2P'))
712 # xrange
713 check(xrange(1), size(h + '3l'))
714 check(xrange(66000), size(h + '3l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000715
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000716 def test_pythontypes(self):
717 # check all types defined in Python/
718 h = self.header
719 vh = self.vheader
720 size = self.calcsize
721 check = self.check_sizeof
722 # _ast.AST
723 import _ast
724 check(_ast.AST(), size(h + ''))
725 # imp.NullImporter
726 import imp
727 check(imp.NullImporter(self.file.name), size(h + ''))
728 try:
729 raise TypeError
730 except TypeError:
731 tb = sys.exc_info()[2]
732 # traceback
733 if tb != None:
734 check(tb, size(h + '2P2i'))
735 # symtable entry
736 # XXX
737 # sys.flags
738 check(sys.flags, size(vh) + self.P * len(sys.flags))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000739
740
Walter Dörwaldc3502462003-02-03 23:03:49 +0000741def test_main():
Robert Schuppenies51df0642008-06-01 16:16:17 +0000742 test_classes = (SysModuleTest, SizeofTest)
743
744 test.test_support.run_unittest(*test_classes)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000745
746if __name__ == "__main__":
747 test_main()