PageRenderTime 61ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/sys/test/test_sysmodule.py

https://bitbucket.org/vanl/pypy
Python | 834 lines | 804 code | 26 blank | 4 comment | 14 complexity | f16ab801ca7ec9ab8d4130b4fdf8caf8 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, AGPL-3.0
  1. # -*- coding: iso-8859-1 -*-
  2. import sys
  3. def test_stdin_exists(space):
  4. space.sys.get('stdin')
  5. space.sys.get('__stdin__')
  6. def test_stdout_exists(space):
  7. space.sys.get('stdout')
  8. space.sys.get('__stdout__')
  9. class AppTestAppSysTests:
  10. def setup_class(cls):
  11. cls.w_appdirect = cls.space.wrap(cls.runappdirect)
  12. cls.w_filesystemenc = cls.space.wrap(sys.getfilesystemencoding())
  13. def test_sys_in_modules(self):
  14. import sys
  15. modules = sys.modules
  16. assert 'sys' in modules, ( "An entry for sys "
  17. "is not in sys.modules.")
  18. sys2 = sys.modules['sys']
  19. assert sys is sys2, "import sys is not sys.modules[sys]."
  20. def test_builtin_in_modules(self):
  21. import sys
  22. modules = sys.modules
  23. assert '__builtin__' in modules, ( "An entry for __builtin__ "
  24. "is not in sys.modules.")
  25. import __builtin__
  26. builtin2 = sys.modules['__builtin__']
  27. assert __builtin__ is builtin2, ( "import __builtin__ "
  28. "is not sys.modules[__builtin__].")
  29. def test_builtin_module_names(self):
  30. import sys
  31. names = sys.builtin_module_names
  32. assert 'sys' in names, (
  33. "sys is not listed as a builtin module.")
  34. assert '__builtin__' in names, (
  35. "__builtin__ is not listed as a builtin module.")
  36. def test_sys_exc_info(self):
  37. try:
  38. raise Exception
  39. except Exception,e:
  40. import sys
  41. exc_type,exc_val,tb = sys.exc_info()
  42. try:
  43. raise Exception # 5 lines below the previous one
  44. except Exception,e2:
  45. exc_type2,exc_val2,tb2 = sys.exc_info()
  46. assert exc_type ==Exception
  47. assert exc_val ==e
  48. assert exc_type2 ==Exception
  49. assert exc_val2 ==e2
  50. assert tb2.tb_lineno - tb.tb_lineno == 5
  51. def test_dynamic_attributes(self):
  52. try:
  53. raise Exception
  54. except Exception,e:
  55. import sys
  56. exc_type = sys.exc_type
  57. exc_val = sys.exc_value
  58. tb = sys.exc_traceback
  59. try:
  60. raise Exception # 7 lines below the previous one
  61. except Exception,e2:
  62. exc_type2 = sys.exc_type
  63. exc_val2 = sys.exc_value
  64. tb2 = sys.exc_traceback
  65. assert exc_type ==Exception
  66. assert exc_val ==e
  67. assert exc_type2 ==Exception
  68. assert exc_val2 ==e2
  69. assert tb2.tb_lineno - tb.tb_lineno == 7
  70. def test_exc_info_normalization(self):
  71. import sys
  72. try:
  73. 1/0
  74. except ZeroDivisionError:
  75. etype, val, tb = sys.exc_info()
  76. assert isinstance(val, etype)
  77. else:
  78. raise AssertionError, "ZeroDivisionError not caught"
  79. def test_io(self):
  80. import sys
  81. assert isinstance(sys.__stdout__, file)
  82. assert isinstance(sys.__stderr__, file)
  83. assert isinstance(sys.__stdin__, file)
  84. #assert sys.__stdin__.name == "<stdin>"
  85. #assert sys.__stdout__.name == "<stdout>"
  86. #assert sys.__stderr__.name == "<stderr>"
  87. if self.appdirect and not isinstance(sys.stdin, file):
  88. return
  89. assert isinstance(sys.stdout, file)
  90. assert isinstance(sys.stderr, file)
  91. assert isinstance(sys.stdin, file)
  92. def test_getfilesystemencoding(self):
  93. import sys
  94. assert sys.getfilesystemencoding() == self.filesystemenc
  95. def test_float_info(self):
  96. import sys
  97. fi = sys.float_info
  98. assert isinstance(fi.epsilon, float)
  99. assert isinstance(fi.dig, int)
  100. assert isinstance(fi.mant_dig, int)
  101. assert isinstance(fi.max, float)
  102. assert isinstance(fi.max_exp, int)
  103. assert isinstance(fi.max_10_exp, int)
  104. assert isinstance(fi.min, float)
  105. assert isinstance(fi.min_exp, int)
  106. assert isinstance(fi.min_10_exp, int)
  107. assert isinstance(fi.radix, int)
  108. assert isinstance(fi.rounds, int)
  109. def test_long_info(self):
  110. import sys
  111. li = sys.long_info
  112. assert isinstance(li.bits_per_digit, int)
  113. assert isinstance(li.sizeof_digit, int)
  114. def test_sys_exit(self):
  115. import sys
  116. exc = raises(SystemExit, sys.exit)
  117. assert exc.value.code is None
  118. exc = raises(SystemExit, sys.exit, 0)
  119. assert exc.value.code == 0
  120. exc = raises(SystemExit, sys.exit, 1)
  121. assert exc.value.code == 1
  122. exc = raises(SystemExit, sys.exit, (1, 2, 3))
  123. assert exc.value.code == (1, 2, 3)
  124. class AppTestSysModulePortedFromCPython:
  125. def setup_class(cls):
  126. cls.w_appdirect = cls.space.wrap(cls.runappdirect)
  127. def test_original_displayhook(self):
  128. import sys, cStringIO, __builtin__
  129. savestdout = sys.stdout
  130. out = cStringIO.StringIO()
  131. sys.stdout = out
  132. dh = sys.__displayhook__
  133. raises(TypeError, dh)
  134. if hasattr(__builtin__, "_"):
  135. del __builtin__._
  136. dh(None)
  137. assert out.getvalue() == ""
  138. assert not hasattr(__builtin__, "_")
  139. dh("hello")
  140. assert out.getvalue() == "'hello'\n"
  141. assert __builtin__._ == "hello"
  142. del sys.stdout
  143. raises(RuntimeError, dh, 42)
  144. sys.stdout = savestdout
  145. def test_lost_displayhook(self):
  146. import sys
  147. olddisplayhook = sys.displayhook
  148. del sys.displayhook
  149. code = compile("42", "<string>", "single")
  150. raises(RuntimeError, eval, code)
  151. sys.displayhook = olddisplayhook
  152. def test_custom_displayhook(self):
  153. import sys
  154. olddisplayhook = sys.displayhook
  155. def baddisplayhook(obj):
  156. raise ValueError
  157. sys.displayhook = baddisplayhook
  158. code = compile("42", "<string>", "single")
  159. raises(ValueError, eval, code)
  160. sys.displayhook = olddisplayhook
  161. def test_original_excepthook(self):
  162. import sys, cStringIO
  163. savestderr = sys.stderr
  164. err = cStringIO.StringIO()
  165. sys.stderr = err
  166. eh = sys.__excepthook__
  167. raises(TypeError, eh)
  168. try:
  169. raise ValueError(42)
  170. except ValueError, exc:
  171. eh(*sys.exc_info())
  172. sys.stderr = savestderr
  173. assert err.getvalue().endswith("ValueError: 42\n")
  174. def test_excepthook_failsafe_path(self):
  175. import traceback
  176. original_print_exception = traceback.print_exception
  177. import sys, cStringIO
  178. savestderr = sys.stderr
  179. err = cStringIO.StringIO()
  180. sys.stderr = err
  181. try:
  182. traceback.print_exception = "foo"
  183. eh = sys.__excepthook__
  184. try:
  185. raise ValueError(42)
  186. except ValueError, exc:
  187. eh(*sys.exc_info())
  188. finally:
  189. traceback.print_exception = original_print_exception
  190. sys.stderr = savestderr
  191. assert err.getvalue() == "ValueError: 42\n"
  192. def test_original_excepthook_pypy_encoding(self):
  193. import sys
  194. if '__pypy__' not in sys.builtin_module_names:
  195. skip("only on PyPy")
  196. savestderr = sys.stderr
  197. class MyStringIO(object):
  198. def __init__(self):
  199. self.output = []
  200. def write(self, s):
  201. assert isinstance(s, str)
  202. self.output.append(s)
  203. def getvalue(self):
  204. return ''.join(self.output)
  205. for input, expectedoutput in [(u"\u013a", "\xe5"),
  206. (u"\u1111", "\\u1111")]:
  207. err = MyStringIO()
  208. err.encoding = 'iso-8859-2'
  209. sys.stderr = err
  210. eh = sys.__excepthook__
  211. try:
  212. raise ValueError(input)
  213. except ValueError, exc:
  214. eh(*sys.exc_info())
  215. sys.stderr = savestderr
  216. print repr(err.getvalue())
  217. assert err.getvalue().endswith("ValueError: %s\n" % expectedoutput)
  218. # FIXME: testing the code for a lost or replaced excepthook in
  219. # Python/pythonrun.c::PyErr_PrintEx() is tricky.
  220. def test_exc_clear(self):
  221. import sys
  222. raises(TypeError, sys.exc_clear, 42)
  223. # Verify that exc_info is present and matches exc, then clear it, and
  224. # check that it worked.
  225. def clear_check(exc):
  226. typ, value, traceback = sys.exc_info()
  227. assert typ is not None
  228. assert value is exc
  229. assert traceback is not None
  230. sys.exc_clear()
  231. typ, value, traceback = sys.exc_info()
  232. assert typ is None
  233. assert value is None
  234. assert traceback is None
  235. def clear():
  236. try:
  237. raise ValueError, 42
  238. except ValueError, exc:
  239. clear_check(exc)
  240. # Raise an exception and check that it can be cleared
  241. clear()
  242. # Verify that a frame currently handling an exception is
  243. # unaffected by calling exc_clear in a nested frame.
  244. try:
  245. raise ValueError, 13
  246. except ValueError, exc:
  247. typ1, value1, traceback1 = sys.exc_info()
  248. clear()
  249. typ2, value2, traceback2 = sys.exc_info()
  250. assert typ1 is typ2
  251. assert value1 is exc
  252. assert value1 is value2
  253. assert traceback1 is traceback2
  254. # Check that an exception can be cleared outside of an except block
  255. clear_check(exc)
  256. def test_exit(self):
  257. import sys
  258. raises(TypeError, sys.exit, 42, 42)
  259. # call without argument
  260. try:
  261. sys.exit(0)
  262. except SystemExit, exc:
  263. assert exc.code == 0
  264. except:
  265. raise AssertionError, "wrong exception"
  266. else:
  267. raise AssertionError, "no exception"
  268. # call with tuple argument with one entry
  269. # entry will be unpacked
  270. try:
  271. sys.exit(42)
  272. except SystemExit, exc:
  273. assert exc.code == 42
  274. except:
  275. raise AssertionError, "wrong exception"
  276. else:
  277. raise AssertionError, "no exception"
  278. # call with integer argument
  279. try:
  280. sys.exit((42,))
  281. except SystemExit, exc:
  282. assert exc.code == 42
  283. except:
  284. raise AssertionError, "wrong exception"
  285. else:
  286. raise AssertionError, "no exception"
  287. # call with string argument
  288. try:
  289. sys.exit("exit")
  290. except SystemExit, exc:
  291. assert exc.code == "exit"
  292. except:
  293. raise AssertionError, "wrong exception"
  294. else:
  295. raise AssertionError, "no exception"
  296. # call with tuple argument with two entries
  297. try:
  298. sys.exit((17, 23))
  299. except SystemExit, exc:
  300. assert exc.code == (17, 23)
  301. except:
  302. raise AssertionError, "wrong exception"
  303. else:
  304. raise AssertionError, "no exception"
  305. def test_getdefaultencoding(self):
  306. import sys
  307. raises(TypeError, sys.getdefaultencoding, 42)
  308. # can't check more than the type, as the user might have changed it
  309. assert isinstance(sys.getdefaultencoding(), str)
  310. def test_setdefaultencoding(self):
  311. import sys
  312. if self.appdirect:
  313. skip("not worth running appdirect")
  314. encoding = sys.getdefaultencoding()
  315. try:
  316. sys.setdefaultencoding("ascii")
  317. assert sys.getdefaultencoding() == 'ascii'
  318. raises(UnicodeDecodeError, unicode, '\x80')
  319. sys.setdefaultencoding("latin-1")
  320. assert sys.getdefaultencoding() == 'latin-1'
  321. assert unicode('\x80') == u'\u0080'
  322. finally:
  323. sys.setdefaultencoding(encoding)
  324. # testing sys.settrace() is done in test_trace.py
  325. # testing sys.setprofile() is done in test_profile.py
  326. def test_setcheckinterval(self):
  327. import sys
  328. raises(TypeError, sys.setcheckinterval)
  329. orig = sys.getcheckinterval()
  330. for n in 0, 100, 120, orig: # orig last to restore starting state
  331. sys.setcheckinterval(n)
  332. assert sys.getcheckinterval() == n
  333. def test_recursionlimit(self):
  334. import sys
  335. raises(TypeError, sys.getrecursionlimit, 42)
  336. oldlimit = sys.getrecursionlimit()
  337. raises(TypeError, sys.setrecursionlimit)
  338. raises(ValueError, sys.setrecursionlimit, -42)
  339. sys.setrecursionlimit(10000)
  340. assert sys.getrecursionlimit() == 10000
  341. sys.setrecursionlimit(oldlimit)
  342. raises(OverflowError, sys.setrecursionlimit, 1<<31)
  343. def test_getwindowsversion(self):
  344. import sys
  345. if hasattr(sys, "getwindowsversion"):
  346. v = sys.getwindowsversion()
  347. if '__pypy__' in sys.builtin_module_names:
  348. assert isinstance(v, tuple)
  349. assert len(v) == 5
  350. assert isinstance(v[0], int)
  351. assert isinstance(v[1], int)
  352. assert isinstance(v[2], int)
  353. assert isinstance(v[3], int)
  354. assert isinstance(v[4], str)
  355. assert v[0] == v.major
  356. assert v[1] == v.minor
  357. assert v[2] == v.build
  358. assert v[3] == v.platform
  359. assert v[4] == v.service_pack
  360. assert isinstance(v.service_pack_minor, int)
  361. assert isinstance(v.service_pack_major, int)
  362. assert isinstance(v.suite_mask, int)
  363. assert isinstance(v.product_type, int)
  364. # This is how platform.py calls it. Make sure tuple still has 5
  365. # elements
  366. maj, min, buildno, plat, csd = sys.getwindowsversion()
  367. def test_winver(self):
  368. import sys
  369. if hasattr(sys, "winver"):
  370. assert sys.winver == sys.version[:3]
  371. def test_dllhandle(self):
  372. import sys
  373. assert hasattr(sys, 'dllhandle') == (sys.platform == 'win32')
  374. def test_dlopenflags(self):
  375. import sys
  376. if hasattr(sys, "setdlopenflags"):
  377. assert hasattr(sys, "getdlopenflags")
  378. raises(TypeError, sys.getdlopenflags, 42)
  379. oldflags = sys.getdlopenflags()
  380. raises(TypeError, sys.setdlopenflags)
  381. sys.setdlopenflags(oldflags+1)
  382. assert sys.getdlopenflags() == oldflags+1
  383. sys.setdlopenflags(oldflags)
  384. def test_refcount(self):
  385. import sys
  386. if not hasattr(sys, "getrefcount"):
  387. skip('Reference counting is not implemented.')
  388. raises(TypeError, sys.getrefcount)
  389. c = sys.getrefcount(None)
  390. n = None
  391. assert sys.getrefcount(None) == c+1
  392. del n
  393. assert sys.getrefcount(None) == c
  394. if hasattr(sys, "gettotalrefcount"):
  395. assert isinstance(sys.gettotalrefcount(), int)
  396. def test_getframe(self):
  397. import sys
  398. raises(TypeError, sys._getframe, 42, 42)
  399. raises(ValueError, sys._getframe, 2000000000)
  400. assert sys._getframe().f_code.co_name == 'test_getframe'
  401. #assert (
  402. # TestSysModule.test_getframe.im_func.func_code \
  403. # is sys._getframe().f_code
  404. #)
  405. def test_getframe_in_returned_func(self):
  406. import sys
  407. def f():
  408. return g()
  409. def g():
  410. return sys._getframe(0)
  411. frame = f()
  412. assert frame.f_code.co_name == 'g'
  413. assert frame.f_back.f_code.co_name == 'f'
  414. assert frame.f_back.f_back.f_code.co_name == 'test_getframe_in_returned_func'
  415. def test_attributes(self):
  416. import sys
  417. assert sys.__name__ == 'sys'
  418. assert isinstance(sys.modules, dict)
  419. assert isinstance(sys.path, list)
  420. assert isinstance(sys.api_version, int)
  421. assert isinstance(sys.argv, list)
  422. assert sys.byteorder in ("little", "big")
  423. assert isinstance(sys.builtin_module_names, tuple)
  424. assert isinstance(sys.copyright, basestring)
  425. #assert isinstance(sys.exec_prefix, basestring) -- not present!
  426. #assert isinstance(sys.executable, basestring) -- not present!
  427. assert isinstance(sys.hexversion, int)
  428. assert isinstance(sys.maxint, int)
  429. assert isinstance(sys.maxsize, int)
  430. assert isinstance(sys.maxunicode, int)
  431. assert isinstance(sys.platform, basestring)
  432. #assert isinstance(sys.prefix, basestring) -- not present!
  433. assert isinstance(sys.version, basestring)
  434. assert isinstance(sys.warnoptions, list)
  435. vi = sys.version_info
  436. if '__pypy__' in sys.builtin_module_names:
  437. assert isinstance(vi, tuple)
  438. assert len(vi) == 5
  439. assert isinstance(vi[0], int)
  440. assert isinstance(vi[1], int)
  441. assert isinstance(vi[2], int)
  442. assert vi[3] in ("alpha", "beta", "candidate", "final")
  443. assert isinstance(vi[4], int)
  444. def test_reload_doesnt_override_sys_executable(self):
  445. import sys
  446. if not hasattr(sys, 'executable'): # if not translated
  447. sys.executable = 'from_test_sysmodule'
  448. previous = sys.executable
  449. reload(sys)
  450. assert sys.executable == previous
  451. def test_settrace(self):
  452. import sys
  453. counts = []
  454. def trace(x, y, z):
  455. counts.append(None)
  456. def x():
  457. pass
  458. sys.settrace(trace)
  459. try:
  460. x()
  461. assert sys.gettrace() is trace
  462. finally:
  463. sys.settrace(None)
  464. assert len(counts) == 1
  465. def test_pypy_attributes(self):
  466. import sys
  467. if '__pypy__' not in sys.builtin_module_names:
  468. skip("only on PyPy")
  469. assert isinstance(sys.pypy_objspaceclass, str)
  470. vi = sys.pypy_version_info
  471. assert isinstance(vi, tuple)
  472. assert len(vi) == 5
  473. assert isinstance(vi[0], int)
  474. assert isinstance(vi[1], int)
  475. assert isinstance(vi[2], int)
  476. assert vi[3] in ("alpha", "beta", "candidate", "dev", "final")
  477. assert isinstance(vi[4], int)
  478. def test_allattributes(self):
  479. import sys
  480. sys.__dict__ # check that we don't crash initializing any attribute
  481. def test_subversion(self):
  482. import sys
  483. if '__pypy__' not in sys.builtin_module_names:
  484. skip("only on PyPy")
  485. assert sys.subversion == ('PyPy', '', '')
  486. def test__mercurial(self):
  487. import sys, re
  488. if '__pypy__' not in sys.builtin_module_names:
  489. skip("only on PyPy")
  490. project, hgtag, hgid = sys._mercurial
  491. assert project == 'PyPy'
  492. # the tag or branch may be anything, including the empty string
  493. assert isinstance(hgtag, str)
  494. # the id is either nothing, or an id of 12 hash digits, with a possible
  495. # suffix of '+' if there are local modifications
  496. assert hgid == '' or re.match('[0-9a-f]{12}\+?', hgid)
  497. # the id should also show up in sys.version
  498. if hgid != '':
  499. assert hgid in sys.version
  500. def test_trace_exec_execfile(self):
  501. import sys
  502. found = []
  503. def do_tracing(f, *args):
  504. print f.f_code.co_filename, f.f_lineno, args
  505. if f.f_code.co_filename == 'foobar':
  506. found.append(args[0])
  507. return do_tracing
  508. co = compile("execfile('this-file-does-not-exist!')",
  509. 'foobar', 'exec')
  510. sys.settrace(do_tracing)
  511. try:
  512. exec co in {}
  513. except IOError:
  514. pass
  515. sys.settrace(None)
  516. assert found == ['call', 'line', 'exception', 'return']
  517. def test_float_repr_style(self):
  518. import sys
  519. # If this ever actually becomes a compilation option this test should
  520. # be changed.
  521. assert sys.float_repr_style == "short"
  522. class AppTestSysSettracePortedFromCpython(object):
  523. def test_sys_settrace(self):
  524. import sys
  525. class Tracer:
  526. def __init__(self):
  527. self.events = []
  528. def trace(self, frame, event, arg):
  529. self.events.append((frame.f_lineno, event))
  530. return self.trace
  531. def traceWithGenexp(self, frame, event, arg):
  532. (o for o in [1])
  533. self.events.append((frame.f_lineno, event))
  534. return self.trace
  535. def compare_events(line_offset, events, expected_events):
  536. events = [(l - line_offset, e) for (l, e) in events]
  537. assert events == expected_events
  538. def run_test2(func):
  539. tracer = Tracer()
  540. func(tracer.trace)
  541. sys.settrace(None)
  542. compare_events(func.func_code.co_firstlineno,
  543. tracer.events, func.events)
  544. def _settrace_and_return(tracefunc):
  545. sys.settrace(tracefunc)
  546. sys._getframe().f_back.f_trace = tracefunc
  547. def settrace_and_return(tracefunc):
  548. _settrace_and_return(tracefunc)
  549. def _settrace_and_raise(tracefunc):
  550. sys.settrace(tracefunc)
  551. sys._getframe().f_back.f_trace = tracefunc
  552. raise RuntimeError
  553. def settrace_and_raise(tracefunc):
  554. try:
  555. _settrace_and_raise(tracefunc)
  556. except RuntimeError, exc:
  557. pass
  558. settrace_and_raise.events = [(2, 'exception'),
  559. (3, 'line'),
  560. (4, 'line'),
  561. (4, 'return')]
  562. settrace_and_return.events = [(1, 'return')]
  563. run_test2(settrace_and_return)
  564. run_test2(settrace_and_raise)
  565. class AppTestCurrentFrames:
  566. def test_current_frames(self):
  567. try:
  568. import thread
  569. except ImportError:
  570. pass
  571. else:
  572. skip('This test requires an intepreter without threads')
  573. import sys
  574. def f():
  575. return sys._current_frames()
  576. frames = f()
  577. assert frames.keys() == [0]
  578. assert frames[0].f_code.co_name in ('f', '?')
  579. class AppTestCurrentFramesWithThread(AppTestCurrentFrames):
  580. spaceconfig = {
  581. "usemodules": ["time", "thread"],
  582. }
  583. def test_current_frames(self):
  584. import sys
  585. import time
  586. import thread
  587. # XXX workaround for now: to prevent deadlocks, call
  588. # sys._current_frames() once before starting threads.
  589. # This is an issue in non-translated versions only.
  590. sys._current_frames()
  591. thread_id = thread.get_ident()
  592. def other_thread():
  593. #print "thread started"
  594. lock2.release()
  595. lock1.acquire()
  596. lock1 = thread.allocate_lock()
  597. lock2 = thread.allocate_lock()
  598. lock1.acquire()
  599. lock2.acquire()
  600. thread.start_new_thread(other_thread, ())
  601. def f():
  602. lock2.acquire()
  603. return sys._current_frames()
  604. frames = f()
  605. lock1.release()
  606. thisframe = frames.pop(thread_id)
  607. assert thisframe.f_code.co_name in ('f', '?')
  608. assert len(frames) == 1
  609. _, other_frame = frames.popitem()
  610. assert other_frame.f_code.co_name in ('other_thread', '?')
  611. class AppTestSysExcInfoDirect:
  612. def setup_method(self, meth):
  613. self.checking = not self.runappdirect
  614. if self.checking:
  615. self.seen = []
  616. from pypy.module.sys import vm
  617. def exc_info_with_tb(*args):
  618. self.seen.append("n") # not optimized
  619. return self.old[0](*args)
  620. def exc_info_without_tb(*args):
  621. self.seen.append("y") # optimized
  622. return self.old[1](*args)
  623. self.old = [vm.exc_info_with_tb, vm.exc_info_without_tb]
  624. vm.exc_info_with_tb = exc_info_with_tb
  625. vm.exc_info_without_tb = exc_info_without_tb
  626. #
  627. from rpython.rlib import jit
  628. self.old2 = [jit.we_are_jitted]
  629. jit.we_are_jitted = lambda: True
  630. def teardown_method(self, meth):
  631. if self.checking:
  632. from pypy.module.sys import vm
  633. from rpython.rlib import jit
  634. vm.exc_info_with_tb = self.old[0]
  635. vm.exc_info_without_tb = self.old[1]
  636. jit.we_are_jitted = self.old2[0]
  637. #
  638. assert ''.join(self.seen) == meth.expected
  639. def test_returns_none(self):
  640. import sys
  641. assert sys.exc_info() == (None, None, None)
  642. assert sys.exc_info()[0] is None
  643. assert sys.exc_info()[1] is None
  644. assert sys.exc_info()[2] is None
  645. assert sys.exc_info()[:2] == (None, None)
  646. assert sys.exc_info()[:3] == (None, None, None)
  647. assert sys.exc_info()[0:2] == (None, None)
  648. assert sys.exc_info()[2:4] == (None,)
  649. test_returns_none.expected = 'nnnnnnnn'
  650. def test_returns_subscr(self):
  651. import sys
  652. e = KeyError("boom")
  653. try:
  654. raise e
  655. except:
  656. assert sys.exc_info()[0] is KeyError # y
  657. assert sys.exc_info()[1] is e # y
  658. assert sys.exc_info()[2] is not None # n
  659. assert sys.exc_info()[-3] is KeyError # y
  660. assert sys.exc_info()[-2] is e # y
  661. assert sys.exc_info()[-1] is not None # n
  662. test_returns_subscr.expected = 'yynyyn'
  663. def test_returns_slice_2(self):
  664. import sys
  665. e = KeyError("boom")
  666. try:
  667. raise e
  668. except:
  669. foo = sys.exc_info() # n
  670. assert sys.exc_info()[:0] == () # y
  671. assert sys.exc_info()[:1] == foo[:1] # y
  672. assert sys.exc_info()[:2] == foo[:2] # y
  673. assert sys.exc_info()[:3] == foo # n
  674. assert sys.exc_info()[:4] == foo # n
  675. assert sys.exc_info()[:-1] == foo[:2] # y
  676. assert sys.exc_info()[:-2] == foo[:1] # y
  677. assert sys.exc_info()[:-3] == () # y
  678. test_returns_slice_2.expected = 'nyyynnyyy'
  679. def test_returns_slice_3(self):
  680. import sys
  681. e = KeyError("boom")
  682. try:
  683. raise e
  684. except:
  685. foo = sys.exc_info() # n
  686. assert sys.exc_info()[2:2] == () # y
  687. assert sys.exc_info()[0:1] == foo[:1] # y
  688. assert sys.exc_info()[1:2] == foo[1:2] # y
  689. assert sys.exc_info()[0:3] == foo # n
  690. assert sys.exc_info()[2:4] == foo[2:] # n
  691. assert sys.exc_info()[0:-1] == foo[:2] # y
  692. assert sys.exc_info()[0:-2] == foo[:1] # y
  693. assert sys.exc_info()[5:-3] == () # y
  694. test_returns_slice_3.expected = 'nyyynnyyy'
  695. def test_strange_invocation(self):
  696. import sys
  697. e = KeyError("boom")
  698. try:
  699. raise e
  700. except:
  701. a = []; k = {}
  702. assert sys.exc_info(*a)[:0] == ()
  703. assert sys.exc_info(**k)[:0] == ()
  704. test_strange_invocation.expected = 'nn'
  705. def test_call_in_subfunction(self):
  706. import sys
  707. def g():
  708. # this case is not optimized, because we need to search the
  709. # frame chain. it's probably not worth the complications
  710. return sys.exc_info()[1]
  711. e = KeyError("boom")
  712. try:
  713. raise e
  714. except:
  715. assert g() is e
  716. test_call_in_subfunction.expected = 'n'