PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

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

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