test_cli.py 10.2 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
272
273
274
275
276
277
278
279
280
281
# Tests for the CLI

import os
import subprocess
import sys
import threading
import json
from subprocess import CompletedProcess
from tempfile import TemporaryDirectory
from unittest import mock

import unittest
from numba.tests.support import TestCase, linux_only
import numba.misc.numba_sysinfo as nsi
from numba.tests.gdb_support import needs_gdb
from numba.misc.numba_gdbinfo import collect_gdbinfo
# Going to mock parts of this in testing
from numba.misc.numba_gdbinfo import _GDBTestWrapper


def run_cmd(cmdline, env=os.environ, timeout=60):
    popen = subprocess.Popen(cmdline,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             env=env)

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


class TestCLI(TestCase):

    def test_as_module_exit_code(self):
        cmdline = [sys.executable, "-m", "numba"]
        with self.assertRaises(AssertionError) as raises:
            run_cmd(cmdline)

        self.assertIn("process failed with code 1", str(raises.exception))

    def test_sysinfo_from_module(self):
        cmdline = [sys.executable, "-m", "numba", "-s"]
        o, _ = run_cmd(cmdline)
        self.assertIn("System info", o)

    def test_json_sysinfo_from_module(self):
        with TemporaryDirectory() as d:
            path = os.path.join(d, "test_json_sysinfo.json")
            cmdline = [sys.executable, "-m", "numba", "--sys-json", path]
            run_cmd(cmdline)
            with self.subTest(msg=f"{path} exists"):
                self.assertTrue(os.path.exists(path))
            with self.subTest(msg="json load"):
                with open(path, 'r') as f:
                    info = json.load(f)
            safe_contents = {
                int: (
                    nsi._cpu_count,
                ),
                float: (
                    nsi._runtime,
                ),
                str: (
                    nsi._start,
                    nsi._start_utc,
                    nsi._machine,
                    nsi._cpu_name,
                    nsi._platform_name,
                    nsi._os_name,
                    nsi._os_version,
                    nsi._python_comp,
                    nsi._python_impl,
                    nsi._python_version,
                    nsi._llvm_version,
                ),
                bool: (
                    nsi._cu_dev_init,
                    nsi._svml_state,
                    nsi._svml_loaded,
                    nsi._svml_operational,
                    nsi._llvm_svml_patched,
                    nsi._tbb_thread,
                    nsi._openmp_thread,
                    nsi._wkq_thread,
                ),
                list: (
                    nsi._errors,
                    nsi._warnings,
                ),
                dict: (
                    nsi._numba_env_vars,
                ),
            }
            for t, keys in safe_contents.items():
                for k in keys:
                    with self.subTest(k=k):
                        self.assertIsInstance(info[k], t)

    @needs_gdb
    def test_gdb_status_from_module(self):
        # Check that the `python -m numba -g` works ok
        cmdline = [sys.executable, "-m", "numba", "-g"]
        o, _ = run_cmd(cmdline)
        self.assertIn("GDB info", o)
        # It's not known a priori whether the extension is supported, this just
        # checks that the last logical item in the output is printed.
        self.assertIn("Numba printing extension support", o)


