PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/IronPython_2_6/Src/Tests/modules/system_related/sys_test.py

#
Python | 444 lines | 351 code | 58 blank | 35 comment | 21 complexity | d5985169555fecc944faf8560e3b73df MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0
  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Microsoft Public License. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Microsoft Public License, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Microsoft Public License.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. from iptest.assert_util import *
  16. # adding some negative test case coverage for the sys module; we currently don't implement
  17. # some methods---there is a CodePlex work item 1042 to track the real implementation of
  18. # these methods
  19. import sys
  20. @skip("win32")
  21. def test_dont_write_bytecode():
  22. AreEqual(sys.dont_write_bytecode, True)
  23. def test_getframe():
  24. # This test requires -X:FullFrames, run it in separate instance of IronPython.
  25. global testDelGetFrame
  26. if not testDelGetFrame:
  27. return
  28. _getframe = sys._getframe
  29. for val in [None, 0, 1L, str, False]:
  30. sys._getframe = val
  31. AreEqual(sys._getframe, val)
  32. del sys._getframe
  33. try:
  34. # try access again
  35. x = sys._getframe
  36. except AttributeError: pass
  37. else: raise AssertionError("Deletion of sys._getframe didn't take effect")
  38. try:
  39. # try deletion again
  40. del sys._getframe
  41. except AttributeError: pass
  42. else: raise AssertionError("Deletion of sys._getframe didn't take effect")
  43. # restore it back
  44. sys._getframe = _getframe
  45. def g():
  46. y = 42
  47. def f():
  48. x = sys._getframe(1)
  49. return x
  50. AreEqual(f().f_locals['y'], 42)
  51. Assert(f().f_builtins is f().f_globals['__builtins__'].__dict__)
  52. AreEqual(f().f_locals['y'], 42)
  53. AreEqual(f().f_exc_traceback, None)
  54. AreEqual(f().f_exc_type, None)
  55. AreEqual(f().f_restricted, False)
  56. AreEqual(f().f_trace, None)
  57. # replace __builtins__, func code should have the non-replaced value
  58. global __builtins__
  59. oldbuiltin = __builtins__
  60. try:
  61. __builtins__ = dict(__builtins__.__dict__)
  62. def f():
  63. x = sys._getframe(1)
  64. return x
  65. Assert(f().f_builtins is oldbuiltin.__dict__)
  66. finally:
  67. __builtins__ = oldbuiltin
  68. def f():
  69. x = sys._getframe()
  70. return x
  71. AreEqual(f().f_back.f_locals['y'], 42)
  72. def f():
  73. yield sys._getframe()
  74. frame = list(f())[0]
  75. if is_cli:
  76. # incompat, this works for us, but not CPython, not sure why.
  77. AreEqual(frame.f_back.f_locals['y'], 42)
  78. # call through a built-in function
  79. global gfres
  80. class x(object):
  81. def __cmp__(self, other):
  82. global gfres
  83. gfres = sys._getframe(1)
  84. return -1
  85. cmp(x(), x())
  86. AreEqual(gfres.f_locals['y'], 42)
  87. g()
  88. def f():
  89. x = 42
  90. def g():
  91. import sys
  92. AreEqual(sys._getframe(1).f_locals['x'], 42)
  93. g()
  94. yield 42
  95. list(f())
  96. class x:
  97. abc = sys._getframe(0)
  98. AreEqual(x.abc.f_locals['abc'], x.abc)
  99. class x:
  100. class y:
  101. abc = sys._getframe(1)
  102. abc = y.abc
  103. AreEqual(x.abc.f_locals['abc'], x.abc)
  104. for i in xrange(2):
  105. x = _getframe(0)
  106. y = _getframe(0)
  107. AreEqual(id(x), id(y))
  108. # odd func_code tests which require on _getframe
  109. global get_odd_code
  110. def get_odd_code():
  111. c = sys._getframe(1)
  112. return c.f_code
  113. def verify(code, is_defined):
  114. d = { 'get_odd_code' : get_odd_code }
  115. exec code in d
  116. AreEqual('defined' in d, is_defined)
  117. class x(object):
  118. abc = get_odd_code()
  119. defined = 42
  120. verify(x.abc, False)
  121. class x(object):
  122. abc = get_odd_code()
  123. global defined
  124. defined = 42
  125. if is_cli: # bug 20553 http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20553
  126. verify(x.abc, False)
  127. else:
  128. verify(x.abc, True)
  129. d = {'get_odd_code' : get_odd_code}
  130. exec 'defined=42\nabc = get_odd_code()\n' in d
  131. verify(d['abc'], True)
  132. # bug 24243, code objects should never be null
  133. class x(object):
  134. f = sys._getframe()
  135. while f:
  136. Assert(f.f_code is not None)
  137. Assert(f.f_code.co_name is not None)
  138. f = f.f_back
  139. # bug 24313, sys._getframe should return the same frame objects
  140. # that tracing functions receive
  141. def method():
  142. global method_id
  143. method_id = id(sys._getframe())
  144. def trace_dispatch(frame, event, arg):
  145. global found_id
  146. found_id = id(frame)
  147. sys.settrace(trace_dispatch)
  148. method()
  149. sys.settrace(None)
  150. AreEqual(method_id, found_id)
  151. # verify thread safety of sys.settrace
  152. import thread
  153. import time
  154. global done
  155. done = 0
  156. lock = thread.allocate_lock()
  157. def starter(events):
  158. def tracer(*args):
  159. events.append(args[1])
  160. return tracer
  161. def f1(): time.sleep(.25)
  162. def f2(): time.sleep(1)
  163. def f3(): time.sleep(.5)
  164. def test_thread():
  165. global done
  166. sys.settrace(tracer)
  167. f1()
  168. sys.settrace(None)
  169. f2()
  170. sys.settrace(tracer)
  171. f3()
  172. with lock: done += 1
  173. thread.start_new_thread(test_thread, ())
  174. lists = []
  175. for i in xrange(10):
  176. cur_list = []
  177. starter(cur_list)
  178. lists.append(cur_list)
  179. while done != 10:
  180. pass
  181. for i in xrange(1, 10):
  182. AreEqual(lists[i-1], lists[i])
  183. # verify we report <module> for top-level code
  184. frame = sys._getframe()
  185. outer_frame = frame.f_back
  186. while outer_frame is not None:
  187. frame = outer_frame
  188. outer_frame = frame.f_back
  189. AreEqual(frame.f_code.co_name, "<module>")
  190. @skip("win32")
  191. def test_api_version():
  192. # api_version
  193. AreEqual(sys.api_version, 0)
  194. @skip("silverlight")
  195. def test_settrace():
  196. """TODO: now that sys.settrace has been implemented this test case needs to be fully revisited"""
  197. # settrace
  198. Assert(hasattr(sys, 'settrace'))
  199. global traces
  200. traces = []
  201. def f(frame, kind, info):
  202. traces.append(('f', kind, frame.f_code.co_name))
  203. return g
  204. def g(frame, kind, info):
  205. traces.append(('g', kind, frame.f_code.co_name))
  206. return g_ret
  207. g_ret = g
  208. def x():
  209. abc = 'hello'
  210. abc = 'next'
  211. sys.settrace(f)
  212. x()
  213. sys.settrace(None)
  214. AreEqual(traces, [('f', 'call', 'x'), ('g', 'line', 'x'), ('g', 'line', 'x'), ('g', 'return', 'x')])
  215. traces = []
  216. g_ret = f
  217. sys.settrace(f)
  218. x()
  219. sys.settrace(None)
  220. AreEqual(traces, [('f', 'call', 'x'), ('g', 'line', 'x'), ('f', 'line', 'x'), ('g', 'return', 'x')])
  221. # verify globals/locals are correct on the frame
  222. global frameobj
  223. def f(frame, event, payload):
  224. global frameobj
  225. frameobj = frame
  226. def g(a):
  227. b = 42
  228. sys.settrace(f)
  229. g(32)
  230. sys.settrace(None)
  231. AreEqual(frameobj.f_locals, {'a': 32, 'b':42})
  232. Assert('test_getrefcount' in frameobj.f_globals)
  233. if is_cli:
  234. # -X:Tracing should enable tracing of top-level code
  235. import os
  236. content = """a = "aaa"
  237. import pdb; pdb.set_trace()
  238. b = "bbb"
  239. c = "ccc"
  240. final = a + b + c
  241. print final"""
  242. f = file('temp.py', 'w+')
  243. try:
  244. f.write(content)
  245. f.close()
  246. stdin, stdout = os.popen2(sys.executable + ' -X:Tracing -X:Frames temp.py')
  247. stdin.write('n\nn\nn\nn\nn\nn\nn\nn\n')
  248. stdin.flush()
  249. out = [x for x in stdout]
  250. Assert('-> b = "bbb"\n' in out)
  251. Assert('-> c = "ccc"\n' in out)
  252. Assert('-> final = a + b + c\n' in out)
  253. Assert('-> print final\n' in out)
  254. Assert('(Pdb) aaabbbccc\n' in out)
  255. Assert('--Return--\n' in out)
  256. Assert('-> print final\n' in out)
  257. Assert('(Pdb) ' in out)
  258. finally:
  259. nt.unlink('temp.py')
  260. @skip("win32")
  261. def test_getrefcount():
  262. # getrefcount
  263. Assert(not hasattr(sys, 'getrefcount'))
  264. @skip("win32 silverlight")
  265. def test_version():
  266. import re
  267. #E.g., 2.5.0 (IronPython 2.0 Alpha (2.0.0.800) on .NET 2.0.50727.1433)
  268. regex = "^\d\.\d\.\d \(IronPython \d\.\d(\.\d)? ((Alpha \d+ )|(Beta \d+ )|())((DEBUG )|()|(\d?))\(\d\.\d\.\d{1,8}\.\d{1,8}\) on \.NET \d(\.\d{1,5}){3}\)$"
  269. Assert(re.match(regex, sys.version) != None)
  270. def test_winver():
  271. import re
  272. #E.g., "2.5"
  273. Assert(re.match("^\d\.\d$", sys.winver) != None)
  274. def test_ps1():
  275. Assert(not hasattr(sys, "ps1"))
  276. def test_ps2():
  277. Assert(not hasattr(sys, "ps2"))
  278. @skip("silverlight")
  279. def test_getsizeof():
  280. '''TODO: revisit'''
  281. if is_cpython:
  282. Assert(sys.getsizeof(1)<sys.getsizeof(1.0))
  283. else:
  284. AreEqual(sys.getsizeof(1), sys.getsizeof(1.0))
  285. @skip("silverlight")
  286. def test_gettrace():
  287. '''TODO: revisit'''
  288. AreEqual(sys.gettrace(), None)
  289. def temp_func(*args, **kwargs):
  290. pass
  291. sys.settrace(temp_func)
  292. AreEqual(sys.gettrace(), temp_func)
  293. sys.settrace(None)
  294. AreEqual(sys.gettrace(), None)
  295. @skip("silverlight")
  296. def test_cp24242():
  297. # This test requires -X:FullFrames, run it in separate instance of IronPython.
  298. global testDelGetFrame
  299. if not testDelGetFrame:
  300. return
  301. frame = sys._getframe()
  302. ids = []
  303. while frame:
  304. ids.append(id(frame))
  305. frame = frame.f_back
  306. del frame
  307. force_gc()
  308. frame = sys._getframe()
  309. new_ids = []
  310. while frame:
  311. new_ids.append(id(frame))
  312. frame = frame.f_back
  313. del frame
  314. force_gc()
  315. AreEqual(ids, new_ids)
  316. CP24381_MESSAGES = []
  317. @skip("silverlight", "cli")
  318. def test_cp24381():
  319. import sys
  320. orig_sys_trace_func = sys.gettrace()
  321. def f(*args):
  322. global CP24381_MESSAGES
  323. CP24381_MESSAGES += args[1:]
  324. return f
  325. cp24381_file_name = r"cp24381.py"
  326. cp24381_contents = """
  327. print 'a'
  328. print 'b'
  329. print 'c'
  330. def f():
  331. print 'hi'
  332. f()
  333. """
  334. try:
  335. write_to_file(cp24381_file_name, cp24381_contents)
  336. sys.settrace(f)
  337. import cp24381
  338. finally:
  339. sys.settrace(orig_sys_trace_func)
  340. nt.unlink(cp24381_file_name)
  341. AreEqual(CP24381_MESSAGES,
  342. ['call', None, 'line', None, 'line', None, 'line', None, 'line',
  343. None, 'line', None, 'call', None, 'line', None, 'return', None,
  344. 'return', None])
  345. #--MAIN------------------------------------------------------------------------
  346. testDelGetFrame = "Test_GetFrame" in sys.argv
  347. if testDelGetFrame:
  348. print 'Calling test_getframe()...'
  349. test_getframe()
  350. print 'Calling test_cp24242()...'
  351. test_cp24242()
  352. else:
  353. run_test(__name__)
  354. # this is a destructive test, run it in separate instance of IronPython
  355. if not is_silverlight and sys.platform!="win32":
  356. from iptest.process_util import launch_ironpython_changing_extensions
  357. AreEqual(0, launch_ironpython_changing_extensions(__file__, ["-X:FullFrames"], [], ("Test_GetFrame",)))
  358. elif sys.platform == "win32":
  359. print 'running test_getframe on cpython'
  360. import subprocess
  361. subprocess.check_call([sys.executable, __file__, "Test_GetFrame"])