test_gdb_bindings.py 7.88 KB
Newer Older
dugupeiwen's avatar
dugupeiwen committed
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
"""
Tests gdb bindings
"""
import os
import platform
import subprocess
import sys
import threading
from itertools import permutations

from numba import njit, gdb, gdb_init, gdb_breakpoint, prange
from numba.core import errors
from numba import jit

from numba.tests.support import (TestCase, captured_stdout, tag,
                                 skip_parfors_unsupported)
from numba.tests.gdb_support import needs_gdb
import unittest


_platform = sys.platform

_unix_like = (_platform.startswith('linux')
              or _platform.startswith('darwin')
              or ('bsd' in _platform))

unix_only = unittest.skipUnless(_unix_like, "unix-like OS is required")
not_unix = unittest.skipIf(_unix_like, "non unix-like OS is required")

_arch_name = platform.machine()
_is_arm = _arch_name in {'aarch64', 'armv7l'}
not_arm = unittest.skipIf(_is_arm, "testing disabled on ARM")

_gdb_cond = os.environ.get('GDB_TEST', None) == '1'
needs_gdb_harness = unittest.skipUnless(_gdb_cond, "needs gdb harness")

long_running = tag('long_running')

_dbg_njit = njit(debug=True)
_dbg_jit = jit(forceobj=True, debug=True)


def impl_gdb_call(a):
    gdb('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q')
    b = a + 1
    c = a * 2.34
    d = (a, b, c)
    print(a, b, c, d)


def impl_gdb_call_w_bp(a):
    gdb_init('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q')
    b = a + 1
    c = a * 2.34
    d = (a, b, c)
    gdb_breakpoint()
    print(a, b, c, d)


def impl_gdb_split_init_and_break_w_parallel(a):
    gdb_init('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q')
    a += 3
    for i in prange(4):
        b = a + 1
        c = a * 2.34
        d = (a, b, c)
        gdb_breakpoint()
        print(a, b, c, d)


@not_arm
@unix_only
class TestGdbBindImpls(TestCase):
    """
    Contains unit test implementations for gdb binding testing. Test must be
    decorated with `@needs_gdb_harness` to prevent their running under normal
    test conditions, the test methods must also end with `_impl` to be
    considered for execution. The tests themselves are invoked by the
    `TestGdbBinding` test class through the parsing of this class for test
    methods and then running the discovered tests in a separate process. Test
    names not including the word `quick` will be tagged as @tag('long_running')
    """

    @needs_gdb_harness
    def test_gdb_cmd_lang_cpython_quick_impl(self):
        with captured_stdout():
            impl_gdb_call(10)

    @needs_gdb_harness
    def test_gdb_cmd_lang_nopython_quick_impl(self):
        with captured_stdout():
            _dbg_njit(impl_gdb_call)(10)

    @needs_gdb_harness
    def test_gdb_cmd_lang_objmode_quick_impl(self):
        with captured_stdout():
            _dbg_jit(impl_gdb_call)(10)

    @needs_gdb_harness
    def test_gdb_split_init_and_break_cpython_impl(self):
        with captured_stdout():
            impl_gdb_call_w_bp(10)

    @needs_gdb_harness
    def test_gdb_split_init_and_break_nopython_impl(self):
        with captured_stdout():
            _dbg_njit(impl_gdb_call_w_bp)(10)

    @needs_gdb_harness
    def test_gdb_split_init_and_break_objmode_impl(self):
        with captured_stdout():
            _dbg_jit(impl_gdb_call_w_bp)(10)

    @skip_parfors_unsupported
    @needs_gdb_harness
    def test_gdb_split_init_and_break_w_parallel_cpython_impl(self):
        with captured_stdout():
            impl_gdb_split_init_and_break_w_parallel(10)

    @skip_parfors_unsupported
    @needs_gdb_harness
    def test_gdb_split_init_and_break_w_parallel_nopython_impl(self):
        with captured_stdout():
            _dbg_njit(impl_gdb_split_init_and_break_w_parallel)(10)

    @skip_parfors_unsupported
    @needs_gdb_harness
    def test_gdb_split_init_and_break_w_parallel_objmode_impl(self):
        with captured_stdout():
            _dbg_jit(impl_gdb_split_init_and_break_w_parallel)(10)


