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

try:
    from unittest import mock
except ImportError:
    import mock

13

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

J
Junxiang Li 已提交
20
from six import string_types, PY2
21 22


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


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

33

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

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


41 42 43
class TestGDBProcess(unittest.TestCase):

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

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

    def test_should_run_inside_gdb(self):
50
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['foo']
51 52 53 54
        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'))

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

59
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('bar:main.c:5')
60 61 62 63 64
        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'))

65 66 67
    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 ~!@#$%^*()-=[]{}|_+":;'`,>?. """
68 69 70
        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 ' "))
71

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

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

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

98

C
Caio Carrara 已提交
99
def mock_fail_find_cmd(cmd, default=None):  # pylint: disable=W0613
100 101 102 103 104 105 106
    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):

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

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

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

130
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
131
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
132 133 134 135 136
    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)

137
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
138 139 140 141 142
    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)

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

152
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
153
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
154 155 156 157 158
    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)

159
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
160 161 162 163 164
    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)

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

171
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
172 173 174 175 176
    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)

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

188
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
189
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
190 191 192 193 194
    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)

195
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
196 197 198 199 200
    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)

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

210
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
211
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
212 213 214 215 216
    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)

217
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
218 219 220 221 222
    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)

223 224 225 226 227 228
    @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"
229 230 231 232 233 234 235
        # 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)
236 237
        cmd = u"%s -n %s" % (ECHO_CMD, text)
        result = process.run(cmd, encoding='utf-8')
238 239
        self.assertEqual(result.stdout, encoded_text)
        self.assertEqual(result.stdout_text, text)
240

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

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)

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
    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"])

283 284 285 286 287 288 289 290
    @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)

291 292 293 294 295 296 297 298
    @unittest.skipUnless(sys.platform.startswith('linux'),
                         'Linux specific feature and test')
    def test_get_children_pids(self):
        '''
        Gets the list of children process.  Linux only.
        '''
        self.assertGreaterEqual(len(process.get_children_pids(1)), 1)

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    @mock.patch('avocado.utils.process.os.stat')
    def test_process_get_owner_id(self, stat_mock):
        process_id = 123
        owner_user_id = 13
        stat_mock.return_value = mock.Mock(st_uid=owner_user_id)

        returned_owner_id = process.get_owner_id(process_id)

        self.assertEqual(returned_owner_id, owner_user_id)
        stat_mock.assert_called_with('/proc/%d/' % process_id)

    @mock.patch('avocado.utils.process.os.stat')
    def test_process_get_owner_id_with_pid_not_found(self, stat_mock):
        process_id = 123
        stat_mock.side_effect = OSError()

        returned_owner_id = process.get_owner_id(process_id)

        self.assertIsNone(returned_owner_id)
        stat_mock.assert_called_with('/proc/%d/' % process_id)

L
Lukáš Doktor 已提交
320

321 322
class CmdResultTests(unittest.TestCase):

323 324 325 326 327 328 329 330 331 332 333 334 335 336
    def test_nasty_str(self):
        result = process.CmdResult("ls", b"unicode_follows: \xc5\xa1",
                                   b"cp1250 follows: \xfd", 1, 2, 3,
                                   "wrong_encoding")
        if PY2:
            prefix = ''
        else:
            prefix = 'b'
        self.assertEqual(str(result), "command: 'ls'\nexit_status: 1"
                         "\nduration: 2\ninterrupted: False\npid: "
                         "3\nencoding: 'wrong_encoding'\nstdout: "
                         "%s'unicode_follows: \\xc5\\xa1'\nstderr: "
                         "%s'cp1250 follows: \\xfd'" % (prefix, prefix))

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
    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)


J
Junxiang Li 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
class CmdErrorTests(unittest.TestCase):

    def test_nasty_str(self):
        result = process.CmdResult("ls", b"unicode_follows: \xc5\xa1",
                                   b"cp1250 follows: \xfd", 1, 2, 3,
                                   "wrong_encoding")
        err = process.CmdError("ls", result, "please don't crash")
        if PY2:
            prefix = ''
        else:
            prefix = 'b'
        self.assertEqual(str(err), "Command 'ls' failed.\nstdout: "
                         "%s'unicode_follows: \\xc5\\xa1'\nstderr: "
                         "%s'cp1250 follows: \\xfd'\nadditional_info: "
                         "please don't crash" % (prefix, prefix))


379 380 381 382 383 384 385
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()
386
        for content in (b"foo", b"bar", b"baz", b"foo\nbar\nbaz\n\n"):
387
            os.write(write_fd, content)
388
        os.write(write_fd, b"finish")
389
        os.close(write_fd)
390
        fd_drainer.flush()
391
        self.assertEqual(fd_drainer.data.getvalue(),
392
                         b"foobarbazfoo\nbar\nbaz\n\nfinish")
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

    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()
416
        os.write(write_fd, b"should go to the log\n")
417
        os.close(write_fd)
418
        fd_drainer.flush()
419
        self.assertEqual(fd_drainer.data.getvalue(),
420
                         b"should go to the log\n")
421 422
        self.assertTrue(handler.caught_record)

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
    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()

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    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")

476

477 478
if __name__ == "__main__":
    unittest.main()