aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/tools/cython/Cython/Debugger/Tests/test_libcython_in_gdb.py
blob: bd7608d6079412d47d32fd539d0d7797ce106784 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
"""
Tests that run inside GDB.

Note: debug information is already imported by the file generated by
Cython.Debugger.Cygdb.make_command_file()
"""

from __future__ import absolute_import

import os
import re
import sys
import trace
import inspect
import warnings
import unittest
import textwrap
import tempfile
import functools
import traceback
import itertools
#from test import test_support

import gdb

from .. import libcython
from .. import libpython
from . import TestLibCython as test_libcython
from ...Utils import add_metaclass

# for some reason sys.argv is missing in gdb
sys.argv = ['gdb']


def print_on_call_decorator(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        _debug(type(self).__name__, func.__name__)

        try:
            return func(self, *args, **kwargs)
        except Exception:
            _debug("An exception occurred:", traceback.format_exc())
            raise

    return wrapper

class TraceMethodCallMeta(type):

    def __init__(self, name, bases, dict):
        for func_name, func in dict.items():
            if inspect.isfunction(func):
                setattr(self, func_name, print_on_call_decorator(func))


@add_metaclass(TraceMethodCallMeta)
class DebugTestCase(unittest.TestCase):
    """
    Base class for test cases. On teardown it kills the inferior and unsets
    all breakpoints.
    """

    def __init__(self, name):
        super(DebugTestCase, self).__init__(name)
        self.cy = libcython.cy
        self.module = libcython.cy.cython_namespace['codefile']
        self.spam_func, self.spam_meth = libcython.cy.functions_by_name['spam']
        self.ham_func = libcython.cy.functions_by_qualified_name[
            'codefile.ham']
        self.eggs_func = libcython.cy.functions_by_qualified_name[
            'codefile.eggs']

    def read_var(self, varname, cast_to=None):
        result = gdb.parse_and_eval('$cy_cvalue("%s")' % varname)
        if cast_to:
            result = cast_to(result)

        return result

    def local_info(self):
        return gdb.execute('info locals', to_string=True)

    def lineno_equals(self, source_line=None, lineno=None):
        if source_line is not None:
            lineno = test_libcython.source_to_lineno[source_line]
        frame = gdb.selected_frame()
        self.assertEqual(libcython.cython_info.lineno(frame), lineno)

    def break_and_run(self, source_line):
        break_lineno = test_libcython.source_to_lineno[source_line]
        gdb.execute('cy break codefile:%d' % break_lineno, to_string=True)
        gdb.execute('run', to_string=True)

    def tearDown(self):
        gdb.execute('delete breakpoints', to_string=True)
        try:
            gdb.execute('kill inferior 1', to_string=True)
        except RuntimeError:
            pass

        gdb.execute('set args -c "import codefile"')


class TestDebugInformationClasses(DebugTestCase):

    def test_CythonModule(self):
        "test that debug information was parsed properly into data structures"
        self.assertEqual(self.module.name, 'codefile')
        global_vars = ('c_var', 'python_var', '__name__',
                       '__builtins__', '__doc__', '__file__')
        assert set(global_vars).issubset(self.module.globals)

    def test_CythonVariable(self):
        module_globals = self.module.globals
        c_var = module_globals['c_var']
        python_var = module_globals['python_var']
        self.assertEqual(c_var.type, libcython.CObject)
        self.assertEqual(python_var.type, libcython.PythonObject)
        self.assertEqual(c_var.qualified_name, 'codefile.c_var')

    def test_CythonFunction(self):
        self.assertEqual(self.spam_func.qualified_name, 'codefile.spam')
        self.assertEqual(self.spam_meth.qualified_name,
                         'codefile.SomeClass.spam')
        self.assertEqual(self.spam_func.module, self.module)

        assert self.eggs_func.pf_cname, (self.eggs_func, self.eggs_func.pf_cname)
        assert not self.ham_func.pf_cname
        assert not self.spam_func.pf_cname
        assert not self.spam_meth.pf_cname

        self.assertEqual(self.spam_func.type, libcython.CObject)
        self.assertEqual(self.ham_func.type, libcython.CObject)

        self.assertEqual(self.spam_func.arguments, ['a'])
        self.assertEqual(self.spam_func.step_into_functions,
                         set(['puts', 'some_c_function']))

        expected_lineno = test_libcython.source_to_lineno['def spam(a=0):']
        self.assertEqual(self.spam_func.lineno, expected_lineno)
        self.assertEqual(sorted(self.spam_func.locals), list('abcd'))


class TestParameters(unittest.TestCase):

    def test_parameters(self):
        gdb.execute('set cy_colorize_code on')
        assert libcython.parameters.colorize_code
        gdb.execute('set cy_colorize_code off')
        assert not libcython.parameters.colorize_code


class TestBreak(DebugTestCase):

    def test_break(self):
        breakpoint_amount = len(gdb.breakpoints() or ())
        gdb.execute('cy break codefile.spam')

        self.assertEqual(len(gdb.breakpoints()), breakpoint_amount + 1)
        bp = gdb.breakpoints()[-1]
        self.assertEqual(bp.type, gdb.BP_BREAKPOINT)
        assert self.spam_func.cname in bp.location
        assert bp.enabled

    def test_python_break(self):
        gdb.execute('cy break -p join')
        assert 'def join(' in gdb.execute('cy run', to_string=True)

    def test_break_lineno(self):
        beginline = 'import os'
        nextline = 'cdef int c_var = 12'

        self.break_and_run(beginline)
        self.lineno_equals(beginline)
        step_result = gdb.execute('cy step', to_string=True)
        self.lineno_equals(nextline)
        assert step_result.rstrip().endswith(nextline)


class TestKilled(DebugTestCase):

    def test_abort(self):
        gdb.execute("set args -c 'import os; os.abort()'")
        output = gdb.execute('cy run', to_string=True)
        assert 'abort' in output.lower()


class DebugStepperTestCase(DebugTestCase):

    def step(self, varnames_and_values, source_line=None, lineno=None):
        gdb.execute(self.command)
        for varname, value in varnames_and_values:
            self.assertEqual(self.read_var(varname), value, self.local_info())

        self.lineno_equals(source_line, lineno)


class TestStep(DebugStepperTestCase):
    """
    Test stepping. Stepping happens in the code found in
    Cython/Debugger/Tests/codefile.
    """

    def test_cython_step(self):
        gdb.execute('cy break codefile.spam')

        gdb.execute('run', to_string=True)
        self.lineno_equals('def spam(a=0):')

        gdb.execute('cy step', to_string=True)
        self.lineno_equals('b = c = d = 0')

        self.command = 'cy step'
        self.step([('b', 0)], source_line='b = 1')
        self.step([('b', 1), ('c', 0)], source_line='c = 2')
        self.step([('c', 2)], source_line='int(10)')
        self.step([], source_line='puts("spam")')

        gdb.execute('cont', to_string=True)
        self.assertEqual(len(gdb.inferiors()), 1)
        self.assertEqual(gdb.inferiors()[0].pid, 0)

    def test_c_step(self):
        self.break_and_run('some_c_function()')
        gdb.execute('cy step', to_string=True)
        self.assertEqual(gdb.selected_frame().name(), 'some_c_function')

    def test_python_step(self):
        self.break_and_run('os.path.join("foo", "bar")')

        result = gdb.execute('cy step', to_string=True)

        curframe = gdb.selected_frame()
        self.assertEqual(curframe.name(), 'PyEval_EvalFrameEx')

        pyframe = libpython.Frame(curframe).get_pyop()
        # With Python 3 inferiors, pyframe.co_name will return a PyUnicodePtr,
        # be compatible
        frame_name = pyframe.co_name.proxyval(set())
        self.assertEqual(frame_name, 'join')
        assert re.match(r'\d+    def join\(', result), result


class TestNext(DebugStepperTestCase):

    def test_cython_next(self):
        self.break_and_run('c = 2')

        lines = (
            'int(10)',
            'puts("spam")',
            'os.path.join("foo", "bar")',
            'some_c_function()',
        )

        for line in lines:
            gdb.execute('cy next')
            self.lineno_equals(line)


class TestLocalsGlobals(DebugTestCase):

    def test_locals(self):
        self.break_and_run('int(10)')

        result = gdb.execute('cy locals', to_string=True)
        assert 'a = 0', repr(result)
        assert 'b = (int) 1', result
        assert 'c = (int) 2' in result, repr(result)

    def test_globals(self):
        self.break_and_run('int(10)')

        result = gdb.execute('cy globals', to_string=True)
        assert '__name__ ' in result, repr(result)
        assert '__doc__ ' in result, repr(result)
        assert 'os ' in result, repr(result)
        assert 'c_var ' in result, repr(result)
        assert 'python_var ' in result, repr(result)


class TestBacktrace(DebugTestCase):

    def test_backtrace(self):
        libcython.parameters.colorize_code.value = False

        self.break_and_run('os.path.join("foo", "bar")')

        def match_backtrace_output(result):
            assert re.search(r'\#\d+ *0x.* in spam\(\) at .*codefile\.pyx:22',
                             result), result
            assert 'os.path.join("foo", "bar")' in result, result

        result = gdb.execute('cy bt', to_string=True)
        match_backtrace_output(result)

        result = gdb.execute('cy bt -a', to_string=True)
        match_backtrace_output(result)

        # Apparently not everyone has main()
        # assert re.search(r'\#0 *0x.* in main\(\)', result), result


class TestFunctions(DebugTestCase):

    def test_functions(self):
        self.break_and_run('c = 2')
        result = gdb.execute('print $cy_cname("b")', to_string=True)
        assert re.search('__pyx_.*b', result), result

        result = gdb.execute('print $cy_lineno()', to_string=True)
        supposed_lineno = test_libcython.source_to_lineno['c = 2']
        assert str(supposed_lineno) in result, (supposed_lineno, result)

        result = gdb.execute('print $cy_cvalue("b")', to_string=True)
        assert '= 1' in result


class TestPrint(DebugTestCase):

    def test_print(self):
        self.break_and_run('c = 2')
        result = gdb.execute('cy print b', to_string=True)
        self.assertEqual('b = (int) 1\n', result)


class TestUpDown(DebugTestCase):

    def test_updown(self):
        self.break_and_run('os.path.join("foo", "bar")')
        gdb.execute('cy step')
        self.assertRaises(RuntimeError, gdb.execute, 'cy down')

        result = gdb.execute('cy up', to_string=True)
        assert 'spam()' in result
        assert 'os.path.join("foo", "bar")' in result


class TestExec(DebugTestCase):

    def setUp(self):
        super(TestExec, self).setUp()
        self.fd, self.tmpfilename = tempfile.mkstemp()
        self.tmpfile = os.fdopen(self.fd, 'r+')

    def tearDown(self):
        super(TestExec, self).tearDown()

        try:
            self.tmpfile.close()
        finally:
            os.remove(self.tmpfilename)

    def eval_command(self, command):
        gdb.execute('cy exec open(%r, "w").write(str(%s))' %
                                                (self.tmpfilename, command))
        return self.tmpfile.read().strip()

    def test_cython_exec(self):
        self.break_and_run('os.path.join("foo", "bar")')

        # test normal behaviour
        self.assertEqual("[0]", self.eval_command('[a]'))

        # test multiline code
        result = gdb.execute(textwrap.dedent('''\
            cy exec
            pass

            "nothing"
            end
            '''))
        result = self.tmpfile.read().rstrip()
        self.assertEqual('', result)

    def test_python_exec(self):
        self.break_and_run('os.path.join("foo", "bar")')
        gdb.execute('cy step')

        gdb.execute('cy exec some_random_var = 14')
        self.assertEqual('14', self.eval_command('some_random_var'))


class CySet(DebugTestCase):

    def test_cyset(self):
        self.break_and_run('os.path.join("foo", "bar")')

        gdb.execute('cy set a = $cy_eval("{None: []}")')
        stringvalue = self.read_var("a", cast_to=str)
        self.assertEqual(stringvalue, "{None: []}")


class TestCyEval(DebugTestCase):
    "Test the $cy_eval() gdb function."

    def test_cy_eval(self):
        # This function leaks a few objects in the GDB python process. This
        # is no biggie
        self.break_and_run('os.path.join("foo", "bar")')

        result = gdb.execute('print $cy_eval("None")', to_string=True)
        assert re.match(r'\$\d+ = None\n', result), result

        result = gdb.execute('print $cy_eval("[a]")', to_string=True)
        assert re.match(r'\$\d+ = \[0\]', result), result


class TestClosure(DebugTestCase):

    def break_and_run_func(self, funcname):
        gdb.execute('cy break ' + funcname)
        gdb.execute('cy run')

    def test_inner(self):
        self.break_and_run_func('inner')
        self.assertEqual('', gdb.execute('cy locals', to_string=True))

        # Allow the Cython-generated code to initialize the scope variable
        gdb.execute('cy step')

        self.assertEqual(str(self.read_var('a')), "'an object'")
        print_result = gdb.execute('cy print a', to_string=True).strip()
        self.assertEqual(print_result, "a = 'an object'")

    def test_outer(self):
        self.break_and_run_func('outer')
        self.assertEqual('', gdb.execute('cy locals', to_string=True))

        # Initialize scope with 'a' uninitialized
        gdb.execute('cy step')
        self.assertEqual('', gdb.execute('cy locals', to_string=True))

        # Initialize 'a' to 1
        gdb.execute('cy step')
        print_result = gdb.execute('cy print a', to_string=True).strip()
        self.assertEqual(print_result, "a = 'an object'")


_do_debug = os.environ.get('GDB_DEBUG')
if _do_debug:
    _debug_file = open('/dev/tty', 'w')

def _debug(*messages):
    if _do_debug:
        messages = itertools.chain([sys._getframe(1).f_code.co_name, ':'],
                                   messages)
        _debug_file.write(' '.join(str(msg) for msg in messages) + '\n')


def run_unittest_in_module(modulename):
    try:
        gdb.lookup_type('PyModuleObject')
    except RuntimeError:
        msg = ("Unable to run tests, Python was not compiled with "
                "debugging information. Either compile python with "
                "-g or get a debug build (configure with --with-pydebug).")
        warnings.warn(msg)
        os._exit(1)
    else:
        m = __import__(modulename, fromlist=[''])
        tests = inspect.getmembers(m, inspect.isclass)

        # test_support.run_unittest(tests)

        test_loader = unittest.TestLoader()
        suite = unittest.TestSuite(
            [test_loader.loadTestsFromTestCase(cls) for name, cls in tests])

        result = unittest.TextTestRunner(verbosity=1).run(suite)
        return result.wasSuccessful()

def runtests():
    """
    Run the libcython and libpython tests. Ensure that an appropriate status is
    returned to the parent test process.
    """
    from Cython.Debugger.Tests import test_libpython_in_gdb

    success_libcython = run_unittest_in_module(__name__)
    success_libpython = run_unittest_in_module(test_libpython_in_gdb.__name__)

    if not success_libcython or not success_libpython:
        sys.exit(2)

def main(version, trace_code=False):
    global inferior_python_version

    inferior_python_version = version

    if trace_code:
        tracer = trace.Trace(count=False, trace=True, outfile=sys.stderr,
                            ignoredirs=[sys.prefix, sys.exec_prefix])
        tracer.runfunc(runtests)
    else:
        runtests()