blob: e82569ac02c23cbb05135a8a8822b504694a97d4 [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
Ezio Melotti3efafd72010-08-02 18:40:55 +000078 with test.test_support._check_py3k_warnings():
79 sys.exc_clear()
Guido van Rossum46d3dc32003-03-01 03:20:41 +000080
Guido van Rossumd6473d12003-03-01 03:25:41 +000081 typ, value, traceback = sys.exc_info()
82 self.assert_(typ is None)
83 self.assert_(value is None)
84 self.assert_(traceback is None)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000085
86 def clear():
Guido van Rossumd6473d12003-03-01 03:25:41 +000087 try:
88 raise ValueError, 42
89 except ValueError, exc:
90 clear_check(exc)
Guido van Rossum46d3dc32003-03-01 03:20:41 +000091
92 # Raise an exception and check that it can be cleared
93 clear()
94
95 # Verify that a frame currently handling an exception is
96 # unaffected by calling exc_clear in a nested frame.
97 try:
Guido van Rossumd6473d12003-03-01 03:25:41 +000098 raise ValueError, 13
Guido van Rossum46d3dc32003-03-01 03:20:41 +000099 except ValueError, exc:
Guido van Rossumd6473d12003-03-01 03:25:41 +0000100 typ1, value1, traceback1 = sys.exc_info()
101 clear()
102 typ2, value2, traceback2 = sys.exc_info()
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000103
Guido van Rossumd6473d12003-03-01 03:25:41 +0000104 self.assert_(typ1 is typ2)
105 self.assert_(value1 is exc)
106 self.assert_(value1 is value2)
107 self.assert_(traceback1 is traceback2)
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000108
109 # Check that an exception can be cleared outside of an except block
110 clear_check(exc)
111
Walter Dörwaldc3502462003-02-03 23:03:49 +0000112 def test_exit(self):
113 self.assertRaises(TypeError, sys.exit, 42, 42)
114
115 # call without argument
116 try:
117 sys.exit(0)
118 except SystemExit, exc:
119 self.assertEquals(exc.code, 0)
120 except:
121 self.fail("wrong exception")
122 else:
123 self.fail("no exception")
124
125 # call with tuple argument with one entry
126 # entry will be unpacked
127 try:
128 sys.exit(42)
129 except SystemExit, exc:
130 self.assertEquals(exc.code, 42)
131 except:
132 self.fail("wrong exception")
133 else:
134 self.fail("no exception")
135
136 # call with integer argument
137 try:
138 sys.exit((42,))
139 except SystemExit, exc:
140 self.assertEquals(exc.code, 42)
141 except:
142 self.fail("wrong exception")
143 else:
144 self.fail("no exception")
145
146 # call with string argument
147 try:
148 sys.exit("exit")
149 except SystemExit, exc:
150 self.assertEquals(exc.code, "exit")
151 except:
152 self.fail("wrong exception")
153 else:
154 self.fail("no exception")
155
156 # call with tuple argument with two entries
157 try:
158 sys.exit((17, 23))
159 except SystemExit, exc:
160 self.assertEquals(exc.code, (17, 23))
161 except:
162 self.fail("wrong exception")
163 else:
164 self.fail("no exception")
165
Michael W. Hudsonf0588582005-02-15 15:26:11 +0000166 # test that the exit machinery handles SystemExits properly
167 import subprocess
168 # both unnormalized...
169 rc = subprocess.call([sys.executable, "-c",
170 "raise SystemExit, 46"])
171 self.assertEqual(rc, 46)
172 # ... and normalized
173 rc = subprocess.call([sys.executable, "-c",
174 "raise SystemExit(47)"])
175 self.assertEqual(rc, 47)
Tim Petersf0db38d2005-02-15 21:50:12 +0000176
Victor Stinnerc3e40e02010-05-25 22:40:38 +0000177 def check_exit_message(code, expected, env=None):
178 process = subprocess.Popen([sys.executable, "-c", code],
179 stderr=subprocess.PIPE, env=env)
180 stdout, stderr = process.communicate()
181 self.assertEqual(process.returncode, 1)
182 self.assertTrue(stderr.startswith(expected),
183 "%s doesn't start with %s" % (repr(stderr), repr(expected)))
184
185 # test that stderr buffer if flushed before the exit message is written
186 # into stderr
187 check_exit_message(
188 r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
189 b"unflushed,message")
190
191 # test that the unicode message is encoded to the stderr encoding
192 env = os.environ.copy()
193 env['PYTHONIOENCODING'] = 'latin-1'
194 check_exit_message(
195 r'import sys; sys.exit(u"h\xe9")',
196 b"h\xe9", env=env)
Tim Petersf0db38d2005-02-15 21:50:12 +0000197
Walter Dörwaldc3502462003-02-03 23:03:49 +0000198 def test_getdefaultencoding(self):
199 if test.test_support.have_unicode:
200 self.assertRaises(TypeError, sys.getdefaultencoding, 42)
201 # can't check more than the type, as the user might have changed it
202 self.assert_(isinstance(sys.getdefaultencoding(), str))
203
204 # testing sys.settrace() is done in test_trace.py
205 # testing sys.setprofile() is done in test_profile.py
206
207 def test_setcheckinterval(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000208 self.assertRaises(TypeError, sys.setcheckinterval)
Tim Peterse5e065b2003-07-06 18:36:54 +0000209 orig = sys.getcheckinterval()
210 for n in 0, 100, 120, orig: # orig last to restore starting state
211 sys.setcheckinterval(n)
212 self.assertEquals(sys.getcheckinterval(), n)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000213
214 def test_recursionlimit(self):
Tim Petersf2715e02003-02-19 02:35:07 +0000215 self.assertRaises(TypeError, sys.getrecursionlimit, 42)
216 oldlimit = sys.getrecursionlimit()
217 self.assertRaises(TypeError, sys.setrecursionlimit)
218 self.assertRaises(ValueError, sys.setrecursionlimit, -42)
219 sys.setrecursionlimit(10000)
220 self.assertEqual(sys.getrecursionlimit(), 10000)
221 sys.setrecursionlimit(oldlimit)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000222
223 def test_getwindowsversion(self):
224 if hasattr(sys, "getwindowsversion"):
225 v = sys.getwindowsversion()
226 self.assert_(isinstance(v, tuple))
227 self.assertEqual(len(v), 5)
228 self.assert_(isinstance(v[0], int))
229 self.assert_(isinstance(v[1], int))
230 self.assert_(isinstance(v[2], int))
231 self.assert_(isinstance(v[3], int))
232 self.assert_(isinstance(v[4], str))
233
234 def test_dlopenflags(self):
235 if hasattr(sys, "setdlopenflags"):
236 self.assert_(hasattr(sys, "getdlopenflags"))
237 self.assertRaises(TypeError, sys.getdlopenflags, 42)
238 oldflags = sys.getdlopenflags()
239 self.assertRaises(TypeError, sys.setdlopenflags)
240 sys.setdlopenflags(oldflags+1)
241 self.assertEqual(sys.getdlopenflags(), oldflags+1)
242 sys.setdlopenflags(oldflags)
243
244 def test_refcount(self):
Georg Brandl9b08e052009-04-05 21:21:05 +0000245 # n here must be a global in order for this test to pass while
246 # tracing with a python function. Tracing calls PyFrame_FastToLocals
247 # which will add a copy of any locals to the frame object, causing
248 # the reference count to increase by 2 instead of 1.
249 global n
Walter Dörwaldc3502462003-02-03 23:03:49 +0000250 self.assertRaises(TypeError, sys.getrefcount)
251 c = sys.getrefcount(None)
252 n = None
253 self.assertEqual(sys.getrefcount(None), c+1)
254 del n
255 self.assertEqual(sys.getrefcount(None), c)
256 if hasattr(sys, "gettotalrefcount"):
257 self.assert_(isinstance(sys.gettotalrefcount(), int))
258
259 def test_getframe(self):
260 self.assertRaises(TypeError, sys._getframe, 42, 42)
Neal Norwitzeb2a5ef2003-02-18 15:22:10 +0000261 self.assertRaises(ValueError, sys._getframe, 2000000000)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000262 self.assert_(
263 SysModuleTest.test_getframe.im_func.func_code \
264 is sys._getframe().f_code
265 )
266
Tim Peters32a83612006-07-10 21:08:24 +0000267 # sys._current_frames() is a CPython-only gimmick.
268 def test_current_frames(self):
Tim Peters112aad32006-07-19 00:03:19 +0000269 have_threads = True
270 try:
271 import thread
272 except ImportError:
273 have_threads = False
274
275 if have_threads:
276 self.current_frames_with_threads()
277 else:
278 self.current_frames_without_threads()
279
280 # Test sys._current_frames() in a WITH_THREADS build.
281 def current_frames_with_threads(self):
Tim Peters32a83612006-07-10 21:08:24 +0000282 import threading, thread
283 import traceback
284
285 # Spawn a thread that blocks at a known place. Then the main
286 # thread does sys._current_frames(), and verifies that the frames
287 # returned make sense.
288 entered_g = threading.Event()
289 leave_g = threading.Event()
290 thread_info = [] # the thread's id
291
292 def f123():
293 g456()
294
295 def g456():
296 thread_info.append(thread.get_ident())
297 entered_g.set()
298 leave_g.wait()
299
300 t = threading.Thread(target=f123)
301 t.start()
302 entered_g.wait()
303
Tim Peters0c4a3b32006-07-25 04:07:22 +0000304 # At this point, t has finished its entered_g.set(), although it's
305 # impossible to guess whether it's still on that line or has moved on
306 # to its leave_g.wait().
Tim Peters32a83612006-07-10 21:08:24 +0000307 self.assertEqual(len(thread_info), 1)
308 thread_id = thread_info[0]
309
310 d = sys._current_frames()
311
312 main_id = thread.get_ident()
313 self.assert_(main_id in d)
314 self.assert_(thread_id in d)
315
316 # Verify that the captured main-thread frame is _this_ frame.
317 frame = d.pop(main_id)
318 self.assert_(frame is sys._getframe())
319
320 # Verify that the captured thread frame is blocked in g456, called
321 # from f123. This is a litte tricky, since various bits of
322 # threading.py are also in the thread's call stack.
323 frame = d.pop(thread_id)
324 stack = traceback.extract_stack(frame)
325 for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
326 if funcname == "f123":
327 break
328 else:
329 self.fail("didn't find f123() on thread's call stack")
330
331 self.assertEqual(sourceline, "g456()")
332
333 # And the next record must be for g456().
334 filename, lineno, funcname, sourceline = stack[i+1]
335 self.assertEqual(funcname, "g456")
Tim Peters0c4a3b32006-07-25 04:07:22 +0000336 self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"])
Tim Peters32a83612006-07-10 21:08:24 +0000337
338 # Reap the spawned thread.
339 leave_g.set()
340 t.join()
341
Tim Peters112aad32006-07-19 00:03:19 +0000342 # Test sys._current_frames() when thread support doesn't exist.
343 def current_frames_without_threads(self):
344 # Not much happens here: there is only one thread, with artificial
345 # "thread id" 0.
346 d = sys._current_frames()
347 self.assertEqual(len(d), 1)
348 self.assert_(0 in d)
349 self.assert_(d[0] is sys._getframe())
350
Walter Dörwaldc3502462003-02-03 23:03:49 +0000351 def test_attributes(self):
352 self.assert_(isinstance(sys.api_version, int))
353 self.assert_(isinstance(sys.argv, list))
354 self.assert_(sys.byteorder in ("little", "big"))
355 self.assert_(isinstance(sys.builtin_module_names, tuple))
356 self.assert_(isinstance(sys.copyright, basestring))
357 self.assert_(isinstance(sys.exec_prefix, basestring))
358 self.assert_(isinstance(sys.executable, basestring))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000359 self.assertEqual(len(sys.float_info), 11)
Christian Heimesc94e2b52008-01-14 04:13:37 +0000360 self.assertEqual(sys.float_info.radix, 2)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000361 self.assert_(isinstance(sys.hexversion, int))
362 self.assert_(isinstance(sys.maxint, int))
Walter Dörwald4e41a4b2005-08-03 17:09:04 +0000363 if test.test_support.have_unicode:
364 self.assert_(isinstance(sys.maxunicode, int))
Walter Dörwaldc3502462003-02-03 23:03:49 +0000365 self.assert_(isinstance(sys.platform, basestring))
366 self.assert_(isinstance(sys.prefix, basestring))
367 self.assert_(isinstance(sys.version, basestring))
368 vi = sys.version_info
369 self.assert_(isinstance(vi, tuple))
370 self.assertEqual(len(vi), 5)
371 self.assert_(isinstance(vi[0], int))
372 self.assert_(isinstance(vi[1], int))
373 self.assert_(isinstance(vi[2], int))
374 self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
375 self.assert_(isinstance(vi[4], int))
376
Martin v. Löwisa8cd7a22006-04-03 11:05:39 +0000377 def test_43581(self):
378 # Can't use sys.stdout, as this is a cStringIO object when
379 # the test runs under regrtest.
380 self.assert_(sys.__stdout__.encoding == sys.__stderr__.encoding)
381
Christian Heimesf31b69f2008-01-14 03:42:48 +0000382 def test_sys_flags(self):
383 self.failUnless(sys.flags)
384 attrs = ("debug", "py3k_warning", "division_warning", "division_new",
385 "inspect", "interactive", "optimize", "dont_write_bytecode",
Andrew M. Kuchling7ce9b182008-01-15 01:29:16 +0000386 "no_site", "ignore_environment", "tabcheck", "verbose",
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500387 "unicode", "bytes_warning", "hash_randomization")
Christian Heimesf31b69f2008-01-14 03:42:48 +0000388 for attr in attrs:
389 self.assert_(hasattr(sys.flags, attr), attr)
390 self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
391 self.assert_(repr(sys.flags))
392
Christian Heimes422051a2008-02-04 18:00:12 +0000393 def test_clear_type_cache(self):
394 sys._clear_type_cache()
395
Martin v. Löwis99815892008-06-01 07:20:46 +0000396 def test_ioencoding(self):
397 import subprocess,os
398 env = dict(os.environ)
399
400 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
401 # not representable in ASCII.
402
403 env["PYTHONIOENCODING"] = "cp424"
404 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
405 stdout = subprocess.PIPE, env=env)
406 out = p.stdout.read().strip()
407 self.assertEqual(out, unichr(0xa2).encode("cp424"))
408
409 env["PYTHONIOENCODING"] = "ascii:replace"
410 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
411 stdout = subprocess.PIPE, env=env)
412 out = p.stdout.read().strip()
413 self.assertEqual(out, '?')
414
Victor Stinnerd85f1c02010-01-31 22:33:22 +0000415 def test_call_tracing(self):
416 self.assertEqual(sys.call_tracing(str, (2,)), "2")
417 self.assertRaises(TypeError, sys.call_tracing, str, 2)
418
Victor Stinner872d6362010-03-21 13:47:28 +0000419 def test_executable(self):
420 # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
421 # has been set to an non existent program name and Python is unable to
422 # retrieve the real program name
423 import subprocess
424 # For a normal installation, it should work without 'cwd'
425 # argument. For test runs in the build directory, see #7774.
426 python_dir = os.path.dirname(os.path.realpath(sys.executable))
427 p = subprocess.Popen(
428 ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
429 executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
430 executable = p.communicate()[0].strip()
431 p.wait()
432 self.assert_(executable in ["''", repr(sys.executable)], executable)
Martin v. Löwis99815892008-06-01 07:20:46 +0000433
Robert Schuppenies51df0642008-06-01 16:16:17 +0000434class SizeofTest(unittest.TestCase):
435
Robert Schuppenies47629022008-07-10 17:13:55 +0000436 TPFLAGS_HAVE_GC = 1<<14
437 TPFLAGS_HEAPTYPE = 1L<<9
438
Robert Schuppenies51df0642008-06-01 16:16:17 +0000439 def setUp(self):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000440 self.c = len(struct.pack('c', ' '))
441 self.H = len(struct.pack('H', 0))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000442 self.i = len(struct.pack('i', 0))
443 self.l = len(struct.pack('l', 0))
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000444 self.P = len(struct.pack('P', 0))
445 # due to missing size_t information from struct, it is assumed that
446 # sizeof(Py_ssize_t) = sizeof(void*)
Robert Schuppenies161b9212008-06-26 15:20:35 +0000447 self.header = 'PP'
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000448 self.vheader = self.header + 'P'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000449 if hasattr(sys, "gettotalrefcount"):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000450 self.header += '2P'
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000451 self.vheader += '2P'
Robert Schuppenies47629022008-07-10 17:13:55 +0000452 import _testcapi
453 self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
Robert Schuppenies51df0642008-06-01 16:16:17 +0000454 self.file = open(test.test_support.TESTFN, 'wb')
455
456 def tearDown(self):
457 self.file.close()
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000458 test.test_support.unlink(test.test_support.TESTFN)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000459
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000460 def check_sizeof(self, o, size):
Robert Schuppenies51df0642008-06-01 16:16:17 +0000461 result = sys.getsizeof(o)
Robert Schuppenies47629022008-07-10 17:13:55 +0000462 if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
463 ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
464 size += self.gc_headsize
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000465 msg = 'wrong size for %s: got %d, expected %d' \
466 % (type(o), result, size)
467 self.assertEqual(result, size, msg)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000468
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000469 def calcsize(self, fmt):
470 """Wrapper around struct.calcsize which enforces the alignment of the
471 end of a structure to the alignment requirement of pointer.
Robert Schuppenies51df0642008-06-01 16:16:17 +0000472
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000473 Note: This wrapper should only be used if a pointer member is included
474 and no member with a size larger than a pointer exists.
475 """
476 return struct.calcsize(fmt + '0P')
Robert Schuppenies51df0642008-06-01 16:16:17 +0000477
Robert Schuppenies47629022008-07-10 17:13:55 +0000478 def test_gc_head_size(self):
479 # Check that the gc header size is added to objects tracked by the gc.
480 h = self.header
481 size = self.calcsize
482 gc_header_size = self.gc_headsize
483 # bool objects are not gc tracked
484 self.assertEqual(sys.getsizeof(True), size(h + 'l'))
485 # but lists are
486 self.assertEqual(sys.getsizeof([]), size(h + 'P PP') + gc_header_size)
487
488 def test_default(self):
489 h = self.header
490 size = self.calcsize
491 self.assertEqual(sys.getsizeof(True, -1), size(h + 'l'))
492
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000493 def test_objecttypes(self):
494 # check all types defined in Objects/
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000495 h = self.header
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000496 vh = self.vheader
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000497 size = self.calcsize
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000498 check = self.check_sizeof
Robert Schuppenies51df0642008-06-01 16:16:17 +0000499 # bool
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000500 check(True, size(h + 'l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000501 # buffer
Ezio Melotti3efafd72010-08-02 18:40:55 +0000502 with test.test_support._check_py3k_warnings():
503 check(buffer(''), size(h + '2P2Pil'))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000504 # builtin_function_or_method
505 check(len, size(h + '3P'))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000506 # bytearray
507 samples = ['', 'u'*100000]
508 for sample in samples:
509 x = bytearray(sample)
510 check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
511 # bytearray_iterator
512 check(iter(bytearray()), size(h + 'PP'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000513 # cell
514 def get_cell():
515 x = 42
516 def inner():
517 return x
518 return inner
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000519 check(get_cell().func_closure[0], size(h + 'P'))
520 # classobj (old-style class)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000521 class class_oldstyle():
522 def method():
523 pass
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000524 check(class_oldstyle, size(h + '6P'))
525 # instance (old-style class)
526 check(class_oldstyle(), size(h + '3P'))
527 # instancemethod (old-style class)
528 check(class_oldstyle().method, size(h + '4P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000529 # complex
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000530 check(complex(0,1), size(h + '2d'))
531 # code
532 check(get_cell().func_code, size(h + '4i8Pi2P'))
533 # BaseException
534 check(BaseException(), size(h + '3P'))
535 # UnicodeEncodeError
536 check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP'))
537 # UnicodeDecodeError
538 check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
539 # UnicodeTranslateError
540 check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP'))
541 # method_descriptor (descriptor object)
542 check(str.lower, size(h + '2PP'))
543 # classmethod_descriptor (descriptor object)
544 # XXX
545 # member_descriptor (descriptor object)
546 import datetime
547 check(datetime.timedelta.days, size(h + '2PP'))
548 # getset_descriptor (descriptor object)
549 import __builtin__
550 check(__builtin__.file.closed, size(h + '2PP'))
551 # wrapper_descriptor (descriptor object)
552 check(int.__add__, size(h + '2P2P'))
553 # dictproxy
554 class C(object): pass
555 check(C.__dict__, size(h + 'P'))
556 # method-wrapper (descriptor object)
557 check({}.__iter__, size(h + '2P'))
558 # dict
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000559 check({}, size(h + '3P2P' + 8*'P2P'))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000560 x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000561 check(x, size(h + '3P2P' + 8*'P2P') + 16*size('P2P'))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000562 # dictionary-keyiterator
563 check({}.iterkeys(), size(h + 'P2PPP'))
564 # dictionary-valueiterator
565 check({}.itervalues(), size(h + 'P2PPP'))
566 # dictionary-itemiterator
567 check({}.iteritems(), size(h + 'P2PPP'))
568 # ellipses
569 check(Ellipsis, size(h + ''))
570 # EncodingMap
571 import codecs, encodings.iso8859_3
572 x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
573 check(x, size(h + '32B2iB'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000574 # enumerate
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000575 check(enumerate([]), size(h + 'l3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000576 # file
Antoine Pitrou24837282010-02-05 17:11:32 +0000577 check(self.file, size(h + '4P2i4P3i3P3i'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000578 # float
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000579 check(float(0), size(h + 'd'))
580 # sys.floatinfo
581 check(sys.float_info, size(vh) + self.P * len(sys.float_info))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000582 # frame
583 import inspect
584 CO_MAXBLOCKS = 20
585 x = inspect.currentframe()
586 ncells = len(x.f_code.co_cellvars)
587 nfrees = len(x.f_code.co_freevars)
588 extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
589 ncells + nfrees - 1
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000590 check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000591 # function
592 def func(): pass
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000593 check(func, size(h + '9P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000594 class c():
595 @staticmethod
596 def foo():
597 pass
598 @classmethod
599 def bar(cls):
600 pass
601 # staticmethod
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000602 check(foo, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000603 # classmethod
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000604 check(bar, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000605 # generator
606 def get_gen(): yield 1
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000607 check(get_gen(), size(h + 'Pi2P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000608 # integer
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000609 check(1, size(h + 'l'))
610 check(100, size(h + 'l'))
611 # iterator
612 check(iter('abc'), size(h + 'lP'))
613 # callable-iterator
614 import re
615 check(re.finditer('',''), size(h + '2P'))
616 # list
617 samples = [[], [1,2,3], ['1', '2', '3']]
618 for sample in samples:
619 check(sample, size(vh + 'PP') + len(sample)*self.P)
620 # sortwrapper (list)
621 # XXX
622 # cmpwrapper (list)
623 # XXX
624 # listiterator (list)
625 check(iter([]), size(h + 'lP'))
626 # listreverseiterator (list)
627 check(reversed([]), size(h + 'lP'))
628 # long
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000629 check(0L, size(vh + 'H') - self.H)
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000630 check(1L, size(vh + 'H'))
631 check(-1L, size(vh + 'H'))
632 check(32768L, size(vh + 'H') + self.H)
633 check(32768L*32768L-1, size(vh + 'H') + self.H)
634 check(32768L*32768L, size(vh + 'H') + 2*self.H)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000635 # module
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000636 check(unittest, size(h + 'P'))
637 # None
638 check(None, size(h + ''))
639 # object
640 check(object(), size(h + ''))
641 # property (descriptor object)
642 class C(object):
643 def getx(self): return self.__x
644 def setx(self, value): self.__x = value
645 def delx(self): del self.__x
646 x = property(getx, setx, delx, "")
647 check(x, size(h + '4Pi'))
648 # PyCObject
649 # XXX
650 # rangeiterator
651 check(iter(xrange(1)), size(h + '4l'))
652 # reverse
653 check(reversed(''), size(h + 'PP'))
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000654 # set
655 # frozenset
656 PySet_MINSIZE = 8
657 samples = [[], range(10), range(50)]
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000658 s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP')
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000659 for sample in samples:
660 minused = len(sample)
661 if minused == 0: tmp = 1
662 # the computation of minused is actually a bit more complicated
663 # but this suffices for the sizeof test
664 minused = minused*2
665 newsize = PySet_MINSIZE
666 while newsize <= minused:
667 newsize = newsize << 1
668 if newsize <= 8:
669 check(set(sample), s)
670 check(frozenset(sample), s)
671 else:
672 check(set(sample), s + newsize*struct.calcsize('lP'))
673 check(frozenset(sample), s + newsize*struct.calcsize('lP'))
674 # setiterator
675 check(iter(set()), size(h + 'P3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000676 # slice
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000677 check(slice(1), size(h + '3P'))
678 # str
679 check('', size(vh + 'lic'))
680 check('abc', size(vh + 'lic') + 3*self.c)
681 # super
682 check(super(int), size(h + '3P'))
683 # tuple
684 check((), size(vh))
685 check((1,2,3), size(vh) + 3*self.P)
686 # tupleiterator
687 check(iter(()), size(h + 'lP'))
688 # type
689 # (PyTypeObject + PyNumberMethods + PyMappingMethods +
690 # PySequenceMethods + PyBufferProcs)
Robert Schuppenies2ee623b2008-07-14 08:42:18 +0000691 s = size(vh + 'P2P15Pl4PP9PP11PI') + size('41P 10P 3P 6P')
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000692 class newstyleclass(object):
693 pass
694 check(newstyleclass, s)
695 # builtin type
696 check(int, s)
697 # NotImplementedType
698 import types
699 check(types.NotImplementedType, s)
Robert Schuppenies901c9972008-06-10 10:10:31 +0000700 # unicode
Robert Schuppenies59f3ade2008-06-17 08:42:15 +0000701 usize = len(u'\0'.encode('unicode-internal'))
Robert Schuppenies901c9972008-06-10 10:10:31 +0000702 samples = [u'', u'1'*100]
703 # we need to test for both sizes, because we don't know if the string
704 # has been cached
705 for s in samples:
Robert Schuppenies9be2ec12008-07-10 15:24:04 +0000706 check(s, size(h + 'PPlP') + usize * (len(s) + 1))
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000707 # weakref
708 import weakref
709 check(weakref.ref(int), size(h + '2Pl2P'))
710 # weakproxy
711 # XXX
712 # weakcallableproxy
713 check(weakref.proxy(int), size(h + '2Pl2P'))
714 # xrange
715 check(xrange(1), size(h + '3l'))
716 check(xrange(66000), size(h + '3l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000717
Robert Schuppeniesd2cd86d2008-07-10 13:43:26 +0000718 def test_pythontypes(self):
719 # check all types defined in Python/
720 h = self.header
721 vh = self.vheader
722 size = self.calcsize
723 check = self.check_sizeof
724 # _ast.AST
725 import _ast
726 check(_ast.AST(), size(h + ''))
727 # imp.NullImporter
728 import imp
729 check(imp.NullImporter(self.file.name), size(h + ''))
730 try:
731 raise TypeError
732 except TypeError:
733 tb = sys.exc_info()[2]
734 # traceback
735 if tb != None:
736 check(tb, size(h + '2P2i'))
737 # symtable entry
738 # XXX
739 # sys.flags
740 check(sys.flags, size(vh) + self.P * len(sys.flags))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000741
742
Walter Dörwaldc3502462003-02-03 23:03:49 +0000743def test_main():
Robert Schuppenies51df0642008-06-01 16:16:17 +0000744 test_classes = (SysModuleTest, SizeofTest)
745
746 test.test_support.run_unittest(*test_classes)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000747
748if __name__ == "__main__":
749 test_main()