summaryrefslogtreecommitdiff
path: root/Cython/Debugger/Tests/TestLibCython.py
blob: b789b106235b8c196a31b18f20490b1cc1b82f3c (plain)
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

import os
import re
import sys
import shutil
import warnings
import textwrap
import unittest
import tempfile
import subprocess
#import distutils.core
#from distutils import sysconfig
from distutils import ccompiler

import runtests
import Cython.Distutils.extension
import Cython.Distutils.old_build_ext as build_ext
from Cython.Debugger import Cygdb as cygdb

root = os.path.dirname(os.path.abspath(__file__))
codefile = os.path.join(root, 'codefile')
cfuncs_file = os.path.join(root, 'cfuncs.c')

with open(codefile) as f:
    source_to_lineno = dict((line.strip(), i + 1) for i, line in enumerate(f))


have_gdb = None
def test_gdb():
    global have_gdb
    if have_gdb is not None:
        return have_gdb

    have_gdb = False
    try:
        p = subprocess.Popen(['gdb', '-nx', '--version'], stdout=subprocess.PIPE)
    except OSError:
        # gdb not found
        gdb_version = None
    else:
        stdout, _ = p.communicate()
        # Based on Lib/test/test_gdb.py
        regex = "GNU gdb [^\d]*(\d+)\.(\d+)"
        gdb_version = re.match(regex, stdout.decode('ascii', 'ignore'))

    if gdb_version:
        gdb_version_number = list(map(int, gdb_version.groups()))
        if gdb_version_number >= [7, 2]:
            have_gdb = True
            with tempfile.NamedTemporaryFile(mode='w+') as python_version_script:
                python_version_script.write(
                    'python import sys; print("%s %s" % sys.version_info[:2])')
                python_version_script.flush()
                p = subprocess.Popen(['gdb', '-batch', '-x', python_version_script.name],
                                     stdout=subprocess.PIPE)
                stdout, _ = p.communicate()
                try:
                    internal_python_version = list(map(int, stdout.decode('ascii', 'ignore').split()))
                    if internal_python_version < [2, 6]:
                        have_gdb = False
                except ValueError:
                    have_gdb = False

    if not have_gdb:
        warnings.warn('Skipping gdb tests, need gdb >= 7.2 with Python >= 2.6')

    return have_gdb


class DebuggerTestCase(unittest.TestCase):

    def setUp(self):
        """
        Run gdb and have cygdb import the debug information from the code
        defined in TestParseTreeTransforms's setUp method
        """
        if not test_gdb():
            return

        self.tempdir = tempfile.mkdtemp()
        self.destfile = os.path.join(self.tempdir, 'codefile.pyx')
        self.debug_dest = os.path.join(self.tempdir,
                                      'cython_debug',
                                      'cython_debug_info_codefile')
        self.cfuncs_destfile = os.path.join(self.tempdir, 'cfuncs')

        self.cwd = os.getcwd()
        try:
            os.chdir(self.tempdir)

            shutil.copy(codefile, self.destfile)
            shutil.copy(cfuncs_file, self.cfuncs_destfile + '.c')
            shutil.copy(cfuncs_file.replace('.c', '.h'),
                        self.cfuncs_destfile + '.h')

            compiler = ccompiler.new_compiler()
            compiler.compile(['cfuncs.c'], debug=True, extra_postargs=['-fPIC'])

            opts = dict(
                test_directory=self.tempdir,
                module='codefile',
            )

            optimization_disabler = build_ext.Optimization()

            cython_compile_testcase = runtests.CythonCompileTestCase(
                workdir=self.tempdir,
                # we clean up everything (not only compiled files)
                cleanup_workdir=False,
                tags=runtests.parse_tags(codefile),
                **opts
            )


            new_stderr = open(os.devnull, 'w')

            stderr = sys.stderr
            sys.stderr = new_stderr

            optimization_disabler.disable_optimization()
            try:
                cython_compile_testcase.run_cython(
                    targetdir=self.tempdir,
                    incdir=None,
                    annotate=False,
                    extra_compile_options={
                        'gdb_debug':True,
                        'output_dir':self.tempdir,
                    },
                    **opts
                )

                cython_compile_testcase.run_distutils(
                    incdir=None,
                    workdir=self.tempdir,
                    extra_extension_args={'extra_objects':['cfuncs.o']},
                    **opts
                )
            finally:
                optimization_disabler.restore_state()
                sys.stderr = stderr
                new_stderr.close()

            # ext = Cython.Distutils.extension.Extension(
                # 'codefile',
                # ['codefile.pyx'],
                # cython_gdb=True,
                # extra_objects=['cfuncs.o'])
            #
            # distutils.core.setup(
                # script_args=['build_ext', '--inplace'],
                # ext_modules=[ext],
                # cmdclass=dict(build_ext=Cython.Distutils.build_ext)
            # )

        except:
            os.chdir(self.cwd)
            raise

    def tearDown(self):
        if not test_gdb():
            return
        os.chdir(self.cwd)
        shutil.rmtree(self.tempdir)


