Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 1 | # -*- coding: iso-8859-1 -*- |
| 2 | import unittest, test.test_support |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 3 | import sys, cStringIO, os |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 4 | import struct |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 5 | |
| 6 | class 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örwald | e7028ac | 2003-02-03 23:05:27 +0000 | [diff] [blame] | 64 | # FIXME: testing the code for a lost or replaced excepthook in |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 65 | # Python/pythonrun.c::PyErr_PrintEx() is tricky. |
| 66 | |
Guido van Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 67 | 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 Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 73 | 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 Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 77 | |
Guido van Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 78 | sys.exc_clear() |
Guido van Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 79 | |
Guido van Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 80 | 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 Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 84 | |
| 85 | def clear(): |
Guido van Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 86 | try: |
| 87 | raise ValueError, 42 |
| 88 | except ValueError, exc: |
| 89 | clear_check(exc) |
Guido van Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 90 | |
| 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 Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 97 | raise ValueError, 13 |
Guido van Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 98 | except ValueError, exc: |
Guido van Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 99 | typ1, value1, traceback1 = sys.exc_info() |
| 100 | clear() |
| 101 | typ2, value2, traceback2 = sys.exc_info() |
Guido van Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 102 | |
Guido van Rossum | d6473d1 | 2003-03-01 03:25:41 +0000 | [diff] [blame] | 103 | 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 Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 107 | |
| 108 | # Check that an exception can be cleared outside of an except block |
| 109 | clear_check(exc) |
| 110 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 111 | 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. Hudson | f058858 | 2005-02-15 15:26:11 +0000 | [diff] [blame] | 165 | # 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 Peters | f0db38d | 2005-02-15 21:50:12 +0000 | [diff] [blame] | 175 | |
| 176 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 177 | 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 Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 187 | self.assertRaises(TypeError, sys.setcheckinterval) |
Tim Peters | e5e065b | 2003-07-06 18:36:54 +0000 | [diff] [blame] | 188 | 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 192 | |
| 193 | def test_recursionlimit(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 194 | 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 201 | |
| 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 Norwitz | eb2a5ef | 2003-02-18 15:22:10 +0000 | [diff] [blame] | 235 | self.assertRaises(ValueError, sys._getframe, 2000000000) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 236 | self.assert_( |
| 237 | SysModuleTest.test_getframe.im_func.func_code \ |
| 238 | is sys._getframe().f_code |
| 239 | ) |
| 240 | |
Tim Peters | 32a8361 | 2006-07-10 21:08:24 +0000 | [diff] [blame] | 241 | # sys._current_frames() is a CPython-only gimmick. |
| 242 | def test_current_frames(self): |
Tim Peters | 112aad3 | 2006-07-19 00:03:19 +0000 | [diff] [blame] | 243 | 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 Peters | 32a8361 | 2006-07-10 21:08:24 +0000 | [diff] [blame] | 256 | 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 Peters | 0c4a3b3 | 2006-07-25 04:07:22 +0000 | [diff] [blame] | 278 | # 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 Peters | 32a8361 | 2006-07-10 21:08:24 +0000 | [diff] [blame] | 281 | 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 Peters | 0c4a3b3 | 2006-07-25 04:07:22 +0000 | [diff] [blame] | 310 | self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"]) |
Tim Peters | 32a8361 | 2006-07-10 21:08:24 +0000 | [diff] [blame] | 311 | |
| 312 | # Reap the spawned thread. |
| 313 | leave_g.set() |
| 314 | t.join() |
| 315 | |
Tim Peters | 112aad3 | 2006-07-19 00:03:19 +0000 | [diff] [blame] | 316 | # 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örwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 325 | 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 Heimes | dfdfaab | 2007-12-01 11:20:10 +0000 | [diff] [blame] | 333 | self.assertEqual(len(sys.float_info), 11) |
Christian Heimes | c94e2b5 | 2008-01-14 04:13:37 +0000 | [diff] [blame] | 334 | self.assertEqual(sys.float_info.radix, 2) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 335 | self.assert_(isinstance(sys.hexversion, int)) |
| 336 | self.assert_(isinstance(sys.maxint, int)) |
Walter Dörwald | 4e41a4b | 2005-08-03 17:09:04 +0000 | [diff] [blame] | 337 | if test.test_support.have_unicode: |
| 338 | self.assert_(isinstance(sys.maxunicode, int)) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 339 | 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öwis | a8cd7a2 | 2006-04-03 11:05:39 +0000 | [diff] [blame] | 351 | 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 Heimes | f31b69f | 2008-01-14 03:42:48 +0000 | [diff] [blame] | 356 | 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. Kuchling | 7ce9b18 | 2008-01-15 01:29:16 +0000 | [diff] [blame] | 360 | "no_site", "ignore_environment", "tabcheck", "verbose", |
Brett Cannon | be1501b | 2008-05-08 20:23:06 +0000 | [diff] [blame] | 361 | "unicode", "bytes_warning") |
Christian Heimes | f31b69f | 2008-01-14 03:42:48 +0000 | [diff] [blame] | 362 | 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 Heimes | 422051a | 2008-02-04 18:00:12 +0000 | [diff] [blame] | 367 | def test_clear_type_cache(self): |
| 368 | sys._clear_type_cache() |
| 369 | |
Martin v. Löwis | 9981589 | 2008-06-01 07:20:46 +0000 | [diff] [blame] | 370 | 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 Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 390 | class SizeofTest(unittest.TestCase): |
| 391 | |
Robert Schuppenies | 4762902 | 2008-07-10 17:13:55 +0000 | [diff] [blame] | 392 | TPFLAGS_HAVE_GC = 1<<14 |
| 393 | TPFLAGS_HEAPTYPE = 1L<<9 |
| 394 | |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 395 | def setUp(self): |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 396 | self.c = len(struct.pack('c', ' ')) |
| 397 | self.H = len(struct.pack('H', 0)) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 398 | self.i = len(struct.pack('i', 0)) |
| 399 | self.l = len(struct.pack('l', 0)) |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 400 | self.P = len(struct.pack('P', 0)) |
| 401 | # due to missing size_t information from struct, it is assumed that |
| 402 | # sizeof(Py_ssize_t) = sizeof(void*) |
Robert Schuppenies | 161b921 | 2008-06-26 15:20:35 +0000 | [diff] [blame] | 403 | self.header = 'PP' |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 404 | self.vheader = self.header + 'P' |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 405 | if hasattr(sys, "gettotalrefcount"): |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 406 | self.header += '2P' |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 407 | self.vheader += '2P' |
Robert Schuppenies | 4762902 | 2008-07-10 17:13:55 +0000 | [diff] [blame] | 408 | import _testcapi |
| 409 | self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 410 | self.file = open(test.test_support.TESTFN, 'wb') |
| 411 | |
| 412 | def tearDown(self): |
| 413 | self.file.close() |
Georg Brandl | 7a6de8b | 2008-06-01 16:42:16 +0000 | [diff] [blame] | 414 | test.test_support.unlink(test.test_support.TESTFN) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 415 | |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 416 | def check_sizeof(self, o, size): |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 417 | result = sys.getsizeof(o) |
Robert Schuppenies | 4762902 | 2008-07-10 17:13:55 +0000 | [diff] [blame] | 418 | if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\ |
| 419 | ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))): |
| 420 | size += self.gc_headsize |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 421 | msg = 'wrong size for %s: got %d, expected %d' \ |
| 422 | % (type(o), result, size) |
| 423 | self.assertEqual(result, size, msg) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 424 | |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 425 | def calcsize(self, fmt): |
| 426 | """Wrapper around struct.calcsize which enforces the alignment of the |
| 427 | end of a structure to the alignment requirement of pointer. |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 428 | |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 429 | Note: This wrapper should only be used if a pointer member is included |
| 430 | and no member with a size larger than a pointer exists. |
| 431 | """ |
| 432 | return struct.calcsize(fmt + '0P') |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 433 | |
Robert Schuppenies | 4762902 | 2008-07-10 17:13:55 +0000 | [diff] [blame] | 434 | def test_gc_head_size(self): |
| 435 | # Check that the gc header size is added to objects tracked by the gc. |
| 436 | h = self.header |
| 437 | size = self.calcsize |
| 438 | gc_header_size = self.gc_headsize |
| 439 | # bool objects are not gc tracked |
| 440 | self.assertEqual(sys.getsizeof(True), size(h + 'l')) |
| 441 | # but lists are |
| 442 | self.assertEqual(sys.getsizeof([]), size(h + 'P PP') + gc_header_size) |
| 443 | |
| 444 | def test_default(self): |
| 445 | h = self.header |
| 446 | size = self.calcsize |
| 447 | self.assertEqual(sys.getsizeof(True, -1), size(h + 'l')) |
| 448 | |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 449 | def test_objecttypes(self): |
| 450 | # check all types defined in Objects/ |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 451 | h = self.header |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 452 | vh = self.vheader |
Robert Schuppenies | 41a7ce0 | 2008-06-25 09:20:03 +0000 | [diff] [blame] | 453 | size = self.calcsize |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 454 | check = self.check_sizeof |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 455 | # bool |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 456 | check(True, size(h + 'l')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 457 | # buffer |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 458 | check(buffer(''), size(h + '2P2Pil')) |
| 459 | # builtin_function_or_method |
| 460 | check(len, size(h + '3P')) |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 461 | # bytearray |
| 462 | samples = ['', 'u'*100000] |
| 463 | for sample in samples: |
| 464 | x = bytearray(sample) |
| 465 | check(x, size(vh + 'iPP') + x.__alloc__() * self.c) |
| 466 | # bytearray_iterator |
| 467 | check(iter(bytearray()), size(h + 'PP')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 468 | # cell |
| 469 | def get_cell(): |
| 470 | x = 42 |
| 471 | def inner(): |
| 472 | return x |
| 473 | return inner |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 474 | check(get_cell().func_closure[0], size(h + 'P')) |
| 475 | # classobj (old-style class) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 476 | class class_oldstyle(): |
| 477 | def method(): |
| 478 | pass |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 479 | check(class_oldstyle, size(h + '6P')) |
| 480 | # instance (old-style class) |
| 481 | check(class_oldstyle(), size(h + '3P')) |
| 482 | # instancemethod (old-style class) |
| 483 | check(class_oldstyle().method, size(h + '4P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 484 | # complex |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 485 | check(complex(0,1), size(h + '2d')) |
| 486 | # code |
| 487 | check(get_cell().func_code, size(h + '4i8Pi2P')) |
| 488 | # BaseException |
| 489 | check(BaseException(), size(h + '3P')) |
| 490 | # UnicodeEncodeError |
| 491 | check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP')) |
| 492 | # UnicodeDecodeError |
| 493 | check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP')) |
| 494 | # UnicodeTranslateError |
| 495 | check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP')) |
| 496 | # method_descriptor (descriptor object) |
| 497 | check(str.lower, size(h + '2PP')) |
| 498 | # classmethod_descriptor (descriptor object) |
| 499 | # XXX |
| 500 | # member_descriptor (descriptor object) |
| 501 | import datetime |
| 502 | check(datetime.timedelta.days, size(h + '2PP')) |
| 503 | # getset_descriptor (descriptor object) |
| 504 | import __builtin__ |
| 505 | check(__builtin__.file.closed, size(h + '2PP')) |
| 506 | # wrapper_descriptor (descriptor object) |
| 507 | check(int.__add__, size(h + '2P2P')) |
| 508 | # dictproxy |
| 509 | class C(object): pass |
| 510 | check(C.__dict__, size(h + 'P')) |
| 511 | # method-wrapper (descriptor object) |
| 512 | check({}.__iter__, size(h + '2P')) |
| 513 | # dict |
Robert Schuppenies | 2ee623b | 2008-07-14 08:42:18 +0000 | [diff] [blame^] | 514 | check({}, size(h + '3P2P' + 8*'P2P')) |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 515 | x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} |
Robert Schuppenies | 2ee623b | 2008-07-14 08:42:18 +0000 | [diff] [blame^] | 516 | check(x, size(h + '3P2P' + 8*'P2P') + 16*size('P2P')) |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 517 | # dictionary-keyiterator |
| 518 | check({}.iterkeys(), size(h + 'P2PPP')) |
| 519 | # dictionary-valueiterator |
| 520 | check({}.itervalues(), size(h + 'P2PPP')) |
| 521 | # dictionary-itemiterator |
| 522 | check({}.iteritems(), size(h + 'P2PPP')) |
| 523 | # ellipses |
| 524 | check(Ellipsis, size(h + '')) |
| 525 | # EncodingMap |
| 526 | import codecs, encodings.iso8859_3 |
| 527 | x = codecs.charmap_build(encodings.iso8859_3.decoding_table) |
| 528 | check(x, size(h + '32B2iB')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 529 | # enumerate |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 530 | check(enumerate([]), size(h + 'l3P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 531 | # file |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 532 | check(self.file, size(h + '4P2i4P3i3Pi')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 533 | # float |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 534 | check(float(0), size(h + 'd')) |
| 535 | # sys.floatinfo |
| 536 | check(sys.float_info, size(vh) + self.P * len(sys.float_info)) |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 537 | # frame |
| 538 | import inspect |
| 539 | CO_MAXBLOCKS = 20 |
| 540 | x = inspect.currentframe() |
| 541 | ncells = len(x.f_code.co_cellvars) |
| 542 | nfrees = len(x.f_code.co_freevars) |
| 543 | extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ |
| 544 | ncells + nfrees - 1 |
Robert Schuppenies | 2ee623b | 2008-07-14 08:42:18 +0000 | [diff] [blame^] | 545 | check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 546 | # function |
| 547 | def func(): pass |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 548 | check(func, size(h + '9P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 549 | class c(): |
| 550 | @staticmethod |
| 551 | def foo(): |
| 552 | pass |
| 553 | @classmethod |
| 554 | def bar(cls): |
| 555 | pass |
| 556 | # staticmethod |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 557 | check(foo, size(h + 'P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 558 | # classmethod |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 559 | check(bar, size(h + 'P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 560 | # generator |
| 561 | def get_gen(): yield 1 |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 562 | check(get_gen(), size(h + 'Pi2P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 563 | # integer |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 564 | check(1, size(h + 'l')) |
| 565 | check(100, size(h + 'l')) |
| 566 | # iterator |
| 567 | check(iter('abc'), size(h + 'lP')) |
| 568 | # callable-iterator |
| 569 | import re |
| 570 | check(re.finditer('',''), size(h + '2P')) |
| 571 | # list |
| 572 | samples = [[], [1,2,3], ['1', '2', '3']] |
| 573 | for sample in samples: |
| 574 | check(sample, size(vh + 'PP') + len(sample)*self.P) |
| 575 | # sortwrapper (list) |
| 576 | # XXX |
| 577 | # cmpwrapper (list) |
| 578 | # XXX |
| 579 | # listiterator (list) |
| 580 | check(iter([]), size(h + 'lP')) |
| 581 | # listreverseiterator (list) |
| 582 | check(reversed([]), size(h + 'lP')) |
| 583 | # long |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 584 | check(0L, size(vh + 'H') - self.H) |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 585 | check(1L, size(vh + 'H')) |
| 586 | check(-1L, size(vh + 'H')) |
| 587 | check(32768L, size(vh + 'H') + self.H) |
| 588 | check(32768L*32768L-1, size(vh + 'H') + self.H) |
| 589 | check(32768L*32768L, size(vh + 'H') + 2*self.H) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 590 | # module |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 591 | check(unittest, size(h + 'P')) |
| 592 | # None |
| 593 | check(None, size(h + '')) |
| 594 | # object |
| 595 | check(object(), size(h + '')) |
| 596 | # property (descriptor object) |
| 597 | class C(object): |
| 598 | def getx(self): return self.__x |
| 599 | def setx(self, value): self.__x = value |
| 600 | def delx(self): del self.__x |
| 601 | x = property(getx, setx, delx, "") |
| 602 | check(x, size(h + '4Pi')) |
| 603 | # PyCObject |
| 604 | # XXX |
| 605 | # rangeiterator |
| 606 | check(iter(xrange(1)), size(h + '4l')) |
| 607 | # reverse |
| 608 | check(reversed(''), size(h + 'PP')) |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 609 | # set |
| 610 | # frozenset |
| 611 | PySet_MINSIZE = 8 |
| 612 | samples = [[], range(10), range(50)] |
Robert Schuppenies | 2ee623b | 2008-07-14 08:42:18 +0000 | [diff] [blame^] | 613 | s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP') |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 614 | for sample in samples: |
| 615 | minused = len(sample) |
| 616 | if minused == 0: tmp = 1 |
| 617 | # the computation of minused is actually a bit more complicated |
| 618 | # but this suffices for the sizeof test |
| 619 | minused = minused*2 |
| 620 | newsize = PySet_MINSIZE |
| 621 | while newsize <= minused: |
| 622 | newsize = newsize << 1 |
| 623 | if newsize <= 8: |
| 624 | check(set(sample), s) |
| 625 | check(frozenset(sample), s) |
| 626 | else: |
| 627 | check(set(sample), s + newsize*struct.calcsize('lP')) |
| 628 | check(frozenset(sample), s + newsize*struct.calcsize('lP')) |
| 629 | # setiterator |
| 630 | check(iter(set()), size(h + 'P3P')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 631 | # slice |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 632 | check(slice(1), size(h + '3P')) |
| 633 | # str |
| 634 | check('', size(vh + 'lic')) |
| 635 | check('abc', size(vh + 'lic') + 3*self.c) |
| 636 | # super |
| 637 | check(super(int), size(h + '3P')) |
| 638 | # tuple |
| 639 | check((), size(vh)) |
| 640 | check((1,2,3), size(vh) + 3*self.P) |
| 641 | # tupleiterator |
| 642 | check(iter(()), size(h + 'lP')) |
| 643 | # type |
| 644 | # (PyTypeObject + PyNumberMethods + PyMappingMethods + |
| 645 | # PySequenceMethods + PyBufferProcs) |
Robert Schuppenies | 2ee623b | 2008-07-14 08:42:18 +0000 | [diff] [blame^] | 646 | s = size(vh + 'P2P15Pl4PP9PP11PI') + size('41P 10P 3P 6P') |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 647 | class newstyleclass(object): |
| 648 | pass |
| 649 | check(newstyleclass, s) |
| 650 | # builtin type |
| 651 | check(int, s) |
| 652 | # NotImplementedType |
| 653 | import types |
| 654 | check(types.NotImplementedType, s) |
Robert Schuppenies | 901c997 | 2008-06-10 10:10:31 +0000 | [diff] [blame] | 655 | # unicode |
Robert Schuppenies | 59f3ade | 2008-06-17 08:42:15 +0000 | [diff] [blame] | 656 | usize = len(u'\0'.encode('unicode-internal')) |
Robert Schuppenies | 901c997 | 2008-06-10 10:10:31 +0000 | [diff] [blame] | 657 | samples = [u'', u'1'*100] |
| 658 | # we need to test for both sizes, because we don't know if the string |
| 659 | # has been cached |
| 660 | for s in samples: |
Robert Schuppenies | 9be2ec1 | 2008-07-10 15:24:04 +0000 | [diff] [blame] | 661 | check(s, size(h + 'PPlP') + usize * (len(s) + 1)) |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 662 | # weakref |
| 663 | import weakref |
| 664 | check(weakref.ref(int), size(h + '2Pl2P')) |
| 665 | # weakproxy |
| 666 | # XXX |
| 667 | # weakcallableproxy |
| 668 | check(weakref.proxy(int), size(h + '2Pl2P')) |
| 669 | # xrange |
| 670 | check(xrange(1), size(h + '3l')) |
| 671 | check(xrange(66000), size(h + '3l')) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 672 | |
Robert Schuppenies | d2cd86d | 2008-07-10 13:43:26 +0000 | [diff] [blame] | 673 | def test_pythontypes(self): |
| 674 | # check all types defined in Python/ |
| 675 | h = self.header |
| 676 | vh = self.vheader |
| 677 | size = self.calcsize |
| 678 | check = self.check_sizeof |
| 679 | # _ast.AST |
| 680 | import _ast |
| 681 | check(_ast.AST(), size(h + '')) |
| 682 | # imp.NullImporter |
| 683 | import imp |
| 684 | check(imp.NullImporter(self.file.name), size(h + '')) |
| 685 | try: |
| 686 | raise TypeError |
| 687 | except TypeError: |
| 688 | tb = sys.exc_info()[2] |
| 689 | # traceback |
| 690 | if tb != None: |
| 691 | check(tb, size(h + '2P2i')) |
| 692 | # symtable entry |
| 693 | # XXX |
| 694 | # sys.flags |
| 695 | check(sys.flags, size(vh) + self.P * len(sys.flags)) |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 696 | |
| 697 | |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 698 | def test_main(): |
Robert Schuppenies | 51df064 | 2008-06-01 16:16:17 +0000 | [diff] [blame] | 699 | test_classes = (SysModuleTest, SizeofTest) |
| 700 | |
| 701 | test.test_support.run_unittest(*test_classes) |
Walter Dörwald | c350246 | 2003-02-03 23:03:49 +0000 | [diff] [blame] | 702 | |
| 703 | if __name__ == "__main__": |
| 704 | test_main() |