test_utils_process.py 17.5 KB
Newer Older
1
import io
2
import logging
3
import os
4
import shlex
5
import unittest
6 7 8 9 10 11

try:
    from unittest import mock
except ImportError:
    import mock

12

13
from .. import recent_mock
14
from avocado.utils import astring
15
from avocado.utils import gdb
16
from avocado.utils import process
17
from avocado.utils import path
18

19 20 21
from six import string_types


22 23 24 25 26 27 28
def probe_binary(binary):
    try:
        return path.find_command(binary)
    except path.CmdNotFoundError:
        return None


29
ECHO_CMD = probe_binary('echo')
30
FICTIONAL_CMD = '/usr/bin/fictional_cmd'
31

32

33 34 35 36
class TestSubProcess(unittest.TestCase):

    def test_allow_output_check_parameter(self):
        self.assertRaises(ValueError, process.SubProcess,
37
                          FICTIONAL_CMD, False, "invalid")
38 39


40 41 42
class TestGDBProcess(unittest.TestCase):

    def setUp(self):
43
        self.current_runtime_expr = gdb.GDB_RUN_BINARY_NAMES_EXPR[:]
44 45

    def cleanUp(self):
46
        gdb.GDB_RUN_BINARY_NAMES_EXPR = self.current_runtime_expr
47 48

    def test_should_run_inside_gdb(self):
49
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['foo']
50 51 52 53
        self.assertTrue(process.should_run_inside_gdb('foo'))
        self.assertTrue(process.should_run_inside_gdb('/usr/bin/foo'))
        self.assertFalse(process.should_run_inside_gdb('/usr/bin/fooz'))

54
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('foo:main')
55 56 57
        self.assertTrue(process.should_run_inside_gdb('foo'))
        self.assertFalse(process.should_run_inside_gdb('bar'))

58
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('bar:main.c:5')
59 60 61 62 63
        self.assertTrue(process.should_run_inside_gdb('bar'))
        self.assertFalse(process.should_run_inside_gdb('baz'))
        self.assertTrue(process.should_run_inside_gdb('bar 1 2 3'))
        self.assertTrue(process.should_run_inside_gdb('/usr/bin/bar 1 2 3'))

64 65 66
    def test_should_run_inside_gdb_malformed_command(self):
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['/bin/virsh']
        cmd = """/bin/virsh node-memory-tune --shm-sleep-millisecs ~!@#$%^*()-=[]{}|_+":;'`,>?. """
67 68 69
        self.assertTrue(process.should_run_inside_gdb(cmd))
        self.assertFalse(process.should_run_inside_gdb("foo bar baz"))
        self.assertFalse(process.should_run_inside_gdb("foo ' "))
70

71
    def test_get_sub_process_klass(self):
72
        gdb.GDB_RUN_BINARY_NAMES_EXPR = []
73
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
74 75
                      process.SubProcess)

76
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('/bin/false')
77 78 79 80
        self.assertIs(process.get_sub_process_klass('/bin/false'),
                      process.GDBSubProcess)
        self.assertIs(process.get_sub_process_klass('false'),
                      process.GDBSubProcess)
81
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
82 83 84
                      process.SubProcess)

    def test_split_gdb_expr(self):
85
        binary, break_point = process.split_gdb_expr('foo:debug_print')
86
        self.assertEqual(binary, 'foo')
87 88
        self.assertEqual(break_point, 'debug_print')
        binary, break_point = process.split_gdb_expr('bar')
89
        self.assertEqual(binary, 'bar')
90 91
        self.assertEqual(break_point, 'main')
        binary, break_point = process.split_gdb_expr('baz:main.c:57')
92
        self.assertEqual(binary, 'baz')
93
        self.assertEqual(break_point, 'main.c:57')
94 95 96
        self.assertIsInstance(process.split_gdb_expr('foo'), tuple)
        self.assertIsInstance(process.split_gdb_expr('foo:debug_print'), tuple)

97

C
Caio Carrara 已提交
98
def mock_fail_find_cmd(cmd, default=None):  # pylint: disable=W0613
99 100 101 102 103 104 105
    path_paths = ["/usr/libexec", "/usr/local/sbin", "/usr/local/bin",
                  "/usr/sbin", "/usr/bin", "/sbin", "/bin"]
    raise path.CmdNotFoundError(cmd, path_paths)


