blob: d87bb4883593ae2a48817f9283479014d101d54e [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
370 def test_compact_freelists(self):
371 sys._compact_freelists()
372 r = sys._compact_freelists()
Raymond Hettinger8c6c12c2008-02-09 10:06:20 +0000373## # freed blocks shouldn't change
374## self.assertEqual(r[0][2], 0)
375## self.assertEqual(r[1][2], 0)
376## # fill freelists
377## ints = list(range(10000))
378## floats = [float(i) for i in ints]
379## del ints
380## del floats
381## # should free more than 200 blocks each
382## r = sys._compact_freelists()
383## self.assert_(r[0][1] > 100, r[0][1])
384## self.assert_(r[1][2] > 100, r[1][1])
385##
386## self.assert_(r[0][2] > 100, r[0][2])
387## self.assert_(r[1][2] > 100, r[1][2])
Christian Heimesf31b69f2008-01-14 03:42:48 +0000388
Martin v. Löwis99815892008-06-01 07:20:46 +0000389 def test_ioencoding(self):
390 import subprocess,os
391 env = dict(os.environ)
392
393 # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
394 # not representable in ASCII.
395
396 env["PYTHONIOENCODING"] = "cp424"
397 p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
398 stdout = subprocess.PIPE, env=env)
399 out = p.stdout.read().strip()
400 self.assertEqual(out, unichr(0xa2).encode("cp424"))
401
402 env["PYTHONIOENCODING"] = "ascii:replace"
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, '?')
407
408
Robert Schuppenies51df0642008-06-01 16:16:17 +0000409class SizeofTest(unittest.TestCase):
410
411 def setUp(self):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000412 self.c = len(struct.pack('c', ' '))
413 self.H = len(struct.pack('H', 0))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000414 self.i = len(struct.pack('i', 0))
415 self.l = len(struct.pack('l', 0))
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000416 self.P = len(struct.pack('P', 0))
417 # due to missing size_t information from struct, it is assumed that
418 # sizeof(Py_ssize_t) = sizeof(void*)
Robert Schuppenies161b9212008-06-26 15:20:35 +0000419 self.header = 'PP'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000420 if hasattr(sys, "gettotalrefcount"):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000421 self.header += '2P'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000422 self.file = open(test.test_support.TESTFN, 'wb')
423
424 def tearDown(self):
425 self.file.close()
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000426 test.test_support.unlink(test.test_support.TESTFN)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000427
Robert Schuppenies901c9972008-06-10 10:10:31 +0000428 def check_sizeof(self, o, size, size2=None):
429 """Check size of o. Possible are size and optionally size2)."""
Robert Schuppenies51df0642008-06-01 16:16:17 +0000430 result = sys.getsizeof(o)
Robert Schuppenies901c9972008-06-10 10:10:31 +0000431 msg = 'wrong size for %s: got %d, expected ' % (type(o), result)
432 if (size2 != None) and (result != size):
433 self.assertEqual(result, size2, msg + str(size2))
434 else:
435 self.assertEqual(result, size, msg + str(size))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000436
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000437 def calcsize(self, fmt):
438 """Wrapper around struct.calcsize which enforces the alignment of the
439 end of a structure to the alignment requirement of pointer.
Robert Schuppenies51df0642008-06-01 16:16:17 +0000440
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000441 Note: This wrapper should only be used if a pointer member is included
442 and no member with a size larger than a pointer exists.
443 """
444 return struct.calcsize(fmt + '0P')
Robert Schuppenies51df0642008-06-01 16:16:17 +0000445
446 def test_standardtypes(self):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000447 h = self.header
448 size = self.calcsize
Robert Schuppenies51df0642008-06-01 16:16:17 +0000449 # bool
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000450 self.check_sizeof(True, size(h + 'l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000451 # buffer
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000452 self.check_sizeof(buffer(''), size(h + '2P2Pil'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000453 # cell
454 def get_cell():
455 x = 42
456 def inner():
457 return x
458 return inner
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000459 self.check_sizeof(get_cell().func_closure[0], size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000460 # old-style class
461 class class_oldstyle():
462 def method():
463 pass
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000464 self.check_sizeof(class_oldstyle, size(h + '6P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000465 # instance
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000466 self.check_sizeof(class_oldstyle(), size(h + '3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000467 # method
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000468 self.check_sizeof(class_oldstyle().method, size(h + '4P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000469 # code
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000470 self.check_sizeof(get_cell().func_code, size(h + '4i8Pi2P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000471 # complex
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000472 self.check_sizeof(complex(0,1), size(h + '2d'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000473 # enumerate
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000474 self.check_sizeof(enumerate([]), size(h + 'l3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000475 # reverse
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000476 self.check_sizeof(reversed(''), size(h + 'PP'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000477 # file
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000478 self.check_sizeof(self.file, size(h + '4P2i4P3i3Pi'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000479 # float
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000480 self.check_sizeof(float(0), size(h + 'd'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000481 # function
482 def func(): pass
Robert Schuppenies161b9212008-06-26 15:20:35 +0000483 self.check_sizeof(func, size(h + '9P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000484 class c():
485 @staticmethod
486 def foo():
487 pass
488 @classmethod
489 def bar(cls):
490 pass
491 # staticmethod
Robert Schuppenies161b9212008-06-26 15:20:35 +0000492 self.check_sizeof(foo, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000493 # classmethod
Robert Schuppenies161b9212008-06-26 15:20:35 +0000494 self.check_sizeof(bar, size(h + 'P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000495 # generator
496 def get_gen(): yield 1
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000497 self.check_sizeof(get_gen(), size(h + 'Pi2P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000498 # integer
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000499 self.check_sizeof(1, size(h + 'l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000500 # builtin_function_or_method
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000501 self.check_sizeof(abs, size(h + '3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000502 # module
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000503 self.check_sizeof(unittest, size(h + 'P'))
Georg Brandl7a6de8b2008-06-01 16:42:16 +0000504 # xrange
Robert Schuppenies161b9212008-06-26 15:20:35 +0000505 self.check_sizeof(xrange(1), size(h + '3l'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000506 # slice
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000507 self.check_sizeof(slice(0), size(h + '3P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000508
Robert Schuppenies161b9212008-06-26 15:20:35 +0000509 h += 'P'
Robert Schuppenies51df0642008-06-01 16:16:17 +0000510 # new-style class
511 class class_newstyle(object):
512 def method():
513 pass
514 # type (PyTypeObject + PyNumberMethods + PyMappingMethods +
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000515 # PySequenceMethods + PyBufferProcs)
516 self.check_sizeof(class_newstyle, size('P2P15Pl4PP9PP11PI') +\
517 size(h + '41P 10P 3P 6P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000518
519 def test_specialtypes(self):
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000520 h = self.header
521 size = self.calcsize
Robert Schuppenies51df0642008-06-01 16:16:17 +0000522 # dict
Robert Schuppenies161b9212008-06-26 15:20:35 +0000523 self.check_sizeof({}, size(h + '3P2P') + 8*size('P2P'))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000524 longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
Robert Schuppenies161b9212008-06-26 15:20:35 +0000525 self.check_sizeof(longdict, size(h + '3P2P') + (8+16)*size('P2P'))
Robert Schuppenies901c9972008-06-10 10:10:31 +0000526 # unicode
Robert Schuppenies59f3ade2008-06-17 08:42:15 +0000527 usize = len(u'\0'.encode('unicode-internal'))
Robert Schuppenies901c9972008-06-10 10:10:31 +0000528 samples = [u'', u'1'*100]
529 # we need to test for both sizes, because we don't know if the string
530 # has been cached
531 for s in samples:
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000532 basicsize = size(h + 'PPlP') + usize * (len(s) + 1)
Robert Schuppenies901c9972008-06-10 10:10:31 +0000533 self.check_sizeof(s, basicsize,\
534 size2=basicsize + sys.getsizeof(str(s)))
535 # XXX trigger caching encoded version as Python string
536 s = samples[1]
537 try:
538 getattr(sys, s)
539 except AttributeError:
540 pass
541 finally:
542 self.check_sizeof(s, basicsize + sys.getsizeof(str(s)))
Robert Schuppenies51df0642008-06-01 16:16:17 +0000543
Robert Schuppenies161b9212008-06-26 15:20:35 +0000544 h += 'P'
545 # list
546 self.check_sizeof([], size(h + 'PP'))
547 self.check_sizeof([1, 2, 3], size(h + 'PP') + 3*self.P)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000548 # long
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000549 self.check_sizeof(0L, size(h + 'H'))
550 self.check_sizeof(1L, size(h + 'H'))
551 self.check_sizeof(-1L, size(h + 'H'))
552 self.check_sizeof(32768L, size(h + 'H') + self.H)
553 self.check_sizeof(32768L*32768L-1, size(h + 'H') + self.H)
554 self.check_sizeof(32768L*32768L, size(h + 'H') + 2*self.H)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000555 # string
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000556 self.check_sizeof('', size(h + 'lic'))
557 self.check_sizeof('abc', size(h + 'lic') + 3*self.c)
Robert Schuppenies73e9ffc2008-06-13 13:29:37 +0000558 # tuple
Robert Schuppenies41a7ce02008-06-25 09:20:03 +0000559 self.check_sizeof((), size(h))
560 self.check_sizeof((1,2,3), size(h) + 3*self.P)
Robert Schuppenies51df0642008-06-01 16:16:17 +0000561
562
Walter Dörwaldc3502462003-02-03 23:03:49 +0000563def test_main():
Robert Schuppenies51df0642008-06-01 16:16:17 +0000564 test_classes = (SysModuleTest, SizeofTest)
565
566 test.test_support.run_unittest(*test_classes)
Walter Dörwaldc3502462003-02-03 23:03:49 +0000567
568if __name__ == "__main__":
569 test_main()