/Lib/test/test_sys.py

http://unladen-swallow.googlecode.com/ · Python · 773 lines · 529 code · 81 blank · 163 comment · 65 complexity · ef6fcaf774386986cb637636bf3f4a7d MD5 · raw file

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