@not_arm
@unix_only
@needs_gdb
class TestGdbBinding(TestCase):
    """
    This test class is used to generate tests which will run the test cases
    defined in TestGdbBindImpls in isolated subprocesses, this is for safety
    in case something goes awry.
    """

    # test mutates env
    _numba_parallel_test_ = False

    _DEBUG = True

    def run_cmd(self, cmdline, env, kill_is_ok=False):
        popen = subprocess.Popen(cmdline,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 env=env,
                                 shell=True)
        # finish in 20s or kill it, there's no work being done

        def kill():
            popen.stdout.flush()
            popen.stderr.flush()
            popen.kill()
        timeout = threading.Timer(20., kill)
        try:
            timeout.start()
            out, err = popen.communicate()
            retcode = popen.returncode
            if retcode != 0:
                raise AssertionError(
                    "process failed with code %s: "
                    "stderr follows\n%s\n"
                    "stdout :%s" % (retcode, err.decode(), out.decode()))
            return out.decode(), err.decode()
        finally:
            timeout.cancel()
        return None, None

    def run_test_in_separate_process(self, test, **kwargs):
        env_copy = os.environ.copy()
        env_copy['NUMBA_OPT'] = '1'
        # Set GDB_TEST to permit the execution of tests decorated with
        # @needs_gdb_harness
        env_copy['GDB_TEST'] = '1'
        cmdline = [sys.executable, "-m", "numba.runtests", test]
        return self.run_cmd(' '.join(cmdline), env_copy, **kwargs)

    @classmethod
    def _inject(cls, name):
        themod = TestGdbBindImpls.__module__
        thecls = TestGdbBindImpls.__name__
        # strip impl
        assert name.endswith('_impl')
        methname = name.replace('_impl', '')
        injected_method = '%s.%s.%s' % (themod, thecls, name)

        def test_template(self):
            o, e = self.run_test_in_separate_process(injected_method)
            dbgmsg = f'\nSTDOUT={o}\nSTDERR={e}\n'
            self.assertIn('GNU gdb', o, msg=dbgmsg)
            self.assertIn('OK', e, msg=dbgmsg)
            self.assertNotIn('FAIL', e, msg=dbgmsg)
            self.assertNotIn('ERROR', e, msg=dbgmsg)
        if 'quick' in name:
            setattr(cls, methname, test_template)
        else:
            setattr(cls, methname, long_running(test_template))

    @classmethod
    def generate(cls):
        for name in dir(TestGdbBindImpls):
            if name.startswith('test_gdb'):
                cls._inject(name)


TestGdbBinding.generate()


@not_arm
@unix_only
@needs_gdb
class TestGdbMisc(TestCase):

    @long_running
    def test_call_gdb_twice(self):
        def gen(f1, f2):
            @njit
            def impl():
                a = 1
                f1()
                b = 2
                f2()
                return a + b
            return impl

        msg_head = "Calling either numba.gdb() or numba.gdb_init() more than"

        def check(func):
            with self.assertRaises(errors.UnsupportedError) as raises:
                func()
            self.assertIn(msg_head, str(raises.exception))

        for g1, g2 in permutations([gdb, gdb_init]):
            func = gen(g1, g2)
            check(func)

        @njit
        def use_globals():
            a = 1
            gdb()
            b = 2
            gdb_init()
            return a + b

        check(use_globals)


@not_unix
class TestGdbExceptions(TestCase):

    def test_call_gdb(self):
        def nop_compiler(x):
            return x
        for compiler in [nop_compiler, jit(forceobj=True), njit]:
            for meth in [gdb, gdb_init]:
                def python_func():
                    meth()
                with self.assertRaises(errors.TypingError) as raises:
                    compiler(python_func)()
                msg = "gdb support is only available on unix-like systems"
                self.assertIn(msg, str(raises.exception))


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