class TestGDBCLIInfo(TestCase):

    def setUp(self):
        # Mock the entire class, to report valid things,
        # then override bits of it locally to check failures etc.

        self._patches = []

        mock_init = lambda self: None
        self._patches.append(mock.patch.object(_GDBTestWrapper, '__init__',
                                               mock_init))

        bpath = 'numba.misc.numba_gdbinfo._GDBTestWrapper.gdb_binary'
        self._patches.append(mock.patch(bpath, 'PATH_TO_GDB'))

        def _patch(fnstr, func):
            self._patches.append(mock.patch.object(_GDBTestWrapper, fnstr,
                                                   func))

        def mock_check_launch(self):
            return CompletedProcess('COMMAND STRING', 0)

        _patch('check_launch', mock_check_launch)

        # NOTE: The Python and NumPy versions are set to something unsupported!
        def mock_check_python(self):
            return CompletedProcess('COMMAND STRING', 0,
                                    stdout='(3, 2)',
                                    stderr='')

        _patch('check_python', mock_check_python)

        def mock_check_numpy(self):
            return CompletedProcess('COMMAND STRING', 0, stdout='True',
                                    stderr='')

        _patch('check_numpy', mock_check_numpy)

        def mock_check_numpy_version(self):
            return CompletedProcess('COMMAND STRING', 0, stdout='1.15',
                                    stderr='')

        _patch('check_numpy_version', mock_check_numpy_version)

        # start the patching
        for p in self._patches:
            p.start()

    def tearDown(self):
        # stop the patching
        for p in self._patches:
            p.stop()

    def test_valid(self):
        collected = collect_gdbinfo()
        self.assertEqual(collected.binary_loc, 'PATH_TO_GDB')
        extp = os.path.exists(os.path.abspath(collected.extension_loc))
        self.assertTrue(extp)
        self.assertEqual(collected.py_ver, '3.2')
        self.assertEqual(collected.np_ver, '1.15')
        self.assertIn('Full', collected.supported)

    def test_invalid_binary(self):

        def mock_fn(self):
            return CompletedProcess('INVALID_BINARY', 1)

        with mock.patch.object(_GDBTestWrapper, 'check_launch', mock_fn):
            info = collect_gdbinfo()
            self.assertIn("Testing gdb binary failed.", info.binary_loc)
            self.assertIn("gdb at 'PATH_TO_GDB' does not appear to work",
                          info.binary_loc)

    def test_no_python(self):
        def mock_fn(self):
            return CompletedProcess('NO PYTHON', 1)

        with mock.patch.object(_GDBTestWrapper, 'check_python', mock_fn):
            collected = collect_gdbinfo()
            self.assertEqual(collected.py_ver, 'No Python support')
            self.assertEqual(collected.supported, 'None')

    def test_unparsable_python_version(self):
        def mock_fn(self):
            return CompletedProcess('NO PYTHON', 0, stdout='(NOT A VERSION)')

        with mock.patch.object(_GDBTestWrapper, 'check_python', mock_fn):
            collected = collect_gdbinfo()
            self.assertEqual(collected.py_ver, 'No Python support')

    def test_no_numpy(self):
        def mock_fn(self):
            return CompletedProcess('NO NUMPY', 1)

        with mock.patch.object(_GDBTestWrapper, 'check_numpy', mock_fn):
            collected = collect_gdbinfo()
            self.assertEqual(collected.np_ver, 'No NumPy support')
            self.assertEqual(collected.py_ver, '3.2')
            self.assertIn('Partial', collected.supported)

    def test_no_numpy_version(self):
        def mock_fn(self):
            return CompletedProcess('NO NUMPY VERSION', 1)

        with mock.patch.object(_GDBTestWrapper, 'check_numpy_version', mock_fn):
            collected = collect_gdbinfo()
            self.assertEqual(collected.np_ver, 'Unknown')

    def test_traceback_in_numpy_version(self):
        def mock_fn(self):
            return CompletedProcess('NO NUMPY VERSION', 0,
                                    stdout='(NOT A VERSION)',
                                    stderr='Traceback')

        with mock.patch.object(_GDBTestWrapper, 'check_numpy_version', mock_fn):
            collected = collect_gdbinfo()
            self.assertEqual(collected.np_ver, 'Unknown')


@linux_only
class TestGDBCLIInfoBrokenGdbs(TestCase):
    # In these tests, it's necessary to actually run the entry point in an env
    # with the env var set as it's in part testing the processing of the
    # handling of consumption of variables by numba.core.config.

    def test_cannot_find_gdb_from_name(self):
        # Tests that supplying an invalid gdb binary name is handled ok
        env = os.environ.copy()
        env['NUMBA_GDB_BINARY'] = 'THIS_IS_NOT_A_VALID_GDB_BINARY_NAME'
        cmdline = [sys.executable, "-m", "numba", "-g"]
        stdout, stderr = run_cmd(cmdline, env=env)
        self.assertIn("Testing gdb binary failed", stdout)
        self.assertIn("No such file or directory", stdout)
        self.assertIn("'THIS_IS_NOT_A_VALID_GDB_BINARY_NAME'", stdout)

    def test_cannot_find_gdb_from_path(self):
        # Tests that an invalid path is handled ok
        env = os.environ.copy()
        with TemporaryDirectory() as d:
            # This wont exist as a path...
            path = os.path.join(d, 'CANNOT_EXIST')
            env['NUMBA_GDB_BINARY'] = path
            cmdline = [sys.executable, "-m", "numba", "-g"]
            stdout, stderr = run_cmd(cmdline, env=env)
            self.assertIn("Testing gdb binary failed", stdout)
            self.assertIn("No such file or directory", stdout)
            self.assertIn(path, stdout)

    def test_nonsense_gdb_binary(self):
        # Tests that a nonsense binary specified as gdb it picked up ok
        env = os.environ.copy()
        env['NUMBA_GDB_BINARY'] = 'python' # 'python' isn't gdb!
        cmdline = [sys.executable, "-m", "numba", "-g"]
        stdout, stderr = run_cmd(cmdline, env=env)
        self.assertIn("Testing gdb binary failed", stdout)
        # NOTE: should 'python' ever add support for the same flags as the gdb
        # commands used in the information gathering code in `numba_gdbinfo`
        # this test will fail, it's reasonably unlikely.
        self.assertIn("Unknown option", stdout)


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