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

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

https://bitbucket.org/kkris/pypy
Python | 716 lines | 695 code | 20 blank | 1 comment | 14 complexity | adb50ea26555f5ba0516ee0ed1dfd33b MD5 | raw file
  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. if self.appdirect and not isinstance(sys.stdin, file):
  85. return
  86. assert isinstance(sys.stdout, file)
  87. assert isinstance(sys.stderr, file)
  88. assert isinstance(sys.stdin, file)
  89. def test_getfilesystemencoding(self):
  90. import sys
  91. assert sys.getfilesystemencoding() == self.filesystemenc
  92. def test_float_info(self):
  93. import sys
  94. fi = sys.float_info
  95. assert isinstance(fi.epsilon, float)
  96. assert isinstance(fi.dig, int)
  97. assert isinstance(fi.mant_dig, int)
  98. assert isinstance(fi.max, float)
  99. assert isinstance(fi.max_exp, int)
  100. assert isinstance(fi.max_10_exp, int)
  101. assert isinstance(fi.min, float)
  102. assert isinstance(fi.min_exp, int)
  103. assert isinstance(fi.min_10_exp, int)
  104. assert isinstance(fi.radix, int)
  105. assert isinstance(fi.rounds, int)
  106. def test_long_info(self):
  107. import sys
  108. li = sys.long_info
  109. assert isinstance(li.bits_per_digit, int)
  110. assert isinstance(li.sizeof_digit, int)
  111. class AppTestSysModulePortedFromCPython:
  112. def setup_class(cls):
  113. cls.w_appdirect = cls.space.wrap(cls.runappdirect)
  114. def test_original_displayhook(self):
  115. import sys, cStringIO, __builtin__
  116. savestdout = sys.stdout
  117. out = cStringIO.StringIO()
  118. sys.stdout = out
  119. dh = sys.__displayhook__
  120. raises(TypeError, dh)
  121. if hasattr(__builtin__, "_"):
  122. del __builtin__._
  123. dh(None)
  124. assert out.getvalue() == ""
  125. assert not hasattr(__builtin__, "_")
  126. dh("hello")
  127. assert out.getvalue() == "'hello'\n"
  128. assert __builtin__._ == "hello"
  129. del sys.stdout
  130. raises(RuntimeError, dh, 42)
  131. sys.stdout = savestdout
  132. def test_lost_displayhook(self):
  133. import sys
  134. olddisplayhook = sys.displayhook
  135. del sys.displayhook
  136. code = compile("42", "<string>", "single")
  137. raises(RuntimeError, eval, code)
  138. sys.displayhook = olddisplayhook
  139. def test_custom_displayhook(self):
  140. import sys
  141. olddisplayhook = sys.displayhook
  142. def baddisplayhook(obj):
  143. raise ValueError
  144. sys.displayhook = baddisplayhook
  145. code = compile("42", "<string>", "single")
  146. raises(ValueError, eval, code)
  147. sys.displayhook = olddisplayhook
  148. def test_original_excepthook(self):
  149. import sys, cStringIO
  150. savestderr = sys.stderr
  151. err = cStringIO.StringIO()
  152. sys.stderr = err
  153. eh = sys.__excepthook__
  154. raises(TypeError, eh)
  155. try:
  156. raise ValueError(42)
  157. except ValueError, exc:
  158. eh(*sys.exc_info())
  159. sys.stderr = savestderr
  160. assert err.getvalue().endswith("ValueError: 42\n")
  161. def test_excepthook_failsafe_path(self):
  162. import traceback
  163. original_print_exception = traceback.print_exception
  164. import sys, cStringIO
  165. savestderr = sys.stderr
  166. err = cStringIO.StringIO()
  167. sys.stderr = err
  168. try:
  169. traceback.print_exception = "foo"
  170. eh = sys.__excepthook__
  171. try:
  172. raise ValueError(42)
  173. except ValueError, exc:
  174. eh(*sys.exc_info())
  175. finally:
  176. traceback.print_exception = original_print_exception
  177. sys.stderr = savestderr
  178. assert err.getvalue() == "ValueError: 42\n"
  179. # FIXME: testing the code for a lost or replaced excepthook in
  180. # Python/pythonrun.c::PyErr_PrintEx() is tricky.
  181. def test_exc_clear(self):
  182. import sys
  183. raises(TypeError, sys.exc_clear, 42)
  184. # Verify that exc_info is present and matches exc, then clear it, and
  185. # check that it worked.
  186. def clear_check(exc):
  187. typ, value, traceback = sys.exc_info()
  188. assert typ is not None
  189. assert value is exc
  190. assert traceback is not None
  191. sys.exc_clear()
  192. typ, value, traceback = sys.exc_info()
  193. assert typ is None
  194. assert value is None
  195. assert traceback is None
  196. def clear():
  197. try:
  198. raise ValueError, 42
  199. except ValueError, exc:
  200. clear_check(exc)
  201. # Raise an exception and check that it can be cleared
  202. clear()
  203. # Verify that a frame currently handling an exception is
  204. # unaffected by calling exc_clear in a nested frame.
  205. try:
  206. raise ValueError, 13
  207. except ValueError, exc:
  208. typ1, value1, traceback1 = sys.exc_info()
  209. clear()
  210. typ2, value2, traceback2 = sys.exc_info()
  211. assert typ1 is typ2
  212. assert value1 is exc
  213. assert value1 is value2
  214. assert traceback1 is traceback2
  215. # Check that an exception can be cleared outside of an except block
  216. clear_check(exc)
  217. def test_exit(self):
  218. import sys
  219. raises(TypeError, sys.exit, 42, 42)
  220. # call without argument
  221. try:
  222. sys.exit(0)
  223. except SystemExit, exc:
  224. assert exc.code == 0
  225. except:
  226. raise AssertionError, "wrong exception"
  227. else:
  228. raise AssertionError, "no exception"
  229. # call with tuple argument with one entry
  230. # entry will be unpacked
  231. try:
  232. sys.exit(42)
  233. except SystemExit, exc:
  234. assert exc.code == 42
  235. except:
  236. raise AssertionError, "wrong exception"
  237. else:
  238. raise AssertionError, "no exception"
  239. # call with integer argument
  240. try:
  241. sys.exit((42,))
  242. except SystemExit, exc:
  243. assert exc.code == 42
  244. except:
  245. raise AssertionError, "wrong exception"
  246. else:
  247. raise AssertionError, "no exception"
  248. # call with string argument
  249. try:
  250. sys.exit("exit")
  251. except SystemExit, exc:
  252. assert exc.code == "exit"
  253. except:
  254. raise AssertionError, "wrong exception"
  255. else:
  256. raise AssertionError, "no exception"
  257. # call with tuple argument with two entries
  258. try:
  259. sys.exit((17, 23))
  260. except SystemExit, exc:
  261. assert exc.code == (17, 23)
  262. except:
  263. raise AssertionError, "wrong exception"
  264. else:
  265. raise AssertionError, "no exception"
  266. def test_getdefaultencoding(self):
  267. import sys
  268. raises(TypeError, sys.getdefaultencoding, 42)
  269. # can't check more than the type, as the user might have changed it
  270. assert isinstance(sys.getdefaultencoding(), str)
  271. def test_setdefaultencoding(self):
  272. import sys
  273. if self.appdirect:
  274. skip("not worth running appdirect")
  275. encoding = sys.getdefaultencoding()
  276. try:
  277. sys.setdefaultencoding("ascii")
  278. assert sys.getdefaultencoding() == 'ascii'
  279. raises(UnicodeDecodeError, unicode, '\x80')
  280. sys.setdefaultencoding("latin-1")
  281. assert sys.getdefaultencoding() == 'latin-1'
  282. assert unicode('\x80') == u'\u0080'
  283. finally:
  284. sys.setdefaultencoding(encoding)
  285. # testing sys.settrace() is done in test_trace.py
  286. # testing sys.setprofile() is done in test_profile.py
  287. def test_setcheckinterval(self):
  288. import sys
  289. raises(TypeError, sys.setcheckinterval)
  290. orig = sys.getcheckinterval()
  291. for n in 0, 100, 120, orig: # orig last to restore starting state
  292. sys.setcheckinterval(n)
  293. assert sys.getcheckinterval() == n
  294. def test_recursionlimit(self):
  295. import sys
  296. raises(TypeError, sys.getrecursionlimit, 42)
  297. oldlimit = sys.getrecursionlimit()
  298. raises(TypeError, sys.setrecursionlimit)
  299. raises(ValueError, sys.setrecursionlimit, -42)
  300. sys.setrecursionlimit(10000)
  301. assert sys.getrecursionlimit() == 10000
  302. sys.setrecursionlimit(oldlimit)
  303. raises(OverflowError, sys.setrecursionlimit, 1<<31)
  304. def test_getwindowsversion(self):
  305. import sys
  306. if hasattr(sys, "getwindowsversion"):
  307. v = sys.getwindowsversion()
  308. assert isinstance(v, tuple)
  309. assert len(v) == 5
  310. assert isinstance(v[0], int)
  311. assert isinstance(v[1], int)
  312. assert isinstance(v[2], int)
  313. assert isinstance(v[3], int)
  314. assert isinstance(v[4], str)
  315. assert v[0] == v.major
  316. assert v[1] == v.minor
  317. assert v[2] == v.build
  318. assert v[3] == v.platform
  319. assert v[4] == v.service_pack
  320. assert isinstance(v.service_pack_minor, int)
  321. assert isinstance(v.service_pack_major, int)
  322. assert isinstance(v.suite_mask, int)
  323. assert isinstance(v.product_type, int)
  324. # This is how platform.py calls it. Make sure tuple still has 5
  325. # elements
  326. maj, min, buildno, plat, csd = sys.getwindowsversion()
  327. def test_winver(self):
  328. import sys
  329. if hasattr(sys, "winver"):
  330. assert sys.winver == sys.version[:3]
  331. def test_dlopenflags(self):
  332. import sys
  333. if hasattr(sys, "setdlopenflags"):
  334. assert hasattr(sys, "getdlopenflags")
  335. raises(TypeError, sys.getdlopenflags, 42)
  336. oldflags = sys.getdlopenflags()
  337. raises(TypeError, sys.setdlopenflags)
  338. sys.setdlopenflags(oldflags+1)
  339. assert sys.getdlopenflags() == oldflags+1
  340. sys.setdlopenflags(oldflags)
  341. def test_refcount(self):
  342. import sys
  343. if not hasattr(sys, "getrefcount"):
  344. skip('Reference counting is not implemented.')
  345. raises(TypeError, sys.getrefcount)
  346. c = sys.getrefcount(None)
  347. n = None
  348. assert sys.getrefcount(None) == c+1
  349. del n
  350. assert sys.getrefcount(None) == c
  351. if hasattr(sys, "gettotalrefcount"):
  352. assert isinstance(sys.gettotalrefcount(), int)
  353. def test_getframe(self):
  354. import sys
  355. raises(TypeError, sys._getframe, 42, 42)
  356. raises(ValueError, sys._getframe, 2000000000)
  357. assert sys._getframe().f_code.co_name == 'test_getframe'
  358. #assert (
  359. # TestSysModule.test_getframe.im_func.func_code \
  360. # is sys._getframe().f_code
  361. #)
  362. def test_getframe_in_returned_func(self):
  363. import sys
  364. def f():
  365. return g()
  366. def g():
  367. return sys._getframe(0)
  368. frame = f()
  369. assert frame.f_code.co_name == 'g'
  370. assert frame.f_back.f_code.co_name == 'f'
  371. assert frame.f_back.f_back.f_code.co_name == 'test_getframe_in_returned_func'
  372. def test_attributes(self):
  373. import sys
  374. assert sys.__name__ == 'sys'
  375. assert isinstance(sys.modules, dict)
  376. assert isinstance(sys.path, list)
  377. assert isinstance(sys.api_version, int)
  378. assert isinstance(sys.argv, list)
  379. assert sys.byteorder in ("little", "big")
  380. assert isinstance(sys.builtin_module_names, tuple)
  381. assert isinstance(sys.copyright, basestring)
  382. #assert isinstance(sys.exec_prefix, basestring) -- not present!
  383. assert isinstance(sys.executable, basestring)
  384. assert isinstance(sys.hexversion, int)
  385. assert isinstance(sys.maxint, int)
  386. assert isinstance(sys.maxsize, int)
  387. assert isinstance(sys.maxunicode, int)
  388. assert isinstance(sys.platform, basestring)
  389. #assert isinstance(sys.prefix, basestring) -- not present!
  390. assert isinstance(sys.version, basestring)
  391. assert isinstance(sys.warnoptions, list)
  392. vi = sys.version_info
  393. assert isinstance(vi, tuple)
  394. assert len(vi) == 5
  395. assert isinstance(vi[0], int)
  396. assert isinstance(vi[1], int)
  397. assert isinstance(vi[2], int)
  398. assert vi[3] in ("alpha", "beta", "candidate", "final")
  399. assert isinstance(vi[4], int)
  400. def test_settrace(self):
  401. import sys
  402. counts = []
  403. def trace(x, y, z):
  404. counts.append(None)
  405. def x():
  406. pass
  407. sys.settrace(trace)
  408. try:
  409. x()
  410. assert sys.gettrace() is trace
  411. finally:
  412. sys.settrace(None)
  413. assert len(counts) == 1
  414. def test_pypy_attributes(self):
  415. import sys
  416. assert isinstance(sys.pypy_objspaceclass, str)
  417. vi = sys.pypy_version_info
  418. assert isinstance(vi, tuple)
  419. assert len(vi) == 5
  420. assert isinstance(vi[0], int)
  421. assert isinstance(vi[1], int)
  422. assert isinstance(vi[2], int)
  423. assert vi[3] in ("alpha", "beta", "candidate", "dev", "final")
  424. assert isinstance(vi[4], int)
  425. def test_allattributes(self):
  426. import sys
  427. sys.__dict__ # check that we don't crash initializing any attribute
  428. def test_subversion(self):
  429. import sys
  430. assert sys.subversion == ('PyPy', '', '')
  431. def test__mercurial(self):
  432. import sys, re
  433. project, hgtag, hgid = sys._mercurial
  434. assert project == 'PyPy'
  435. # the tag or branch may be anything, including the empty string
  436. assert isinstance(hgtag, str)
  437. # the id is either nothing, or an id of 12 hash digits, with a possible
  438. # suffix of '+' if there are local modifications
  439. assert hgid == '' or re.match('[0-9a-f]{12}\+?', hgid)
  440. # the id should also show up in sys.version
  441. if hgid != '':
  442. assert hgid in sys.version
  443. def test_trace_exec_execfile(self):
  444. import sys
  445. found = []
  446. def do_tracing(f, *args):
  447. print f.f_code.co_filename, f.f_lineno, args
  448. if f.f_code.co_filename == 'foobar':
  449. found.append(args[0])
  450. return do_tracing
  451. co = compile("execfile('this-file-does-not-exist!')",
  452. 'foobar', 'exec')
  453. sys.settrace(do_tracing)
  454. try:
  455. exec co in {}
  456. except IOError:
  457. pass
  458. sys.settrace(None)
  459. assert found == ['call', 'line', 'exception', 'return']
  460. def test_float_repr_style(self):
  461. import sys
  462. # If this ever actually becomes a compilation option this test should
  463. # be changed.
  464. assert sys.float_repr_style == "short"
  465. class AppTestCurrentFrames:
  466. def test_current_frames(self):
  467. try:
  468. import thread
  469. except ImportError:
  470. pass
  471. else:
  472. skip('This test requires an intepreter without threads')
  473. import sys
  474. def f():
  475. return sys._current_frames()
  476. frames = f()
  477. assert frames.keys() == [0]
  478. assert frames[0].f_code.co_name in ('f', '?')
  479. class AppTestCurrentFramesWithThread(AppTestCurrentFrames):
  480. spaceconfig = {
  481. "usemodules": ["rctime", "thread"],
  482. }
  483. def test_current_frames(self):
  484. import sys
  485. import time
  486. import thread
  487. # XXX workaround for now: to prevent deadlocks, call
  488. # sys._current_frames() once before starting threads.
  489. # This is an issue in non-translated versions only.
  490. sys._current_frames()
  491. thread_id = thread.get_ident()
  492. def other_thread():
  493. print "thread started"
  494. lock2.release()
  495. lock1.acquire()
  496. lock1 = thread.allocate_lock()
  497. lock2 = thread.allocate_lock()
  498. lock1.acquire()
  499. lock2.acquire()
  500. thread.start_new_thread(other_thread, ())
  501. def f():
  502. lock2.acquire()
  503. return sys._current_frames()
  504. frames = f()
  505. lock1.release()
  506. thisframe = frames.pop(thread_id)
  507. assert thisframe.f_code.co_name in ('f', '?')
  508. assert len(frames) == 1
  509. _, other_frame = frames.popitem()
  510. assert other_frame.f_code.co_name in ('other_thread', '?')
  511. class AppTestSysExcInfoDirect:
  512. def setup_method(self, meth):
  513. self.checking = not self.runappdirect
  514. if self.checking:
  515. self.seen = []
  516. from pypy.module.sys import vm
  517. def exc_info_with_tb(*args):
  518. self.seen.append("n") # not optimized
  519. return self.old[0](*args)
  520. def exc_info_without_tb(*args):
  521. self.seen.append("y") # optimized
  522. return self.old[1](*args)
  523. self.old = [vm.exc_info_with_tb, vm.exc_info_without_tb]
  524. vm.exc_info_with_tb = exc_info_with_tb
  525. vm.exc_info_without_tb = exc_info_without_tb
  526. #
  527. from rpython.rlib import jit
  528. self.old2 = [jit.we_are_jitted]
  529. jit.we_are_jitted = lambda: True
  530. def teardown_method(self, meth):
  531. if self.checking:
  532. from pypy.module.sys import vm
  533. from rpython.rlib import jit
  534. vm.exc_info_with_tb = self.old[0]
  535. vm.exc_info_without_tb = self.old[1]
  536. jit.we_are_jitted = self.old2[0]
  537. #
  538. assert ''.join(self.seen) == meth.expected
  539. def test_returns_none(self):
  540. import sys
  541. assert sys.exc_info() == (None, None, None)
  542. assert sys.exc_info()[0] is None
  543. assert sys.exc_info()[1] is None
  544. assert sys.exc_info()[2] is None
  545. assert sys.exc_info()[:2] == (None, None)
  546. assert sys.exc_info()[:3] == (None, None, None)
  547. assert sys.exc_info()[0:2] == (None, None)
  548. assert sys.exc_info()[2:4] == (None,)
  549. test_returns_none.expected = 'nnnnnnnn'
  550. def test_returns_subscr(self):
  551. import sys
  552. e = KeyError("boom")
  553. try:
  554. raise e
  555. except:
  556. assert sys.exc_info()[0] is KeyError # y
  557. assert sys.exc_info()[1] is e # y
  558. assert sys.exc_info()[2] is not None # n
  559. assert sys.exc_info()[-3] is KeyError # y
  560. assert sys.exc_info()[-2] is e # y
  561. assert sys.exc_info()[-1] is not None # n
  562. test_returns_subscr.expected = 'yynyyn'
  563. def test_returns_slice_2(self):
  564. import sys
  565. e = KeyError("boom")
  566. try:
  567. raise e
  568. except:
  569. foo = sys.exc_info() # n
  570. assert sys.exc_info()[:0] == () # y
  571. assert sys.exc_info()[:1] == foo[:1] # y
  572. assert sys.exc_info()[:2] == foo[:2] # y
  573. assert sys.exc_info()[:3] == foo # n
  574. assert sys.exc_info()[:4] == foo # n
  575. assert sys.exc_info()[:-1] == foo[:2] # y
  576. assert sys.exc_info()[:-2] == foo[:1] # y
  577. assert sys.exc_info()[:-3] == () # y
  578. test_returns_slice_2.expected = 'nyyynnyyy'
  579. def test_returns_slice_3(self):
  580. import sys
  581. e = KeyError("boom")
  582. try:
  583. raise e
  584. except:
  585. foo = sys.exc_info() # n
  586. assert sys.exc_info()[2:2] == () # y
  587. assert sys.exc_info()[0:1] == foo[:1] # y
  588. assert sys.exc_info()[1:2] == foo[1:2] # y
  589. assert sys.exc_info()[0:3] == foo # n
  590. assert sys.exc_info()[2:4] == foo[2:] # n
  591. assert sys.exc_info()[0:-1] == foo[:2] # y
  592. assert sys.exc_info()[0:-2] == foo[:1] # y
  593. assert sys.exc_info()[5:-3] == () # y
  594. test_returns_slice_3.expected = 'nyyynnyyy'
  595. def test_strange_invocation(self):
  596. import sys
  597. e = KeyError("boom")
  598. try:
  599. raise e
  600. except:
  601. a = []; k = {}
  602. assert sys.exc_info(*a)[:0] == ()
  603. assert sys.exc_info(**k)[:0] == ()
  604. test_strange_invocation.expected = 'nn'
  605. def test_call_in_subfunction(self):
  606. import sys
  607. def g():
  608. # this case is not optimized, because we need to search the
  609. # frame chain. it's probably not worth the complications
  610. return sys.exc_info()[1]
  611. e = KeyError("boom")
  612. try:
  613. raise e
  614. except:
  615. assert g() is e
  616. test_call_in_subfunction.expected = 'n'
  617. class AppTestSysExcInfoDirectCallMethod(AppTestSysExcInfoDirect):
  618. spaceconfig = {"objspace.opcodes.CALL_METHOD": True}