PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/test/test_sys.py

https://bitbucket.org/quangquach/pypy
Python | 815 lines | 703 code | 52 blank | 60 comment | 26 complexity | 045ebff27c9a0adbe726360ef6982bb4 MD5 | raw file
  1. # -*- coding: iso-8859-1 -*-
  2. import unittest, test.test_support
  3. import sys, os, cStringIO
  4. import struct
  5. import operator
  6. class SysModuleTest(unittest.TestCase):
  7. def tearDown(self):
  8. test.test_support.reap_children()
  9. def test_original_displayhook(self):
  10. import __builtin__
  11. savestdout = sys.stdout
  12. out = cStringIO.StringIO()
  13. sys.stdout = out
  14. dh = sys.__displayhook__
  15. self.assertRaises(TypeError, dh)
  16. if hasattr(__builtin__, "_"):
  17. del __builtin__._
  18. dh(None)
  19. self.assertEqual(out.getvalue(), "")
  20. self.assertTrue(not hasattr(__builtin__, "_"))
  21. dh(42)
  22. self.assertEqual(out.getvalue(), "42\n")
  23. self.assertEqual(__builtin__._, 42)
  24. del sys.stdout
  25. self.assertRaises(RuntimeError, dh, 42)
  26. sys.stdout = savestdout
  27. def test_lost_displayhook(self):
  28. olddisplayhook = sys.displayhook
  29. del sys.displayhook
  30. code = compile("42", "<string>", "single")
  31. self.assertRaises(RuntimeError, eval, code)
  32. sys.displayhook = olddisplayhook
  33. def test_custom_displayhook(self):
  34. olddisplayhook = sys.displayhook
  35. def baddisplayhook(obj):
  36. raise ValueError
  37. sys.displayhook = baddisplayhook
  38. code = compile("42", "<string>", "single")
  39. self.assertRaises(ValueError, eval, code)
  40. sys.displayhook = olddisplayhook
  41. def test_original_excepthook(self):
  42. savestderr = sys.stderr
  43. err = cStringIO.StringIO()
  44. sys.stderr = err
  45. eh = sys.__excepthook__
  46. self.assertRaises(TypeError, eh)
  47. try:
  48. raise ValueError(42)
  49. except ValueError, exc:
  50. eh(*sys.exc_info())
  51. sys.stderr = savestderr
  52. self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))
  53. # FIXME: testing the code for a lost or replaced excepthook in
  54. # Python/pythonrun.c::PyErr_PrintEx() is tricky.
  55. def test_exc_clear(self):
  56. self.assertRaises(TypeError, sys.exc_clear, 42)
  57. # Verify that exc_info is present and matches exc, then clear it, and
  58. # check that it worked.
  59. def clear_check(exc):
  60. typ, value, traceback = sys.exc_info()
  61. self.assertTrue(typ is not None)
  62. self.assertTrue(value is exc)
  63. self.assertTrue(traceback is not None)
  64. with test.test_support.check_py3k_warnings():
  65. sys.exc_clear()
  66. typ, value, traceback = sys.exc_info()
  67. self.assertTrue(typ is None)
  68. self.assertTrue(value is None)
  69. self.assertTrue(traceback is None)
  70. def clear():
  71. try:
  72. raise ValueError, 42
  73. except ValueError, exc:
  74. clear_check(exc)
  75. # Raise an exception and check that it can be cleared
  76. clear()
  77. # Verify that a frame currently handling an exception is
  78. # unaffected by calling exc_clear in a nested frame.
  79. try:
  80. raise ValueError, 13
  81. except ValueError, exc:
  82. typ1, value1, traceback1 = sys.exc_info()
  83. clear()
  84. typ2, value2, traceback2 = sys.exc_info()
  85. self.assertTrue(typ1 is typ2)
  86. self.assertTrue(value1 is exc)
  87. self.assertTrue(value1 is value2)
  88. self.assertTrue(traceback1 is traceback2)
  89. # Check that an exception can be cleared outside of an except block
  90. clear_check(exc)
  91. def test_exit(self):
  92. self.assertRaises(TypeError, sys.exit, 42, 42)
  93. # call without argument
  94. try:
  95. sys.exit(0)
  96. except SystemExit, exc:
  97. self.assertEqual(exc.code, 0)
  98. except:
  99. self.fail("wrong exception")
  100. else:
  101. self.fail("no exception")
  102. # call with tuple argument with one entry
  103. # entry will be unpacked
  104. try:
  105. sys.exit(42)
  106. except SystemExit, exc:
  107. self.assertEqual(exc.code, 42)
  108. except:
  109. self.fail("wrong exception")
  110. else:
  111. self.fail("no exception")
  112. # call with integer argument
  113. try:
  114. sys.exit((42,))
  115. except SystemExit, exc:
  116. self.assertEqual(exc.code, 42)
  117. except:
  118. self.fail("wrong exception")
  119. else:
  120. self.fail("no exception")
  121. # call with string argument
  122. try:
  123. sys.exit("exit")
  124. except SystemExit, exc:
  125. self.assertEqual(exc.code, "exit")
  126. except:
  127. self.fail("wrong exception")
  128. else:
  129. self.fail("no exception")
  130. # call with tuple argument with two entries
  131. try:
  132. sys.exit((17, 23))
  133. except SystemExit, exc:
  134. self.assertEqual(exc.code, (17, 23))
  135. except:
  136. self.fail("wrong exception")
  137. else:
  138. self.fail("no exception")
  139. # test that the exit machinery handles SystemExits properly
  140. import subprocess
  141. # both unnormalized...
  142. rc = subprocess.call([sys.executable, "-c",
  143. "raise SystemExit, 46"])
  144. self.assertEqual(rc, 46)
  145. # ... and normalized
  146. rc = subprocess.call([sys.executable, "-c",
  147. "raise SystemExit(47)"])
  148. self.assertEqual(rc, 47)
  149. def check_exit_message(code, expected, env=None):
  150. process = subprocess.Popen([sys.executable, "-c", code],
  151. stderr=subprocess.PIPE, env=env)
  152. stdout, stderr = process.communicate()
  153. self.assertEqual(process.returncode, 1)
  154. self.assertTrue(stderr.startswith(expected),
  155. "%s doesn't start with %s" % (repr(stderr), repr(expected)))
  156. # test that stderr buffer if flushed before the exit message is written
  157. # into stderr
  158. check_exit_message(
  159. r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
  160. b"unflushed,message")
  161. # test that the unicode message is encoded to the stderr encoding
  162. env = os.environ.copy()
  163. env['PYTHONIOENCODING'] = 'latin-1'
  164. check_exit_message(
  165. r'import sys; sys.exit(u"h\xe9")',
  166. b"h\xe9", env=env)
  167. def test_getdefaultencoding(self):
  168. if test.test_support.have_unicode:
  169. self.assertRaises(TypeError, sys.getdefaultencoding, 42)
  170. # can't check more than the type, as the user might have changed it
  171. self.assertIsInstance(sys.getdefaultencoding(), str)
  172. # testing sys.settrace() is done in test_sys_settrace.py
  173. # testing sys.setprofile() is done in test_sys_setprofile.py
  174. def test_setcheckinterval(self):
  175. self.assertRaises(TypeError, sys.setcheckinterval)
  176. orig = sys.getcheckinterval()
  177. for n in 0, 100, 120, orig: # orig last to restore starting state
  178. sys.setcheckinterval(n)
  179. self.assertEqual(sys.getcheckinterval(), n)
  180. def test_recursionlimit(self):
  181. self.assertRaises(TypeError, sys.getrecursionlimit, 42)
  182. oldlimit = sys.getrecursionlimit()
  183. self.assertRaises(TypeError, sys.setrecursionlimit)
  184. self.assertRaises(ValueError, sys.setrecursionlimit, -42)
  185. sys.setrecursionlimit(10000)
  186. self.assertEqual(sys.getrecursionlimit(), 10000)
  187. sys.setrecursionlimit(oldlimit)
  188. self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
  189. try:
  190. sys.setrecursionlimit((1 << 31) - 5)
  191. try:
  192. # issue13546: isinstance(e, ValueError) used to fail
  193. # when the recursion limit is close to 1<<31
  194. raise ValueError()
  195. except ValueError, e:
  196. pass
  197. finally:
  198. sys.setrecursionlimit(oldlimit)
  199. def test_getwindowsversion(self):
  200. # Raise SkipTest if sys doesn't have getwindowsversion attribute
  201. test.test_support.get_attribute(sys, "getwindowsversion")
  202. v = sys.getwindowsversion()
  203. self.assertEqual(len(v), 5)
  204. self.assertIsInstance(v[0], int)
  205. self.assertIsInstance(v[1], int)
  206. self.assertIsInstance(v[2], int)
  207. self.assertIsInstance(v[3], int)
  208. self.assertIsInstance(v[4], str)
  209. self.assertRaises(IndexError, operator.getitem, v, 5)
  210. self.assertIsInstance(v.major, int)
  211. self.assertIsInstance(v.minor, int)
  212. self.assertIsInstance(v.build, int)
  213. self.assertIsInstance(v.platform, int)
  214. self.assertIsInstance(v.service_pack, str)
  215. self.assertIsInstance(v.service_pack_minor, int)
  216. self.assertIsInstance(v.service_pack_major, int)
  217. self.assertIsInstance(v.suite_mask, int)
  218. self.assertIsInstance(v.product_type, int)
  219. self.assertEqual(v[0], v.major)
  220. self.assertEqual(v[1], v.minor)
  221. self.assertEqual(v[2], v.build)
  222. self.assertEqual(v[3], v.platform)
  223. self.assertEqual(v[4], v.service_pack)
  224. # This is how platform.py calls it. Make sure tuple
  225. # still has 5 elements
  226. maj, min, buildno, plat, csd = sys.getwindowsversion()
  227. def test_dlopenflags(self):
  228. if hasattr(sys, "setdlopenflags"):
  229. self.assertTrue(hasattr(sys, "getdlopenflags"))
  230. self.assertRaises(TypeError, sys.getdlopenflags, 42)
  231. oldflags = sys.getdlopenflags()
  232. self.assertRaises(TypeError, sys.setdlopenflags)
  233. sys.setdlopenflags(oldflags+1)
  234. self.assertEqual(sys.getdlopenflags(), oldflags+1)
  235. sys.setdlopenflags(oldflags)
  236. @test.test_support.impl_detail("reference counting")
  237. def test_refcount(self):
  238. # n here must be a global in order for this test to pass while
  239. # tracing with a python function. Tracing calls PyFrame_FastToLocals
  240. # which will add a copy of any locals to the frame object, causing
  241. # the reference count to increase by 2 instead of 1.
  242. global n
  243. self.assertRaises(TypeError, sys.getrefcount)
  244. c = sys.getrefcount(None)
  245. n = None
  246. self.assertEqual(sys.getrefcount(None), c+1)
  247. del n
  248. self.assertEqual(sys.getrefcount(None), c)
  249. if hasattr(sys, "gettotalrefcount"):
  250. self.assertIsInstance(sys.gettotalrefcount(), int)
  251. def test_getframe(self):
  252. self.assertRaises(TypeError, sys._getframe, 42, 42)
  253. self.assertRaises(ValueError, sys._getframe, 2000000000)
  254. self.assertTrue(
  255. SysModuleTest.test_getframe.im_func.func_code \
  256. is sys._getframe().f_code
  257. )
  258. @test.test_support.impl_detail("current_frames")
  259. def test_current_frames(self):
  260. have_threads = True
  261. try:
  262. import thread
  263. except ImportError:
  264. have_threads = False
  265. if have_threads:
  266. self.current_frames_with_threads()
  267. else:
  268. self.current_frames_without_threads()
  269. # Test sys._current_frames() in a WITH_THREADS build.
  270. @test.test_support.reap_threads
  271. def current_frames_with_threads(self):
  272. import threading, thread
  273. import traceback
  274. # Spawn a thread that blocks at a known place. Then the main
  275. # thread does sys._current_frames(), and verifies that the frames
  276. # returned make sense.
  277. entered_g = threading.Event()
  278. leave_g = threading.Event()
  279. thread_info = [] # the thread's id
  280. def f123():
  281. g456()
  282. def g456():
  283. thread_info.append(thread.get_ident())
  284. entered_g.set()
  285. leave_g.wait()
  286. t = threading.Thread(target=f123)
  287. t.start()
  288. entered_g.wait()
  289. # At this point, t has finished its entered_g.set(), although it's
  290. # impossible to guess whether it's still on that line or has moved on
  291. # to its leave_g.wait().
  292. self.assertEqual(len(thread_info), 1)
  293. thread_id = thread_info[0]
  294. d = sys._current_frames()
  295. main_id = thread.get_ident()
  296. self.assertIn(main_id, d)
  297. self.assertIn(thread_id, d)
  298. # Verify that the captured main-thread frame is _this_ frame.
  299. frame = d.pop(main_id)
  300. self.assertTrue(frame is sys._getframe())
  301. # Verify that the captured thread frame is blocked in g456, called
  302. # from f123. This is a litte tricky, since various bits of
  303. # threading.py are also in the thread's call stack.
  304. frame = d.pop(thread_id)
  305. stack = traceback.extract_stack(frame)
  306. for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
  307. if funcname == "f123":
  308. break
  309. else:
  310. self.fail("didn't find f123() on thread's call stack")
  311. self.assertEqual(sourceline, "g456()")
  312. # And the next record must be for g456().
  313. filename, lineno, funcname, sourceline = stack[i+1]
  314. self.assertEqual(funcname, "g456")
  315. self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
  316. # Reap the spawned thread.
  317. leave_g.set()
  318. t.join()
  319. # Test sys._current_frames() when thread support doesn't exist.
  320. def current_frames_without_threads(self):
  321. # Not much happens here: there is only one thread, with artificial
  322. # "thread id" 0.
  323. d = sys._current_frames()
  324. self.assertEqual(len(d), 1)
  325. self.assertIn(0, d)
  326. self.assertTrue(d[0] is sys._getframe())
  327. def test_attributes(self):
  328. self.assertIsInstance(sys.api_version, int)
  329. self.assertIsInstance(sys.argv, list)
  330. self.assertIn(sys.byteorder, ("little", "big"))
  331. self.assertIsInstance(sys.builtin_module_names, tuple)
  332. self.assertIsInstance(sys.copyright, basestring)
  333. self.assertIsInstance(sys.exec_prefix, basestring)
  334. self.assertIsInstance(sys.executable, basestring)
  335. self.assertEqual(len(sys.float_info), 11)
  336. self.assertEqual(sys.float_info.radix, 2)
  337. self.assertEqual(len(sys.long_info), 2)
  338. if test.test_support.check_impl_detail(cpython=True):
  339. self.assertTrue(sys.long_info.bits_per_digit % 5 == 0)
  340. else:
  341. self.assertTrue(sys.long_info.bits_per_digit >= 1)
  342. self.assertTrue(sys.long_info.sizeof_digit >= 1)
  343. self.assertEqual(type(sys.long_info.bits_per_digit), int)
  344. self.assertEqual(type(sys.long_info.sizeof_digit), int)
  345. self.assertIsInstance(sys.hexversion, int)
  346. self.assertIsInstance(sys.maxint, int)
  347. if test.test_support.have_unicode:
  348. self.assertIsInstance(sys.maxunicode, int)
  349. self.assertIsInstance(sys.platform, basestring)
  350. self.assertIsInstance(sys.prefix, basestring)
  351. self.assertIsInstance(sys.version, basestring)
  352. vi = sys.version_info
  353. self.assertIsInstance(vi[:], tuple)
  354. self.assertEqual(len(vi), 5)
  355. self.assertIsInstance(vi[0], int)
  356. self.assertIsInstance(vi[1], int)
  357. self.assertIsInstance(vi[2], int)
  358. self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
  359. self.assertIsInstance(vi[4], int)
  360. self.assertIsInstance(vi.major, int)
  361. self.assertIsInstance(vi.minor, int)
  362. self.assertIsInstance(vi.micro, int)
  363. self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
  364. self.assertIsInstance(vi.serial, int)
  365. self.assertEqual(vi[0], vi.major)
  366. self.assertEqual(vi[1], vi.minor)
  367. self.assertEqual(vi[2], vi.micro)
  368. self.assertEqual(vi[3], vi.releaselevel)
  369. self.assertEqual(vi[4], vi.serial)
  370. self.assertTrue(vi > (1,0,0))
  371. self.assertIsInstance(sys.float_repr_style, str)
  372. self.assertIn(sys.float_repr_style, ('short', 'legacy'))
  373. def test_43581(self):
  374. # Can't use sys.stdout, as this is a cStringIO object when
  375. # the test runs under regrtest.
  376. self.assertTrue(sys.__stdout__.encoding == sys.__stderr__.encoding)
  377. def test_sys_flags(self):
  378. self.assertTrue(sys.flags)
  379. attrs = ("debug", "py3k_warning", "division_warning", "division_new",
  380. "inspect", "interactive", "optimize", "dont_write_bytecode",
  381. "no_site", "ignore_environment", "tabcheck", "verbose",
  382. "unicode", "bytes_warning", "hash_randomization")
  383. for attr in attrs:
  384. self.assertTrue(hasattr(sys.flags, attr), attr)
  385. self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
  386. self.assertTrue(repr(sys.flags))
  387. @test.test_support.impl_detail("sys._clear_type_cache")
  388. def test_clear_type_cache(self):
  389. sys._clear_type_cache()
  390. def test_ioencoding(self):
  391. import subprocess
  392. env = dict(os.environ)
  393. # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
  394. # not representable in ASCII.
  395. env["PYTHONIOENCODING"] = "cp424"
  396. p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
  397. stdout = subprocess.PIPE, env=env)
  398. out = p.communicate()[0].strip()
  399. self.assertEqual(out, unichr(0xa2).encode("cp424"))
  400. env["PYTHONIOENCODING"] = "ascii:replace"
  401. p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
  402. stdout = subprocess.PIPE, env=env)
  403. out = p.communicate()[0].strip()
  404. self.assertEqual(out, '?')
  405. def test_call_tracing(self):
  406. self.assertEqual(sys.call_tracing(str, (2,)), "2")
  407. self.assertRaises(TypeError, sys.call_tracing, str, 2)
  408. def test_executable(self):
  409. # sys.executable should be absolute
  410. self.assertEqual(os.path.abspath(sys.executable), sys.executable)
  411. # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
  412. # has been set to an non existent program name and Python is unable to
  413. # retrieve the real program name
  414. import subprocess
  415. # For a normal installation, it should work without 'cwd'
  416. # argument. For test runs in the build directory, see #7774.
  417. python_dir = os.path.dirname(os.path.realpath(sys.executable))
  418. p = subprocess.Popen(
  419. ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
  420. executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
  421. executable = p.communicate()[0].strip()
  422. p.wait()
  423. self.assertIn(executable, ["''", repr(sys.executable)])
  424. @unittest.skipUnless(test.test_support.check_impl_detail(), "sys.getsizeof()")
  425. class SizeofTest(unittest.TestCase):
  426. TPFLAGS_HAVE_GC = 1<<14
  427. TPFLAGS_HEAPTYPE = 1L<<9
  428. def setUp(self):
  429. self.c = len(struct.pack('c', ' '))
  430. self.H = len(struct.pack('H', 0))
  431. self.i = len(struct.pack('i', 0))
  432. self.l = len(struct.pack('l', 0))
  433. self.P = len(struct.pack('P', 0))
  434. # due to missing size_t information from struct, it is assumed that
  435. # sizeof(Py_ssize_t) = sizeof(void*)
  436. self.header = 'PP'
  437. self.vheader = self.header + 'P'
  438. if hasattr(sys, "gettotalrefcount"):
  439. self.header += '2P'
  440. self.vheader += '2P'
  441. self.longdigit = sys.long_info.sizeof_digit
  442. import _testcapi
  443. self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
  444. self.file = open(test.test_support.TESTFN, 'wb')
  445. def tearDown(self):
  446. self.file.close()
  447. test.test_support.unlink(test.test_support.TESTFN)
  448. def check_sizeof(self, o, size):
  449. result = sys.getsizeof(o)
  450. if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
  451. ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
  452. size += self.gc_headsize
  453. msg = 'wrong size for %s: got %d, expected %d' \
  454. % (type(o), result, size)
  455. self.assertEqual(result, size, msg)
  456. def calcsize(self, fmt):
  457. """Wrapper around struct.calcsize which enforces the alignment of the
  458. end of a structure to the alignment requirement of pointer.
  459. Note: This wrapper should only be used if a pointer member is included
  460. and no member with a size larger than a pointer exists.
  461. """
  462. return struct.calcsize(fmt + '0P')
  463. def test_gc_head_size(self):
  464. # Check that the gc header size is added to objects tracked by the gc.
  465. h = self.header
  466. size = self.calcsize
  467. gc_header_size = self.gc_headsize
  468. # bool objects are not gc tracked
  469. self.assertEqual(sys.getsizeof(True), size(h + 'l'))
  470. # but lists are
  471. self.assertEqual(sys.getsizeof([]), size(h + 'P PP') + gc_header_size)
  472. def test_default(self):
  473. h = self.header
  474. size = self.calcsize
  475. self.assertEqual(sys.getsizeof(True, -1), size(h + 'l'))
  476. def test_objecttypes(self):
  477. # check all types defined in Objects/
  478. h = self.header
  479. vh = self.vheader
  480. size = self.calcsize
  481. check = self.check_sizeof
  482. # bool
  483. check(True, size(h + 'l'))
  484. # buffer
  485. with test.test_support.check_py3k_warnings():
  486. check(buffer(''), size(h + '2P2Pil'))
  487. # builtin_function_or_method
  488. check(len, size(h + '3P'))
  489. # bytearray
  490. samples = ['', 'u'*100000]
  491. for sample in samples:
  492. x = bytearray(sample)
  493. check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
  494. # bytearray_iterator
  495. check(iter(bytearray()), size(h + 'PP'))
  496. # cell
  497. def get_cell():
  498. x = 42
  499. def inner():
  500. return x
  501. return inner
  502. check(get_cell().func_closure[0], size(h + 'P'))
  503. # classobj (old-style class)
  504. class class_oldstyle():
  505. def method():
  506. pass
  507. check(class_oldstyle, size(h + '7P'))
  508. # instance (old-style class)
  509. check(class_oldstyle(), size(h + '3P'))
  510. # instancemethod (old-style class)
  511. check(class_oldstyle().method, size(h + '4P'))
  512. # complex
  513. check(complex(0,1), size(h + '2d'))
  514. # code
  515. check(get_cell().func_code, size(h + '4i8Pi3P'))
  516. # BaseException
  517. check(BaseException(), size(h + '3P'))
  518. # UnicodeEncodeError
  519. check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP'))
  520. # UnicodeDecodeError
  521. check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
  522. # UnicodeTranslateError
  523. check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP'))
  524. # method_descriptor (descriptor object)
  525. check(str.lower, size(h + '2PP'))
  526. # classmethod_descriptor (descriptor object)
  527. # XXX
  528. # member_descriptor (descriptor object)
  529. import datetime
  530. check(datetime.timedelta.days, size(h + '2PP'))
  531. # getset_descriptor (descriptor object)
  532. import __builtin__
  533. check(__builtin__.file.closed, size(h + '2PP'))
  534. # wrapper_descriptor (descriptor object)
  535. check(int.__add__, size(h + '2P2P'))
  536. # dictproxy
  537. class C(object): pass
  538. check(C.__dict__, size(h + 'P'))
  539. # method-wrapper (descriptor object)
  540. check({}.__iter__, size(h + '2P'))
  541. # dict
  542. check({}, size(h + '3P2P' + 8*'P2P'))
  543. x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
  544. check(x, size(h + '3P2P' + 8*'P2P') + 16*size('P2P'))
  545. # dictionary-keyiterator
  546. check({}.iterkeys(), size(h + 'P2PPP'))
  547. # dictionary-valueiterator
  548. check({}.itervalues(), size(h + 'P2PPP'))
  549. # dictionary-itemiterator
  550. check({}.iteritems(), size(h + 'P2PPP'))
  551. # ellipses
  552. check(Ellipsis, size(h + ''))
  553. # EncodingMap
  554. import codecs, encodings.iso8859_3
  555. x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
  556. check(x, size(h + '32B2iB'))
  557. # enumerate
  558. check(enumerate([]), size(h + 'l3P'))
  559. # file
  560. check(self.file, size(h + '4P2i4P3i3P3i'))
  561. # float
  562. check(float(0), size(h + 'd'))
  563. # sys.floatinfo
  564. check(sys.float_info, size(vh) + self.P * len(sys.float_info))
  565. # frame
  566. import inspect
  567. CO_MAXBLOCKS = 20
  568. x = inspect.currentframe()
  569. ncells = len(x.f_code.co_cellvars)
  570. nfrees = len(x.f_code.co_freevars)
  571. extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
  572. ncells + nfrees - 1
  573. check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
  574. # function
  575. def func(): pass
  576. check(func, size(h + '9P'))
  577. class c():
  578. @staticmethod
  579. def foo():
  580. pass
  581. @classmethod
  582. def bar(cls):
  583. pass
  584. # staticmethod
  585. check(foo, size(h + 'P'))
  586. # classmethod
  587. check(bar, size(h + 'P'))
  588. # generator
  589. def get_gen(): yield 1
  590. check(get_gen(), size(h + 'Pi2P'))
  591. # integer
  592. check(1, size(h + 'l'))
  593. check(100, size(h + 'l'))
  594. # iterator
  595. check(iter('abc'), size(h + 'lP'))
  596. # callable-iterator
  597. import re
  598. check(re.finditer('',''), size(h + '2P'))
  599. # list
  600. samples = [[], [1,2,3], ['1', '2', '3']]
  601. for sample in samples:
  602. check(sample, size(vh + 'PP') + len(sample)*self.P)
  603. # sortwrapper (list)
  604. # XXX
  605. # cmpwrapper (list)
  606. # XXX
  607. # listiterator (list)
  608. check(iter([]), size(h + 'lP'))
  609. # listreverseiterator (list)
  610. check(reversed([]), size(h + 'lP'))
  611. # long
  612. check(0L, size(vh))
  613. check(1L, size(vh) + self.longdigit)
  614. check(-1L, size(vh) + self.longdigit)
  615. PyLong_BASE = 2**sys.long_info.bits_per_digit
  616. check(long(PyLong_BASE), size(vh) + 2*self.longdigit)
  617. check(long(PyLong_BASE**2-1), size(vh) + 2*self.longdigit)
  618. check(long(PyLong_BASE**2), size(vh) + 3*self.longdigit)
  619. # module
  620. check(unittest, size(h + 'P'))
  621. # None
  622. check(None, size(h + ''))
  623. # object
  624. check(object(), size(h + ''))
  625. # property (descriptor object)
  626. class C(object):
  627. def getx(self): return self.__x
  628. def setx(self, value): self.__x = value
  629. def delx(self): del self.__x
  630. x = property(getx, setx, delx, "")
  631. check(x, size(h + '4Pi'))
  632. # PyCObject
  633. # PyCapsule
  634. # XXX
  635. # rangeiterator
  636. check(iter(xrange(1)), size(h + '4l'))
  637. # reverse
  638. check(reversed(''), size(h + 'PP'))
  639. # set
  640. # frozenset
  641. PySet_MINSIZE = 8
  642. samples = [[], range(10), range(50)]
  643. s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP')
  644. for sample in samples:
  645. minused = len(sample)
  646. if minused == 0: tmp = 1
  647. # the computation of minused is actually a bit more complicated
  648. # but this suffices for the sizeof test
  649. minused = minused*2
  650. newsize = PySet_MINSIZE
  651. while newsize <= minused:
  652. newsize = newsize << 1
  653. if newsize <= 8:
  654. check(set(sample), s)
  655. check(frozenset(sample), s)
  656. else:
  657. check(set(sample), s + newsize*struct.calcsize('lP'))
  658. check(frozenset(sample), s + newsize*struct.calcsize('lP'))
  659. # setiterator
  660. check(iter(set()), size(h + 'P3P'))
  661. # slice
  662. check(slice(1), size(h + '3P'))
  663. # str
  664. check('', struct.calcsize(vh + 'li') + 1)
  665. check('abc', struct.calcsize(vh + 'li') + 1 + 3*self.c)
  666. # super
  667. check(super(int), size(h + '3P'))
  668. # tuple
  669. check((), size(vh))
  670. check((1,2,3), size(vh) + 3*self.P)
  671. # tupleiterator
  672. check(iter(()), size(h + 'lP'))
  673. # type
  674. # (PyTypeObject + PyNumberMethods + PyMappingMethods +
  675. # PySequenceMethods + PyBufferProcs)
  676. s = size(vh + 'P2P15Pl4PP9PP11PI') + size('41P 10P 3P 6P')
  677. class newstyleclass(object):
  678. pass
  679. check(newstyleclass, s)
  680. # builtin type
  681. check(int, s)
  682. # NotImplementedType
  683. import types
  684. check(types.NotImplementedType, s)
  685. # unicode
  686. usize = len(u'\0'.encode('unicode-internal'))
  687. samples = [u'', u'1'*100]
  688. # we need to test for both sizes, because we don't know if the string
  689. # has been cached
  690. for s in samples:
  691. check(s, size(h + 'PPlP') + usize * (len(s) + 1))
  692. # weakref
  693. import weakref
  694. check(weakref.ref(int), size(h + '2Pl2P'))
  695. # weakproxy
  696. # XXX
  697. # weakcallableproxy
  698. check(weakref.proxy(int), size(h + '2Pl2P'))
  699. # xrange
  700. check(xrange(1), size(h + '3l'))
  701. check(xrange(66000), size(h + '3l'))
  702. def test_pythontypes(self):
  703. # check all types defined in Python/
  704. h = self.header
  705. vh = self.vheader
  706. size = self.calcsize
  707. check = self.check_sizeof
  708. # _ast.AST
  709. import _ast
  710. check(_ast.AST(), size(h + ''))
  711. # imp.NullImporter
  712. import imp
  713. check(imp.NullImporter(self.file.name), size(h + ''))
  714. try:
  715. raise TypeError
  716. except TypeError:
  717. tb = sys.exc_info()[2]
  718. # traceback
  719. if tb != None:
  720. check(tb, size(h + '2P2i'))
  721. # symtable entry
  722. # XXX
  723. # sys.flags
  724. check(sys.flags, size(vh) + self.P * len(sys.flags))
  725. def test_main():
  726. test_classes = (SysModuleTest, SizeofTest)
  727. test.test_support.run_unittest(*test_classes)
  728. if __name__ == "__main__":
  729. test_main()