class TestProcessRun(unittest.TestCase):

106
    @mock.patch.object(os, 'getuid',
107
                       mock.Mock(return_value=1000))
108 109 110 111 112
    def test_subprocess_nosudo(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

113
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
114 115 116 117 118
    def test_subprocess_nosudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

119
    @mock.patch.object(path, 'find_command',
120
                       mock.Mock(return_value='/bin/sudo'))
121
    @mock.patch.object(os, 'getuid',
122
                       mock.Mock(return_value=1000))
123
    def test_subprocess_sudo(self):
124
        expected_command = '/bin/sudo -n ls -l'
125
        p = process.SubProcess(cmd='ls -l', sudo=True)
126
        path.find_command.assert_called_once_with('sudo')
127 128
        self.assertEqual(p.cmd, expected_command)

129
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
130
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
131 132 133 134 135
    def test_subprocess_sudo_no_sudo_installed(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l', sudo=True)
        self.assertEqual(p.cmd, expected_command)

136
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
137 138 139 140 141
    def test_subprocess_sudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l', sudo=True)
        self.assertEqual(p.cmd, expected_command)

142
    @mock.patch.object(path, 'find_command',
143
                       mock.Mock(return_value='/bin/sudo'))
144
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
145
    def test_subprocess_sudo_shell(self):
146
        expected_command = '/bin/sudo -n -s ls -l'
147
        p = process.SubProcess(cmd='ls -l', sudo=True, shell=True)
148
        path.find_command.assert_called_once_with('sudo')
149 150
        self.assertEqual(p.cmd, expected_command)

151
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
152
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
153 154 155 156 157
    def test_subprocess_sudo_shell_no_sudo_installed(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l', sudo=True, shell=True)
        self.assertEqual(p.cmd, expected_command)

158
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
159 160 161 162 163
    def test_subprocess_sudo_shell_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l', sudo=True, shell=True)
        self.assertEqual(p.cmd, expected_command)

164
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
165 166 167 168 169
    def test_run_nosudo(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', ignore_status=True)
        self.assertEqual(p.command, expected_command)

170
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
171 172 173 174 175
    def test_run_nosudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', ignore_status=True)
        self.assertEqual(p.command, expected_command)

176 177
    @unittest.skipUnless(os.path.exists('/bin/sudo'),
                         "/bin/sudo not available")
178
    @mock.patch.object(path, 'find_command',
179
                       mock.Mock(return_value='/bin/sudo'))
180
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
181
    def test_run_sudo(self):
182
        expected_command = '/bin/sudo -n ls -l'
183
        p = process.run(cmd='ls -l', sudo=True, ignore_status=True)
184
        path.find_command.assert_called_once_with('sudo')
185 186
        self.assertEqual(p.command, expected_command)

187
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
188
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
189 190 191 192 193
    def test_run_sudo_no_sudo_installed(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', sudo=True, ignore_status=True)
        self.assertEqual(p.command, expected_command)

194
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
195 196 197 198 199
    def test_run_sudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', sudo=True, ignore_status=True)
        self.assertEqual(p.command, expected_command)

200
    @mock.patch.object(path, 'find_command',
201
                       mock.Mock(return_value='/bin/sudo'))
202
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
203
    def test_run_sudo_shell(self):
204
        expected_command = '/bin/sudo -n -s ls -l'
205
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
206
        path.find_command.assert_called_once_with('sudo')
207 208
        self.assertEqual(p.command, expected_command)

209
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
210
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
211 212 213 214 215
    def test_run_sudo_shell_no_sudo_installed(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
        self.assertEqual(p.command, expected_command)

216
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
217 218 219 220 221
    def test_run_sudo_shell_uid_0(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
        self.assertEqual(p.command, expected_command)

222 223 224 225 226 227
    @unittest.skipUnless(ECHO_CMD, "Echo command not available in system")
    def test_run_unicode_output(self):
        # Using encoded string as shlex does not support decoding
        # but the behavior is exactly the same as if shell binary
        # produced unicode
        text = u"Avok\xe1do"
228 229 230 231 232 233 234
        # Even though code point used is "LATIN SMALL LETTER A WITH ACUTE"
        # (http://unicode.scarfboy.com/?s=u%2B00e1) when encoded to proper
        # utf-8, it becomes two bytes because it is >= 0x80
        # See https://en.wikipedia.org/wiki/UTF-8
        encoded_text = b'Avok\xc3\xa1do'
        self.assertEqual(text.encode('utf-8'), encoded_text)
        self.assertEqual(encoded_text.decode('utf-8'), text)
235 236
        cmd = u"%s -n %s" % (ECHO_CMD, text)
        result = process.run(cmd, encoding='utf-8')
237 238
        self.assertEqual(result.stdout, encoded_text)
        self.assertEqual(result.stdout_text, text)
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

class MiscProcessTests(unittest.TestCase):

    def test_binary_from_shell(self):
        self.assertEqual("binary", process.binary_from_shell_cmd("binary"))
        res = process.binary_from_shell_cmd("MY_VAR=foo myV4r=123 "
                                            "quote='a b c' QUOTE=\"1 2 && b\" "
                                            "QuOtE=\"1 2\"foo' 3 4' first_bin "
                                            "second_bin VAR=xyz")
        self.assertEqual("first_bin", res)
        res = process.binary_from_shell_cmd("VAR=VALUE 1st_binary var=value "
                                            "second_binary")
        self.assertEqual("1st_binary", res)
        res = process.binary_from_shell_cmd("FOO=bar ./bin var=value")
        self.assertEqual("./bin", res)

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
    def test_cmd_split(self):
        plain_str = ''
        unicode_str = u''
        empty_bytes = b''
        # shlex.split() can work with "plain_str" and "unicode_str" on both
        # Python 2 and Python 3.  While we're not testing Python itself,
        # this will help us catch possible differences in the Python
        # standard library should they arise.
        self.assertEqual(shlex.split(plain_str), [])
        self.assertEqual(shlex.split(astring.to_text(plain_str)), [])
        self.assertEqual(shlex.split(unicode_str), [])
        self.assertEqual(shlex.split(astring.to_text(unicode_str)), [])
        # on Python 3, shlex.split() won't work with bytes, raising:
        # AttributeError: 'bytes' object has no attribute 'read'.
        # To turn bytes into text (when necessary), that is, on
        # Python 3 only, use astring.to_text()
        self.assertEqual(shlex.split(astring.to_text(empty_bytes)), [])
        # Now let's test our specific implementation to split commands
        self.assertEqual(process.cmd_split(plain_str), [])
        self.assertEqual(process.cmd_split(unicode_str), [])
        self.assertEqual(process.cmd_split(empty_bytes), [])
        unicode_command = u"avok\xe1do_test_runner arguments"
        self.assertEqual(process.cmd_split(unicode_command),
                         [u"avok\xe1do_test_runner",
                          u"arguments"])

282 283 284 285 286 287 288 289
    @unittest.skipUnless(recent_mock(),
                         "mock library version cannot (easily) patch open()")
    def test_get_parent_pid(self):
        stat = b'18405 (bash) S 24139 18405 18405 34818 8056 4210688 9792 170102 0 7 11 4 257 84 20 0 1 0 44336493 235409408 4281 18446744073709551615 94723230367744 94723231442728 140723100226000 0 0 0 65536 3670020 1266777851 0 0 0 17 1 0 0 0 0 0 94723233541456 94723233588580 94723248717824 140723100229613 140723100229623 140723100229623 140723100233710 0'
        with mock.patch('avocado.utils.process.open',
                        return_value=io.BytesIO(stat)):
            self.assertTrue(process.get_parent_pid(0), 24139)

L
Lukáš Doktor 已提交
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
class CmdResultTests(unittest.TestCase):

    def test_cmd_result_stdout_stderr_bytes(self):
        result = process.CmdResult()
        self.assertTrue(isinstance(result.stdout, bytes))
        self.assertTrue(isinstance(result.stderr, bytes))

    def test_cmd_result_stdout_stderr_text(self):
        result = process.CmdResult()
        self.assertTrue(isinstance(result.stdout_text, string_types))
        self.assertTrue(isinstance(result.stderr_text, string_types))

    def test_cmd_result_stdout_stderr_already_text(self):
        result = process.CmdResult()
        result.stdout = "supposed command output, but not as bytes"
        result.stderr = "supposed command error, but not as bytes"
        self.assertEqual(result.stdout, result.stdout_text)
        self.assertEqual(result.stderr, result.stderr_text)

    def test_cmd_result_stdout_stderr_other_type(self):
        result = process.CmdResult()
        result.stdout = None
        result.stderr = None
        self.assertRaises(TypeError, lambda x: result.stdout_text)
        self.assertRaises(TypeError, lambda x: result.stderr_text)


318 319 320 321 322 323 324
class FDDrainerTests(unittest.TestCase):

    def test_drain_from_pipe_fd(self):
        read_fd, write_fd = os.pipe()
        result = process.CmdResult()
        fd_drainer = process.FDDrainer(read_fd, result, "test")
        fd_drainer.start()
325
        for content in (b"foo", b"bar", b"baz", b"foo\nbar\nbaz\n\n"):
326
            os.write(write_fd, content)
327
        os.write(write_fd, b"finish")
328
        os.close(write_fd)
329
        fd_drainer.flush()
330
        self.assertEqual(fd_drainer.data.getvalue(),
331
                         b"foobarbazfoo\nbar\nbaz\n\nfinish")
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

    def test_log(self):
        class CatchHandler(logging.NullHandler):
            """
            Handler used just to confirm that a logging event happened
            """
            def __init__(self, *args, **kwargs):
                super(CatchHandler, self).__init__(*args, **kwargs)
                self.caught_record = False

            def handle(self, record):
                self.caught_record = True

        read_fd, write_fd = os.pipe()
        result = process.CmdResult()
        logger = logging.getLogger("FDDrainerTests.test_log")
        handler = CatchHandler()
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)

        fd_drainer = process.FDDrainer(read_fd, result, "test",
                                       logger=logger, verbose=True)
        fd_drainer.start()
355
        os.write(write_fd, b"should go to the log\n")
356
        os.close(write_fd)
357
        fd_drainer.flush()
358
        self.assertEqual(fd_drainer.data.getvalue(),
359
                         b"should go to the log\n")
360 361
        self.assertTrue(handler.caught_record)

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
    def test_flush_on_closed_handler(self):
        handler = logging.StreamHandler(io.StringIO())
        log = logging.getLogger("test_flush_on_closed_handler")
        log.addHandler(handler)
        read_fd, write_fd = os.pipe()
        result = process.CmdResult()
        fd_drainer = process.FDDrainer(read_fd, result, name="test",
                                       stream_logger=log)
        fd_drainer.start()
        os.close(write_fd)
        self.assertIsNotNone(fd_drainer._stream_logger)
        one_stream_closed = False
        for handler in fd_drainer._stream_logger.handlers:
            stream = getattr(handler, 'stream', None)
            if stream is not None:
                if hasattr(stream, 'close'):
                    # force closing the handler's stream to check if
                    # flush will adapt to it
                    stream.close()
                    one_stream_closed = True
        self.assertTrue(one_stream_closed)
        fd_drainer.flush()

    def test_flush_on_handler_with_no_fileno(self):
        handler = logging.StreamHandler(io.StringIO())
        log = logging.getLogger("test_flush_on_handler_with_no_fileno")
        log.addHandler(handler)
        read_fd, write_fd = os.pipe()
        result = process.CmdResult()
        fd_drainer = process.FDDrainer(read_fd, result, name="test",
                                       stream_logger=log)
        fd_drainer.start()
        os.close(write_fd)
        fd_drainer.flush()

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    def test_replace_incorrect_characters_in_log(self):
        data = io.StringIO()
        handler = logging.StreamHandler(data)
        log = logging.getLogger("test_replace_incorrect_characters_in_log")
        log.addHandler(handler)
        log.setLevel(logging.DEBUG)
        read_fd, write_fd = os.pipe()
        result = process.CmdResult(encoding='ascii')
        fd_drainer = process.FDDrainer(read_fd, result, name="test",
                                       stream_logger=log, verbose=True)
        fd_drainer.start()
        os.write(write_fd, b"Avok\xc3\xa1do")
        os.close(write_fd)
        fd_drainer._thread.join(60)
        self.assertFalse(fd_drainer._thread.is_alive())
        # \n added by StreamLogger
        self.assertEqual(data.getvalue(), u"Avok\ufffd\ufffddo\n")

415

416 417
if __name__ == "__main__":
    unittest.main()