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

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

http://github.com/IronLanguages/main
Python | 794 lines | 686 code | 50 blank | 58 comment | 20 complexity | 598187ef18546783cc4663a6ad1a8dc6 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. 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. def test_getwindowsversion(self):
  189. # Raise SkipTest if sys doesn't have getwindowsversion attribute
  190. test.test_support.get_attribute(sys, "getwindowsversion")
  191. v = sys.getwindowsversion()
  192. self.assertEqual(len(v), 5)
  193. self.assertIsInstance(v[0], int)
  194. self.assertIsInstance(v[1], int)
  195. self.assertIsInstance(v[2], int)
  196. self.assertIsInstance(v[3], int)
  197. self.assertIsInstance(v[4], str)
  198. self.assertRaises(IndexError, operator.getitem, v, 5)
  199. self.assertIsInstance(v.major, int)
  200. self.assertIsInstance(v.minor, int)
  201. self.assertIsInstance(v.build, int)
  202. self.assertIsInstance(v.platform, int)
  203. self.assertIsInstance(v.service_pack, str)
  204. self.assertIsInstance(v.service_pack_minor, int)
  205. self.assertIsInstance(v.service_pack_major, int)
  206. self.assertIsInstance(v.suite_mask, int)
  207. self.assertIsInstance(v.product_type, int)
  208. self.assertEqual(v[0], v.major)
  209. self.assertEqual(v[1], v.minor)
  210. self.assertEqual(v[2], v.build)
  211. self.assertEqual(v[3], v.platform)
  212. self.assertEqual(v[4], v.service_pack)
  213. # This is how platform.py calls it. Make sure tuple
  214. # still has 5 elements
  215. maj, min, buildno, plat, csd = sys.getwindowsversion()
  216. def test_dlopenflags(self):
  217. if hasattr(sys, "setdlopenflags"):
  218. self.assertTrue(hasattr(sys, "getdlopenflags"))
  219. self.assertRaises(TypeError, sys.getdlopenflags, 42)
  220. oldflags = sys.getdlopenflags()
  221. self.assertRaises(TypeError, sys.setdlopenflags)
  222. sys.setdlopenflags(oldflags+1)
  223. self.assertEqual(sys.getdlopenflags(), oldflags+1)
  224. sys.setdlopenflags(oldflags)
  225. def test_refcount(self):
  226. # n here must be a global in order for this test to pass while
  227. # tracing with a python function. Tracing calls PyFrame_FastToLocals
  228. # which will add a copy of any locals to the frame object, causing
  229. # the reference count to increase by 2 instead of 1.
  230. global n
  231. self.assertRaises(TypeError, sys.getrefcount)
  232. c = sys.getrefcount(None)
  233. n = None
  234. self.assertEqual(sys.getrefcount(None), c+1)
  235. del n
  236. self.assertEqual(sys.getrefcount(None), c)
  237. if hasattr(sys, "gettotalrefcount"):
  238. self.assertIsInstance(sys.gettotalrefcount(), int)
  239. def test_getframe(self):
  240. self.assertRaises(TypeError, sys._getframe, 42, 42)
  241. self.assertRaises(ValueError, sys._getframe, 2000000000)
  242. self.assertTrue(
  243. SysModuleTest.test_getframe.im_func.func_code \
  244. is sys._getframe().f_code
  245. )
  246. # sys._current_frames() is a CPython-only gimmick.
  247. def test_current_frames(self):
  248. have_threads = True
  249. try:
  250. import thread
  251. except ImportError:
  252. have_threads = False
  253. if have_threads:
  254. self.current_frames_with_threads()
  255. else:
  256. self.current_frames_without_threads()
  257. # Test sys._current_frames() in a WITH_THREADS build.
  258. @test.test_support.reap_threads
  259. def current_frames_with_threads(self):
  260. import threading, thread
  261. import traceback
  262. # Spawn a thread that blocks at a known place. Then the main
  263. # thread does sys._current_frames(), and verifies that the frames
  264. # returned make sense.
  265. entered_g = threading.Event()
  266. leave_g = threading.Event()
  267. thread_info = [] # the thread's id
  268. def f123():
  269. g456()
  270. def g456():
  271. thread_info.append(thread.get_ident())
  272. entered_g.set()
  273. leave_g.wait()
  274. t = threading.Thread(target=f123)
  275. t.start()
  276. entered_g.wait()
  277. # At this point, t has finished its entered_g.set(), although it's
  278. # impossible to guess whether it's still on that line or has moved on
  279. # to its leave_g.wait().
  280. self.assertEqual(len(thread_info), 1)
  281. thread_id = thread_info[0]
  282. d = sys._current_frames()
  283. main_id = thread.get_ident()
  284. self.assertIn(main_id, d)
  285. self.assertIn(thread_id, d)
  286. # Verify that the captured main-thread frame is _this_ frame.
  287. frame = d.pop(main_id)
  288. self.assertTrue(frame is sys._getframe())
  289. # Verify that the captured thread frame is blocked in g456, called
  290. # from f123. This is a litte tricky, since various bits of
  291. # threading.py are also in the thread's call stack.
  292. frame = d.pop(thread_id)
  293. stack = traceback.extract_stack(frame)
  294. for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
  295. if funcname == "f123":
  296. break
  297. else:
  298. self.fail("didn't find f123() on thread's call stack")
  299. self.assertEqual(sourceline, "g456()")
  300. # And the next record must be for g456().
  301. filename, lineno, funcname, sourceline = stack[i+1]
  302. self.assertEqual(funcname, "g456")
  303. self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
  304. # Reap the spawned thread.
  305. leave_g.set()
  306. t.join()
  307. # Test sys._current_frames() when thread support doesn't exist.
  308. def current_frames_without_threads(self):
  309. # Not much happens here: there is only one thread, with artificial
  310. # "thread id" 0.
  311. d = sys._current_frames()
  312. self.assertEqual(len(d), 1)
  313. self.assertIn(0, d)
  314. self.assertTrue(d[0] is sys._getframe())
  315. def test_attributes(self):
  316. self.assertIsInstance(sys.api_version, int)
  317. self.assertIsInstance(sys.argv, list)
  318. self.assertIn(sys.byteorder, ("little", "big"))
  319. self.assertIsInstance(sys.builtin_module_names, tuple)
  320. self.assertIsInstance(sys.copyright, basestring)
  321. self.assertIsInstance(sys.exec_prefix, basestring)
  322. self.assertIsInstance(sys.executable, basestring)
  323. self.assertEqual(len(sys.float_info), 11)
  324. self.assertEqual(sys.float_info.radix, 2)
  325. self.assertEqual(len(sys.long_info), 2)
  326. self.assertTrue(sys.long_info.bits_per_digit % 5 == 0)
  327. self.assertTrue(sys.long_info.sizeof_digit >= 1)
  328. self.assertEqual(type(sys.long_info.bits_per_digit), int)
  329. self.assertEqual(type(sys.long_info.sizeof_digit), int)
  330. self.assertIsInstance(sys.hexversion, int)
  331. self.assertIsInstance(sys.maxint, int)
  332. if test.test_support.have_unicode:
  333. self.assertIsInstance(sys.maxunicode, int)
  334. self.assertIsInstance(sys.platform, basestring)
  335. self.assertIsInstance(sys.prefix, basestring)
  336. self.assertIsInstance(sys.version, basestring)
  337. vi = sys.version_info
  338. self.assertIsInstance(vi[:], tuple)
  339. self.assertEqual(len(vi), 5)
  340. self.assertIsInstance(vi[0], int)
  341. self.assertIsInstance(vi[1], int)
  342. self.assertIsInstance(vi[2], int)
  343. self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
  344. self.assertIsInstance(vi[4], int)
  345. self.assertIsInstance(vi.major, int)
  346. self.assertIsInstance(vi.minor, int)
  347. self.assertIsInstance(vi.micro, int)
  348. self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
  349. self.assertIsInstance(vi.serial, int)
  350. self.assertEqual(vi[0], vi.major)
  351. self.assertEqual(vi[1], vi.minor)
  352. self.assertEqual(vi[2], vi.micro)
  353. self.assertEqual(vi[3], vi.releaselevel)
  354. self.assertEqual(vi[4], vi.serial)
  355. self.assertTrue(vi > (1,0,0))
  356. self.assertIsInstance(sys.float_repr_style, str)
  357. self.assertIn(sys.float_repr_style, ('short', 'legacy'))
  358. def test_43581(self):
  359. # Can't use sys.stdout, as this is a cStringIO object when
  360. # the test runs under regrtest.
  361. self.assertTrue(sys.__stdout__.encoding == sys.__stderr__.encoding)
  362. def test_sys_flags(self):
  363. self.assertTrue(sys.flags)
  364. attrs = ("debug", "py3k_warning", "division_warning", "division_new",
  365. "inspect", "interactive", "optimize", "dont_write_bytecode",
  366. "no_site", "ignore_environment", "tabcheck", "verbose",
  367. "unicode", "bytes_warning")
  368. for attr in attrs:
  369. self.assertTrue(hasattr(sys.flags, attr), attr)
  370. self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
  371. self.assertTrue(repr(sys.flags))
  372. def test_clear_type_cache(self):
  373. sys._clear_type_cache()
  374. def test_ioencoding(self):
  375. import subprocess
  376. env = dict(os.environ)
  377. # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
  378. # not representable in ASCII.
  379. env["PYTHONIOENCODING"] = "cp424"
  380. p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
  381. stdout = subprocess.PIPE, env=env)
  382. out = p.communicate()[0].strip()
  383. self.assertEqual(out, unichr(0xa2).encode("cp424"))
  384. env["PYTHONIOENCODING"] = "ascii:replace"
  385. p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
  386. stdout = subprocess.PIPE, env=env)
  387. out = p.communicate()[0].strip()
  388. self.assertEqual(out, '?')
  389. def test_call_tracing(self):
  390. self.assertEqual(sys.call_tracing(str, (2,)), "2")
  391. self.assertRaises(TypeError, sys.call_tracing, str, 2)
  392. def test_executable(self):
  393. # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
  394. # has been set to an non existent program name and Python is unable to
  395. # retrieve the real program name
  396. import subprocess
  397. # For a normal installation, it should work without 'cwd'
  398. # argument. For test runs in the build directory, see #7774.
  399. python_dir = os.path.dirname(os.path.realpath(sys.executable))
  400. p = subprocess.Popen(
  401. ["nonexistent", "-c", 'import sys; print repr(sys.executable)'],
  402. executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
  403. executable = p.communicate()[0].strip()
  404. p.wait()
  405. self.assertIn(executable, ["''", repr(sys.executable)])
  406. class SizeofTest(unittest.TestCase):
  407. TPFLAGS_HAVE_GC = 1<<14
  408. TPFLAGS_HEAPTYPE = 1L<<9
  409. def setUp(self):
  410. self.c = len(struct.pack('c', ' '))
  411. self.H = len(struct.pack('H', 0))
  412. self.i = len(struct.pack('i', 0))
  413. self.l = len(struct.pack('l', 0))
  414. self.P = len(struct.pack('P', 0))
  415. # due to missing size_t information from struct, it is assumed that
  416. # sizeof(Py_ssize_t) = sizeof(void*)
  417. self.header = 'PP'
  418. self.vheader = self.header + 'P'
  419. if hasattr(sys, "gettotalrefcount"):
  420. self.header += '2P'
  421. self.vheader += '2P'
  422. self.longdigit = sys.long_info.sizeof_digit
  423. import _testcapi
  424. self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
  425. self.file = open(test.test_support.TESTFN, 'wb')
  426. def tearDown(self):
  427. self.file.close()
  428. test.test_support.unlink(test.test_support.TESTFN)
  429. def check_sizeof(self, o, size):
  430. result = sys.getsizeof(o)
  431. if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
  432. ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
  433. size += self.gc_headsize
  434. msg = 'wrong size for %s: got %d, expected %d' \
  435. % (type(o), result, size)
  436. self.assertEqual(result, size, msg)
  437. def calcsize(self, fmt):
  438. """Wrapper around struct.calcsize which enforces the alignment of the
  439. end of a structure to the alignment requirement of pointer.
  440. Note: This wrapper should only be used if a pointer member is included
  441. and no member with a size larger than a pointer exists.
  442. """
  443. return struct.calcsize(fmt + '0P')
  444. def test_gc_head_size(self):
  445. # Check that the gc header size is added to objects tracked by the gc.
  446. h = self.header
  447. size = self.calcsize
  448. gc_header_size = self.gc_headsize
  449. # bool objects are not gc tracked
  450. self.assertEqual(sys.getsizeof(True), size(h + 'l'))
  451. # but lists are
  452. self.assertEqual(sys.getsizeof([]), size(h + 'P PP') + gc_header_size)
  453. def test_default(self):
  454. h = self.header
  455. size = self.calcsize
  456. self.assertEqual(sys.getsizeof(True, -1), size(h + 'l'))
  457. def test_objecttypes(self):
  458. # check all types defined in Objects/
  459. h = self.header
  460. vh = self.vheader
  461. size = self.calcsize
  462. check = self.check_sizeof
  463. # bool
  464. check(True, size(h + 'l'))
  465. # buffer
  466. with test.test_support.check_py3k_warnings():
  467. check(buffer(''), size(h + '2P2Pil'))
  468. # builtin_function_or_method
  469. check(len, size(h + '3P'))
  470. # bytearray
  471. samples = ['', 'u'*100000]
  472. for sample in samples:
  473. x = bytearray(sample)
  474. check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
  475. # bytearray_iterator
  476. check(iter(bytearray()), size(h + 'PP'))
  477. # cell
  478. def get_cell():
  479. x = 42
  480. def inner():
  481. return x
  482. return inner
  483. check(get_cell().func_closure[0], size(h + 'P'))
  484. # classobj (old-style class)
  485. class class_oldstyle():
  486. def method():
  487. pass
  488. check(class_oldstyle, size(h + '7P'))
  489. # instance (old-style class)
  490. check(class_oldstyle(), size(h + '3P'))
  491. # instancemethod (old-style class)
  492. check(class_oldstyle().method, size(h + '4P'))
  493. # complex
  494. check(complex(0,1), size(h + '2d'))
  495. # code
  496. check(get_cell().func_code, size(h + '4i8Pi3P'))
  497. # BaseException
  498. check(BaseException(), size(h + '3P'))
  499. # UnicodeEncodeError
  500. check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP'))
  501. # UnicodeDecodeError
  502. check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
  503. # UnicodeTranslateError
  504. check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP'))
  505. # method_descriptor (descriptor object)
  506. check(str.lower, size(h + '2PP'))
  507. # classmethod_descriptor (descriptor object)
  508. # XXX
  509. # member_descriptor (descriptor object)
  510. import datetime
  511. check(datetime.timedelta.days, size(h + '2PP'))
  512. # getset_descriptor (descriptor object)
  513. import __builtin__
  514. check(__builtin__.file.closed, size(h + '2PP'))
  515. # wrapper_descriptor (descriptor object)
  516. check(int.__add__, size(h + '2P2P'))
  517. # dictproxy
  518. class C(object): pass
  519. check(C.__dict__, size(h + 'P'))
  520. # method-wrapper (descriptor object)
  521. check({}.__iter__, size(h + '2P'))
  522. # dict
  523. check({}, size(h + '3P2P' + 8*'P2P'))
  524. x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
  525. check(x, size(h + '3P2P' + 8*'P2P') + 16*size('P2P'))
  526. # dictionary-keyiterator
  527. check({}.iterkeys(), size(h + 'P2PPP'))
  528. # dictionary-valueiterator
  529. check({}.itervalues(), size(h + 'P2PPP'))
  530. # dictionary-itemiterator
  531. check({}.iteritems(), size(h + 'P2PPP'))
  532. # ellipses
  533. check(Ellipsis, size(h + ''))
  534. # EncodingMap
  535. import codecs, encodings.iso8859_3
  536. x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
  537. check(x, size(h + '32B2iB'))
  538. # enumerate
  539. check(enumerate([]), size(h + 'l3P'))
  540. # file
  541. check(self.file, size(h + '4P2i4P3i3P3i'))
  542. # float
  543. check(float(0), size(h + 'd'))
  544. # sys.floatinfo
  545. check(sys.float_info, size(vh) + self.P * len(sys.float_info))
  546. # frame
  547. import inspect
  548. CO_MAXBLOCKS = 20
  549. x = inspect.currentframe()
  550. ncells = len(x.f_code.co_cellvars)
  551. nfrees = len(x.f_code.co_freevars)
  552. extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
  553. ncells + nfrees - 1
  554. check(x, size(vh + '12P3i' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P'))
  555. # function
  556. def func(): pass
  557. check(func, size(h + '9P'))
  558. class c():
  559. @staticmethod
  560. def foo():
  561. pass
  562. @classmethod
  563. def bar(cls):
  564. pass
  565. # staticmethod
  566. check(foo, size(h + 'P'))
  567. # classmethod
  568. check(bar, size(h + 'P'))
  569. # generator
  570. def get_gen(): yield 1
  571. check(get_gen(), size(h + 'Pi2P'))
  572. # integer
  573. check(1, size(h + 'l'))
  574. check(100, size(h + 'l'))
  575. # iterator
  576. check(iter('abc'), size(h + 'lP'))
  577. # callable-iterator
  578. import re
  579. check(re.finditer('',''), size(h + '2P'))
  580. # list
  581. samples = [[], [1,2,3], ['1', '2', '3']]
  582. for sample in samples:
  583. check(sample, size(vh + 'PP') + len(sample)*self.P)
  584. # sortwrapper (list)
  585. # XXX
  586. # cmpwrapper (list)
  587. # XXX
  588. # listiterator (list)
  589. check(iter([]), size(h + 'lP'))
  590. # listreverseiterator (list)
  591. check(reversed([]), size(h + 'lP'))
  592. # long
  593. check(0L, size(vh))
  594. check(1L, size(vh) + self.longdigit)
  595. check(-1L, size(vh) + self.longdigit)
  596. PyLong_BASE = 2**sys.long_info.bits_per_digit
  597. check(long(PyLong_BASE), size(vh) + 2*self.longdigit)
  598. check(long(PyLong_BASE**2-1), size(vh) + 2*self.longdigit)
  599. check(long(PyLong_BASE**2), size(vh) + 3*self.longdigit)
  600. # module
  601. check(unittest, size(h + 'P'))
  602. # None
  603. check(None, size(h + ''))
  604. # object
  605. check(object(), size(h + ''))
  606. # property (descriptor object)
  607. class C(object):
  608. def getx(self): return self.__x
  609. def setx(self, value): self.__x = value
  610. def delx(self): del self.__x
  611. x = property(getx, setx, delx, "")
  612. check(x, size(h + '4Pi'))
  613. # PyCObject
  614. # PyCapsule
  615. # XXX
  616. # rangeiterator
  617. check(iter(xrange(1)), size(h + '4l'))
  618. # reverse
  619. check(reversed(''), size(h + 'PP'))
  620. # set
  621. # frozenset
  622. PySet_MINSIZE = 8
  623. samples = [[], range(10), range(50)]
  624. s = size(h + '3P2P' + PySet_MINSIZE*'lP' + 'lP')
  625. for sample in samples:
  626. minused = len(sample)
  627. if minused == 0: tmp = 1
  628. # the computation of minused is actually a bit more complicated
  629. # but this suffices for the sizeof test
  630. minused = minused*2
  631. newsize = PySet_MINSIZE
  632. while newsize <= minused:
  633. newsize = newsize << 1
  634. if newsize <= 8:
  635. check(set(sample), s)
  636. check(frozenset(sample), s)
  637. else:
  638. check(set(sample), s + newsize*struct.calcsize('lP'))
  639. check(frozenset(sample), s + newsize*struct.calcsize('lP'))
  640. # setiterator
  641. check(iter(set()), size(h + 'P3P'))
  642. # slice
  643. check(slice(1), size(h + '3P'))
  644. # str
  645. check('', struct.calcsize(vh + 'li') + 1)
  646. check('abc', struct.calcsize(vh + 'li') + 1 + 3*self.c)
  647. # super
  648. check(super(int), size(h + '3P'))
  649. # tuple
  650. check((), size(vh))
  651. check((1,2,3), size(vh) + 3*self.P)
  652. # tupleiterator
  653. check(iter(()), size(h + 'lP'))
  654. # type
  655. # (PyTypeObject + PyNumberMethods + PyMappingMethods +
  656. # PySequenceMethods + PyBufferProcs)
  657. s = size(vh + 'P2P15Pl4PP9PP11PI') + size('41P 10P 3P 6P')
  658. class newstyleclass(object):
  659. pass
  660. check(newstyleclass, s)
  661. # builtin type
  662. check(int, s)
  663. # NotImplementedType
  664. import types
  665. check(types.NotImplementedType, s)
  666. # unicode
  667. usize = len(u'\0'.encode('unicode-internal'))
  668. samples = [u'', u'1'*100]
  669. # we need to test for both sizes, because we don't know if the string
  670. # has been cached
  671. for s in samples:
  672. check(s, size(h + 'PPlP') + usize * (len(s) + 1))
  673. # weakref
  674. import weakref
  675. check(weakref.ref(int), size(h + '2Pl2P'))
  676. # weakproxy
  677. # XXX
  678. # weakcallableproxy
  679. check(weakref.proxy(int), size(h + '2Pl2P'))
  680. # xrange
  681. check(xrange(1), size(h + '3l'))
  682. check(xrange(66000), size(h + '3l'))
  683. def test_pythontypes(self):
  684. # check all types defined in Python/
  685. h = self.header
  686. vh = self.vheader
  687. size = self.calcsize
  688. check = self.check_sizeof
  689. # _ast.AST
  690. import _ast
  691. check(_ast.AST(), size(h + ''))
  692. # imp.NullImporter
  693. import imp
  694. check(imp.NullImporter(self.file.name), size(h + ''))
  695. try:
  696. raise TypeError
  697. except TypeError:
  698. tb = sys.exc_info()[2]
  699. # traceback
  700. if tb != None:
  701. check(tb, size(h + '2P2i'))
  702. # symtable entry
  703. # XXX
  704. # sys.flags
  705. check(sys.flags, size(vh) + self.P * len(sys.flags))
  706. def test_main():
  707. test_classes = (SysModuleTest, SizeofTest)
  708. test.test_support.run_unittest(*test_classes)
  709. if __name__ == "__main__":
  710. test_main()