test_libcython_in_gdb.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. """
  2. Tests that run inside GDB.
  3. Note: debug information is already imported by the file generated by
  4. Cython.Debugger.Cygdb.make_command_file()
  5. """
  6. from __future__ import absolute_import
  7. import os
  8. import re
  9. import sys
  10. import trace
  11. import inspect
  12. import warnings
  13. import unittest
  14. import textwrap
  15. import tempfile
  16. import functools
  17. import traceback
  18. import itertools
  19. #from test import test_support
  20. import gdb
  21. from .. import libcython
  22. from .. import libpython
  23. from . import TestLibCython as test_libcython
  24. from ...Utils import add_metaclass
  25. # for some reason sys.argv is missing in gdb
  26. sys.argv = ['gdb']
  27. def print_on_call_decorator(func):
  28. @functools.wraps(func)
  29. def wrapper(self, *args, **kwargs):
  30. _debug(type(self).__name__, func.__name__)
  31. try:
  32. return func(self, *args, **kwargs)
  33. except Exception:
  34. _debug("An exception occurred:", traceback.format_exc())
  35. raise
  36. return wrapper
  37. class TraceMethodCallMeta(type):
  38. def __init__(self, name, bases, dict):
  39. for func_name, func in dict.items():
  40. if inspect.isfunction(func):
  41. setattr(self, func_name, print_on_call_decorator(func))
  42. @add_metaclass(TraceMethodCallMeta)
  43. class DebugTestCase(unittest.TestCase):
  44. """
  45. Base class for test cases. On teardown it kills the inferior and unsets
  46. all breakpoints.
  47. """
  48. def __init__(self, name):
  49. super(DebugTestCase, self).__init__(name)
  50. self.cy = libcython.cy
  51. self.module = libcython.cy.cython_namespace['codefile']
  52. self.spam_func, self.spam_meth = libcython.cy.functions_by_name['spam']
  53. self.ham_func = libcython.cy.functions_by_qualified_name[
  54. 'codefile.ham']
  55. self.eggs_func = libcython.cy.functions_by_qualified_name[
  56. 'codefile.eggs']
  57. def read_var(self, varname, cast_to=None):
  58. result = gdb.parse_and_eval('$cy_cvalue("%s")' % varname)
  59. if cast_to:
  60. result = cast_to(result)
  61. return result
  62. def local_info(self):
  63. return gdb.execute('info locals', to_string=True)
  64. def lineno_equals(self, source_line=None, lineno=None):
  65. if source_line is not None:
  66. lineno = test_libcython.source_to_lineno[source_line]
  67. frame = gdb.selected_frame()
  68. self.assertEqual(libcython.cython_info.lineno(frame), lineno)
  69. def break_and_run(self, source_line):
  70. break_lineno = test_libcython.source_to_lineno[source_line]
  71. gdb.execute('cy break codefile:%d' % break_lineno, to_string=True)
  72. gdb.execute('run', to_string=True)
  73. def tearDown(self):
  74. gdb.execute('delete breakpoints', to_string=True)
  75. try:
  76. gdb.execute('kill inferior 1', to_string=True)
  77. except RuntimeError:
  78. pass
  79. gdb.execute('set args -c "import codefile"')
  80. class TestDebugInformationClasses(DebugTestCase):
  81. def test_CythonModule(self):
  82. "test that debug information was parsed properly into data structures"
  83. self.assertEqual(self.module.name, 'codefile')
  84. global_vars = ('c_var', 'python_var', '__name__',
  85. '__builtins__', '__doc__', '__file__')
  86. assert set(global_vars).issubset(self.module.globals)
  87. def test_CythonVariable(self):
  88. module_globals = self.module.globals
  89. c_var = module_globals['c_var']
  90. python_var = module_globals['python_var']
  91. self.assertEqual(c_var.type, libcython.CObject)
  92. self.assertEqual(python_var.type, libcython.PythonObject)
  93. self.assertEqual(c_var.qualified_name, 'codefile.c_var')
  94. def test_CythonFunction(self):
  95. self.assertEqual(self.spam_func.qualified_name, 'codefile.spam')
  96. self.assertEqual(self.spam_meth.qualified_name,
  97. 'codefile.SomeClass.spam')
  98. self.assertEqual(self.spam_func.module, self.module)
  99. assert self.eggs_func.pf_cname, (self.eggs_func, self.eggs_func.pf_cname)
  100. assert not self.ham_func.pf_cname
  101. assert not self.spam_func.pf_cname
  102. assert not self.spam_meth.pf_cname
  103. self.assertEqual(self.spam_func.type, libcython.CObject)
  104. self.assertEqual(self.ham_func.type, libcython.CObject)
  105. self.assertEqual(self.spam_func.arguments, ['a'])
  106. self.assertEqual(self.spam_func.step_into_functions,
  107. set(['puts', 'some_c_function']))
  108. expected_lineno = test_libcython.source_to_lineno['def spam(a=0):']
  109. self.assertEqual(self.spam_func.lineno, expected_lineno)
  110. self.assertEqual(sorted(self.spam_func.locals), list('abcd'))
  111. class TestParameters(unittest.TestCase):
  112. def test_parameters(self):
  113. gdb.execute('set cy_colorize_code on')
  114. assert libcython.parameters.colorize_code
  115. gdb.execute('set cy_colorize_code off')
  116. assert not libcython.parameters.colorize_code
  117. class TestBreak(DebugTestCase):
  118. def test_break(self):
  119. breakpoint_amount = len(gdb.breakpoints() or ())
  120. gdb.execute('cy break codefile.spam')
  121. self.assertEqual(len(gdb.breakpoints()), breakpoint_amount + 1)
  122. bp = gdb.breakpoints()[-1]
  123. self.assertEqual(bp.type, gdb.BP_BREAKPOINT)
  124. assert self.spam_func.cname in bp.location
  125. assert bp.enabled
  126. def test_python_break(self):
  127. gdb.execute('cy break -p join')
  128. assert 'def join(' in gdb.execute('cy run', to_string=True)
  129. def test_break_lineno(self):
  130. beginline = 'import os'
  131. nextline = 'cdef int c_var = 12'
  132. self.break_and_run(beginline)
  133. self.lineno_equals(beginline)
  134. step_result = gdb.execute('cy step', to_string=True)
  135. self.lineno_equals(nextline)
  136. assert step_result.rstrip().endswith(nextline)
  137. class TestKilled(DebugTestCase):
  138. def test_abort(self):
  139. gdb.execute("set args -c 'import os; os.abort()'")
  140. output = gdb.execute('cy run', to_string=True)
  141. assert 'abort' in output.lower()
  142. class DebugStepperTestCase(DebugTestCase):
  143. def step(self, varnames_and_values, source_line=None, lineno=None):
  144. gdb.execute(self.command)
  145. for varname, value in varnames_and_values:
  146. self.assertEqual(self.read_var(varname), value, self.local_info())
  147. self.lineno_equals(source_line, lineno)
  148. class TestStep(DebugStepperTestCase):
  149. """
  150. Test stepping. Stepping happens in the code found in
  151. Cython/Debugger/Tests/codefile.
  152. """
  153. def test_cython_step(self):
  154. gdb.execute('cy break codefile.spam')
  155. gdb.execute('run', to_string=True)
  156. self.lineno_equals('def spam(a=0):')
  157. gdb.execute('cy step', to_string=True)
  158. self.lineno_equals('b = c = d = 0')
  159. self.command = 'cy step'
  160. self.step([('b', 0)], source_line='b = 1')
  161. self.step([('b', 1), ('c', 0)], source_line='c = 2')
  162. self.step([('c', 2)], source_line='int(10)')
  163. self.step([], source_line='puts("spam")')
  164. gdb.execute('cont', to_string=True)
  165. self.assertEqual(len(gdb.inferiors()), 1)
  166. self.assertEqual(gdb.inferiors()[0].pid, 0)
  167. def test_c_step(self):
  168. self.break_and_run('some_c_function()')
  169. gdb.execute('cy step', to_string=True)
  170. self.assertEqual(gdb.selected_frame().name(), 'some_c_function')
  171. def test_python_step(self):
  172. self.break_and_run('os.path.join("foo", "bar")')
  173. result = gdb.execute('cy step', to_string=True)
  174. curframe = gdb.selected_frame()
  175. self.assertEqual(curframe.name(), 'PyEval_EvalFrameEx')
  176. pyframe = libpython.Frame(curframe).get_pyop()
  177. # With Python 3 inferiors, pyframe.co_name will return a PyUnicodePtr,
  178. # be compatible
  179. frame_name = pyframe.co_name.proxyval(set())
  180. self.assertEqual(frame_name, 'join')
  181. assert re.match(r'\d+ def join\(', result), result
  182. class TestNext(DebugStepperTestCase):
  183. def test_cython_next(self):
  184. self.break_and_run('c = 2')
  185. lines = (
  186. 'int(10)',
  187. 'puts("spam")',
  188. 'os.path.join("foo", "bar")',
  189. 'some_c_function()',
  190. )
  191. for line in lines:
  192. gdb.execute('cy next')
  193. self.lineno_equals(line)
  194. class TestLocalsGlobals(DebugTestCase):
  195. def test_locals(self):
  196. self.break_and_run('int(10)')
  197. result = gdb.execute('cy locals', to_string=True)
  198. assert 'a = 0', repr(result)
  199. assert 'b = (int) 1', result
  200. assert 'c = (int) 2' in result, repr(result)
  201. def test_globals(self):
  202. self.break_and_run('int(10)')
  203. result = gdb.execute('cy globals', to_string=True)
  204. assert '__name__ ' in result, repr(result)
  205. assert '__doc__ ' in result, repr(result)
  206. assert 'os ' in result, repr(result)
  207. assert 'c_var ' in result, repr(result)
  208. assert 'python_var ' in result, repr(result)
  209. class TestBacktrace(DebugTestCase):
  210. def test_backtrace(self):
  211. libcython.parameters.colorize_code.value = False
  212. self.break_and_run('os.path.join("foo", "bar")')
  213. def match_backtrace_output(result):
  214. assert re.search(r'\#\d+ *0x.* in spam\(\) at .*codefile\.pyx:22',
  215. result), result
  216. assert 'os.path.join("foo", "bar")' in result, result
  217. result = gdb.execute('cy bt', to_string=True)
  218. match_backtrace_output(result)
  219. result = gdb.execute('cy bt -a', to_string=True)
  220. match_backtrace_output(result)
  221. # Apparently not everyone has main()
  222. # assert re.search(r'\#0 *0x.* in main\(\)', result), result
  223. class TestFunctions(DebugTestCase):
  224. def test_functions(self):
  225. self.break_and_run('c = 2')
  226. result = gdb.execute('print $cy_cname("b")', to_string=True)
  227. assert re.search('__pyx_.*b', result), result
  228. result = gdb.execute('print $cy_lineno()', to_string=True)
  229. supposed_lineno = test_libcython.source_to_lineno['c = 2']
  230. assert str(supposed_lineno) in result, (supposed_lineno, result)
  231. result = gdb.execute('print $cy_cvalue("b")', to_string=True)
  232. assert '= 1' in result
  233. class TestPrint(DebugTestCase):
  234. def test_print(self):
  235. self.break_and_run('c = 2')
  236. result = gdb.execute('cy print b', to_string=True)
  237. self.assertEqual('b = (int) 1\n', result)
  238. class TestUpDown(DebugTestCase):
  239. def test_updown(self):
  240. self.break_and_run('os.path.join("foo", "bar")')
  241. gdb.execute('cy step')
  242. self.assertRaises(RuntimeError, gdb.execute, 'cy down')
  243. result = gdb.execute('cy up', to_string=True)
  244. assert 'spam()' in result
  245. assert 'os.path.join("foo", "bar")' in result
  246. class TestExec(DebugTestCase):
  247. def setUp(self):
  248. super(TestExec, self).setUp()
  249. self.fd, self.tmpfilename = tempfile.mkstemp()
  250. self.tmpfile = os.fdopen(self.fd, 'r+')
  251. def tearDown(self):
  252. super(TestExec, self).tearDown()
  253. try:
  254. self.tmpfile.close()
  255. finally:
  256. os.remove(self.tmpfilename)
  257. def eval_command(self, command):
  258. gdb.execute('cy exec open(%r, "w").write(str(%s))' %
  259. (self.tmpfilename, command))
  260. return self.tmpfile.read().strip()
  261. def test_cython_exec(self):
  262. self.break_and_run('os.path.join("foo", "bar")')
  263. # test normal behaviour
  264. self.assertEqual("[0]", self.eval_command('[a]'))
  265. # test multiline code
  266. result = gdb.execute(textwrap.dedent('''\
  267. cy exec
  268. pass
  269. "nothing"
  270. end
  271. '''))
  272. result = self.tmpfile.read().rstrip()
  273. self.assertEqual('', result)
  274. def test_python_exec(self):
  275. self.break_and_run('os.path.join("foo", "bar")')
  276. gdb.execute('cy step')
  277. gdb.execute('cy exec some_random_var = 14')
  278. self.assertEqual('14', self.eval_command('some_random_var'))
  279. class CySet(DebugTestCase):
  280. def test_cyset(self):
  281. self.break_and_run('os.path.join("foo", "bar")')
  282. gdb.execute('cy set a = $cy_eval("{None: []}")')
  283. stringvalue = self.read_var("a", cast_to=str)
  284. self.assertEqual(stringvalue, "{None: []}")
  285. class TestCyEval(DebugTestCase):
  286. "Test the $cy_eval() gdb function."
  287. def test_cy_eval(self):
  288. # This function leaks a few objects in the GDB python process. This
  289. # is no biggie
  290. self.break_and_run('os.path.join("foo", "bar")')
  291. result = gdb.execute('print $cy_eval("None")', to_string=True)
  292. assert re.match(r'\$\d+ = None\n', result), result
  293. result = gdb.execute('print $cy_eval("[a]")', to_string=True)
  294. assert re.match(r'\$\d+ = \[0\]', result), result
  295. class TestClosure(DebugTestCase):
  296. def break_and_run_func(self, funcname):
  297. gdb.execute('cy break ' + funcname)
  298. gdb.execute('cy run')
  299. def test_inner(self):
  300. self.break_and_run_func('inner')
  301. self.assertEqual('', gdb.execute('cy locals', to_string=True))
  302. # Allow the Cython-generated code to initialize the scope variable
  303. gdb.execute('cy step')
  304. self.assertEqual(str(self.read_var('a')), "'an object'")
  305. print_result = gdb.execute('cy print a', to_string=True).strip()
  306. self.assertEqual(print_result, "a = 'an object'")
  307. def test_outer(self):
  308. self.break_and_run_func('outer')
  309. self.assertEqual('', gdb.execute('cy locals', to_string=True))
  310. # Initialize scope with 'a' uninitialized
  311. gdb.execute('cy step')
  312. self.assertEqual('', gdb.execute('cy locals', to_string=True))
  313. # Initialize 'a' to 1
  314. gdb.execute('cy step')
  315. print_result = gdb.execute('cy print a', to_string=True).strip()
  316. self.assertEqual(print_result, "a = 'an object'")
  317. _do_debug = os.environ.get('GDB_DEBUG')
  318. if _do_debug:
  319. _debug_file = open('/dev/tty', 'w')
  320. def _debug(*messages):
  321. if _do_debug:
  322. messages = itertools.chain([sys._getframe(1).f_code.co_name, ':'],
  323. messages)
  324. _debug_file.write(' '.join(str(msg) for msg in messages) + '\n')
  325. def run_unittest_in_module(modulename):
  326. try:
  327. gdb.lookup_type('PyModuleObject')
  328. except RuntimeError:
  329. msg = ("Unable to run tests, Python was not compiled with "
  330. "debugging information. Either compile python with "
  331. "-g or get a debug build (configure with --with-pydebug).")
  332. warnings.warn(msg)
  333. os._exit(1)
  334. else:
  335. m = __import__(modulename, fromlist=[''])
  336. tests = inspect.getmembers(m, inspect.isclass)
  337. # test_support.run_unittest(tests)
  338. test_loader = unittest.TestLoader()
  339. suite = unittest.TestSuite(
  340. [test_loader.loadTestsFromTestCase(cls) for name, cls in tests])
  341. result = unittest.TextTestRunner(verbosity=1).run(suite)
  342. return result.wasSuccessful()
  343. def runtests():
  344. """
  345. Run the libcython and libpython tests. Ensure that an appropriate status is
  346. returned to the parent test process.
  347. """
  348. from Cython.Debugger.Tests import test_libpython_in_gdb
  349. success_libcython = run_unittest_in_module(__name__)
  350. success_libpython = run_unittest_in_module(test_libpython_in_gdb.__name__)
  351. if not success_libcython or not success_libpython:
  352. sys.exit(2)
  353. def main(version, trace_code=False):
  354. global inferior_python_version
  355. inferior_python_version = version
  356. if trace_code:
  357. tracer = trace.Trace(count=False, trace=True, outfile=sys.stderr,
  358. ignoredirs=[sys.prefix, sys.exec_prefix])
  359. tracer.runfunc(runtests)
  360. else:
  361. runtests()