PageRenderTime 49ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_sys.py

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