class GdbDebuggerTestCase(DebuggerTestCase):

    def setUp(self):
        if not test_gdb():
            return

        super(GdbDebuggerTestCase, self).setUp()

        prefix_code = textwrap.dedent('''\
            python

            import os
            import sys
            import traceback

            def excepthook(type, value, tb):
                traceback.print_exception(type, value, tb)
                sys.stderr.flush()
                sys.stdout.flush()
                os._exit(1)

            sys.excepthook = excepthook

            # Have tracebacks end up on sys.stderr (gdb replaces sys.stderr
            # with an object that calls gdb.write())
            sys.stderr = sys.__stderr__

            end
            ''')

        code = textwrap.dedent('''\
            python

            from Cython.Debugger.Tests import test_libcython_in_gdb
            test_libcython_in_gdb.main(version=%r)

            end
            ''' % (sys.version_info[:2],))

        self.gdb_command_file = cygdb.make_command_file(self.tempdir,
                                                        prefix_code)

        with open(self.gdb_command_file, 'a') as f:
            f.write(code)

        args = ['gdb', '-batch', '-x', self.gdb_command_file, '-n', '--args',
                sys.executable, '-c', 'import codefile']

        paths = []
        path = os.environ.get('PYTHONPATH')
        if path:
            paths.append(path)
        paths.append(os.path.dirname(os.path.dirname(
            os.path.abspath(Cython.__file__))))
        env = dict(os.environ, PYTHONPATH=os.pathsep.join(paths))

        self.p = subprocess.Popen(
            args,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            env=env)

    def tearDown(self):
        if not test_gdb():
            return

        try:
            super(GdbDebuggerTestCase, self).tearDown()
            if self.p:
                try: self.p.stdout.close()
                except: pass
                try: self.p.stderr.close()
                except: pass
                self.p.wait()
        finally:
            os.remove(self.gdb_command_file)


class TestAll(GdbDebuggerTestCase):

    def test_all(self):
        if not test_gdb():
            return

        out, err = self.p.communicate()
        out = out.decode('UTF-8')
        err = err.decode('UTF-8')

        exit_status = self.p.returncode

        if exit_status == 1:
            sys.stderr.write(out)
            sys.stderr.write(err)
        elif exit_status >= 2:
            border = u'*' * 30
            start  = u'%s   v INSIDE GDB v   %s' % (border, border)
            stderr = u'%s   v STDERR v   %s' % (border, border)
            end    = u'%s   ^ INSIDE GDB ^   %s' % (border, border)
            errmsg = u'\n%s\n%s%s\n%s%s' % (start, out, stderr, err, end)

            sys.stderr.write(errmsg)

        # FIXME: re-enable this to make the test fail on internal failures
        #self.assertEqual(exit_status, 0)


if __name__ == '__main__':
    unittest.main()