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

try:
    from unittest import mock
except ImportError:
    import mock

14

15
from .. import recent_mock
16
from avocado.utils import astring
17
from avocado.utils import script
18
from avocado.utils import gdb
19
from avocado.utils import process
20
from avocado.utils import path
21

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

24 25 26 27 28
from .. import setup_avocado_loggers


setup_avocado_loggers()

29

30 31 32 33 34 35 36
def probe_binary(binary):
    try:
        return path.find_command(binary)
    except path.CmdNotFoundError:
        return None


37
ECHO_CMD = probe_binary('echo')
38
FICTIONAL_CMD = '/usr/bin/fictional_cmd'
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53
REFUSE_TO_DIE = """import signal
import time

for sig in range(64):
    try:
        signal.signal(sig, signal.SIG_IGN)
    except:
        pass

end = time.time() + 120

while time.time() < end:
    time.sleep(1)"""

54

55 56 57 58
class TestSubProcess(unittest.TestCase):

    def test_allow_output_check_parameter(self):
        self.assertRaises(ValueError, process.SubProcess,
59
                          FICTIONAL_CMD, False, "invalid")
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
    @mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @mock.patch('avocado.utils.process.SubProcess.is_sudo_enabled')
    @mock.patch('avocado.utils.process.SubProcess.get_pid')
    @mock.patch('avocado.utils.process.get_children_pids')
    @mock.patch('avocado.utils.process.run')
    def test_send_signal_sudo_enabled(self, run, get_children, pid, sudo, init):  # pylint: disable=W0613
        signal = 1
        child_pid = 123
        sudo.return_value = True
        get_children.return_value = [child_pid]

        subprocess = process.SubProcess(FICTIONAL_CMD)
        subprocess.send_signal(signal)

        expected_cmd = 'kill -%d %d' % (signal, child_pid)
        run.assert_called_with(expected_cmd, sudo=True)

    @mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @mock.patch('avocado.utils.process.SubProcess.is_sudo_enabled')
    @mock.patch('avocado.utils.process.SubProcess.get_pid')
    @mock.patch('avocado.utils.process.get_children_pids')
    @mock.patch('avocado.utils.process.run')
    def test_send_signal_sudo_enabled_with_exception(
            self, run, get_children, pid, sudo, init):  # pylint: disable=W0613
        signal = 1
        child_pid = 123
        sudo.return_value = True
        get_children.return_value = [child_pid]
        run.side_effect = Exception()

        subprocess = process.SubProcess(FICTIONAL_CMD)
        subprocess.send_signal(signal)

        expected_cmd = 'kill -%d %d' % (signal, child_pid)
        run.assert_called_with(expected_cmd, sudo=True)

    @mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @mock.patch('avocado.utils.process.SubProcess.get_pid')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_get_user_id(self, get_owner, get_pid, init):  # pylint: disable=W0613
        user_id = 1
        process_id = 123
        get_pid.return_value = process_id
        get_owner.return_value = user_id

        subprocess = process.SubProcess(FICTIONAL_CMD)

        self.assertEqual(subprocess.get_user_id(), user_id)
        get_owner.assert_called_with(process_id)

    @mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @mock.patch('avocado.utils.process.SubProcess.get_pid')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_is_sudo_enabled_false(self, get_owner, get_pid, init):  # pylint: disable=W0613
        user_id = 1
        process_id = 123
        get_pid.return_value = process_id
        get_owner.return_value = user_id

        subprocess = process.SubProcess(FICTIONAL_CMD)

        self.assertFalse(subprocess.is_sudo_enabled())
        get_owner.assert_called_with(process_id)

    @mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @mock.patch('avocado.utils.process.SubProcess.get_pid')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_is_sudo_enabled_true(self, get_owner, get_pid, init):  # pylint: disable=W0613
        user_id = 0
        process_id = 123
        get_pid.return_value = process_id
        get_owner.return_value = user_id

        subprocess = process.SubProcess(FICTIONAL_CMD)

        self.assertTrue(subprocess.is_sudo_enabled())
        get_owner.assert_called_with(process_id)

139

140 141 142
class TestGDBProcess(unittest.TestCase):

    def setUp(self):
143
        self.current_runtime_expr = gdb.GDB_RUN_BINARY_NAMES_EXPR[:]
144 145

    def cleanUp(self):
146
        gdb.GDB_RUN_BINARY_NAMES_EXPR = self.current_runtime_expr
147 148

    def test_should_run_inside_gdb(self):
149
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['foo']
150 151 152 153
        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'))

154
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('foo:main')
155 156 157
        self.assertTrue(process.should_run_inside_gdb('foo'))
        self.assertFalse(process.should_run_inside_gdb('bar'))

158
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('bar:main.c:5')
159 160 161 162 163
        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'))

164 165 166
    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 ~!@#$%^*()-=[]{}|_+":;'`,>?. """
167 168 169
        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 ' "))
170

171
    def test_get_sub_process_klass(self):
172
        gdb.GDB_RUN_BINARY_NAMES_EXPR = []
173
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
174 175
                      process.SubProcess)

176
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('/bin/false')
177 178 179 180
        self.assertIs(process.get_sub_process_klass('/bin/false'),
                      process.GDBSubProcess)
        self.assertIs(process.get_sub_process_klass('false'),
                      process.GDBSubProcess)
181
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
182 183 184
                      process.SubProcess)

    def test_split_gdb_expr(self):
185
        binary, break_point = process.split_gdb_expr('foo:debug_print')
186
        self.assertEqual(binary, 'foo')
187 188
        self.assertEqual(break_point, 'debug_print')
        binary, break_point = process.split_gdb_expr('bar')
189
        self.assertEqual(binary, 'bar')
190 191
        self.assertEqual(break_point, 'main')
        binary, break_point = process.split_gdb_expr('baz:main.c:57')
192
        self.assertEqual(binary, 'baz')
193
        self.assertEqual(break_point, 'main.c:57')
194 195 196
        self.assertIsInstance(process.split_gdb_expr('foo'), tuple)
        self.assertIsInstance(process.split_gdb_expr('foo:debug_print'), tuple)

197

C
Caio Carrara 已提交
198
def mock_fail_find_cmd(cmd, default=None):  # pylint: disable=W0613
199 200 201 202 203 204 205
    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):

206
    @mock.patch.object(os, 'getuid',
207
                       mock.Mock(return_value=1000))
208 209 210 211 212
    def test_subprocess_nosudo(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

213
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
214 215 216 217 218
    def test_subprocess_nosudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

219
    @mock.patch.object(path, 'find_command',
220
                       mock.Mock(return_value='/bin/sudo'))
221
    @mock.patch.object(os, 'getuid',
222
                       mock.Mock(return_value=1000))
223
    def test_subprocess_sudo(self):
224
        expected_command = '/bin/sudo -n ls -l'
225
        p = process.SubProcess(cmd='ls -l', sudo=True)
226
        path.find_command.assert_called_once_with('sudo')
227 228
        self.assertEqual(p.cmd, expected_command)

229
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
230
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
231 232 233 234 235
    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)

236
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
237 238 239 240 241
    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)

242
    @mock.patch.object(path, 'find_command',
243
                       mock.Mock(return_value='/bin/sudo'))
244
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
245
    def test_subprocess_sudo_shell(self):
246
        expected_command = '/bin/sudo -n -s ls -l'
247
        p = process.SubProcess(cmd='ls -l', sudo=True, shell=True)
248
        path.find_command.assert_called_once_with('sudo')
249 250
        self.assertEqual(p.cmd, expected_command)

251
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
252
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
253 254 255 256 257
    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)

258
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
259 260 261 262 263
    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)

264
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
265 266 267 268 269
    def test_run_nosudo(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', ignore_status=True)
        self.assertEqual(p.command, expected_command)

270
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
271 272 273 274 275
    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)

276 277
    @unittest.skipUnless(os.path.exists('/bin/sudo'),
                         "/bin/sudo not available")
278
    @mock.patch.object(path, 'find_command',
279
                       mock.Mock(return_value='/bin/sudo'))
280
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
281
    def test_run_sudo(self):
282
        expected_command = '/bin/sudo -n ls -l'
283
        p = process.run(cmd='ls -l', sudo=True, ignore_status=True)
284
        path.find_command.assert_called_once_with('sudo')
285 286
        self.assertEqual(p.command, expected_command)

287
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
288
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
289 290 291 292 293
    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)

294
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
295 296 297 298 299
    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)

300
    @mock.patch.object(path, 'find_command',
301
                       mock.Mock(return_value='/bin/sudo'))
302
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
303
    def test_run_sudo_shell(self):
304
        expected_command = '/bin/sudo -n -s ls -l'
305
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
306
        path.find_command.assert_called_once_with('sudo')
307 308
        self.assertEqual(p.command, expected_command)

309
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
310
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
311 312 313 314 315
    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)

316
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
317 318 319 320 321
    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)

322 323 324 325 326 327
    @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"
328 329 330 331 332 333 334
        # 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)
335 336
        cmd = u"%s -n %s" % (ECHO_CMD, text)
        result = process.run(cmd, encoding='utf-8')
337 338
        self.assertEqual(result.stdout, encoded_text)
        self.assertEqual(result.stdout_text, text)
339

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 1)) < 2,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
    def test_run_with_timeout_ugly_cmd(self):
        with script.TemporaryScript("refuse_to_die", REFUSE_TO_DIE) as exe:
            cmd = "%s '%s'" % (sys.executable, exe.path)
            # Wait 1s to set the traps
            res = process.run(cmd, timeout=1, ignore_status=True)
            self.assertLess(res.duration, 100, "Took longer than expected, "
                            "process probably not interrupted by Avocado.\n%s"
                            % res)
            self.assertNotEqual(res.exit_status, 0, "Command finished without "
                                "reporting failure but should be killed.\n%s"
                                % res)

    @unittest.skipIf(int(os.environ.get("AVOCADO_CHECK_LEVEL", 0)) < 2,
                     "Skipping test that take a long time to run, are "
                     "resource intensive or time sensitve")
    def test_run_with_negative_timeout_ugly_cmd(self):
        with script.TemporaryScript("refuse_to_die", REFUSE_TO_DIE) as exe:
            cmd = "%s '%s'" % (sys.executable, exe.path)
            # Wait 1s to set the traps
            proc = process.SubProcess(cmd)
            proc.start()
            time.sleep(1)
            proc.wait(-1)
            res = proc.result
            self.assertLess(res.duration, 100, "Took longer than expected, "
                            "process probably not interrupted by Avocado.\n%s"
                            % res)
            self.assertNotEqual(res.exit_status, 0, "Command finished without "
                                "reporting failure but should be killed.\n%s"
                                % res)

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

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)

390 391 392 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_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"])

416 417 418 419 420 421 422 423
    @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)

424 425 426 427 428 429 430 431
    @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)

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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    @mock.patch('avocado.utils.process.os.kill')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_safe_kill(self, owner_mocked, kill_mocked):
        owner_id = 1
        process_id = 123
        signal = 1
        owner_mocked.return_value = owner_id

        killed = process.safe_kill(process_id, signal)
        self.assertTrue(killed)
        kill_mocked.assert_called_with(process_id, signal)

    @mock.patch('avocado.utils.process.os.kill')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_safe_kill_with_exception(self, owner_mocked, kill_mocked):
        owner_id = 1
        process_id = 123
        signal = 1
        owner_mocked.return_value = owner_id
        kill_mocked.side_effect = Exception()

        killed = process.safe_kill(process_id, signal)
        self.assertFalse(killed)
        kill_mocked.assert_called_with(process_id, signal)

    @mock.patch('avocado.utils.process.run')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_safe_kill_sudo_enabled(self, owner_mocked, run_mocked):
        owner_id = 0
        process_id = 123
        signal = 1
        owner_mocked.return_value = owner_id
        expected_cmd = 'kill -%d %d' % (signal, process_id)

        killed = process.safe_kill(process_id, signal)
        self.assertTrue(killed)
        run_mocked.assert_called_with(expected_cmd, sudo=True)

    @mock.patch('avocado.utils.process.run')
    @mock.patch('avocado.utils.process.get_owner_id')
    def test_safe_kill_sudo_enabled_with_exception(self, owner_mocked, run_mocked):
        owner_id = 0
        process_id = 123
        signal = 1
        owner_mocked.return_value = owner_id
        expected_cmd = 'kill -%d %d' % (signal, process_id)
        run_mocked.side_effect = Exception()

        killed = process.safe_kill(process_id, signal)
        self.assertFalse(killed)
        run_mocked.assert_called_with(expected_cmd, sudo=True)

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    @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)

505 506 507 508 509 510 511
    @mock.patch('avocado.utils.process.time.sleep')
    @mock.patch('avocado.utils.process.safe_kill')
    @mock.patch('avocado.utils.process.get_children_pids')
    def test_kill_process_tree_nowait(self, get_children_pids, safe_kill,
                                      sleep):
        safe_kill.return_value = True
        get_children_pids.return_value = []
512
        self.assertEqual([1], process.kill_process_tree(1))
513 514 515 516 517 518 519 520 521 522 523
        self.assertEqual(sleep.call_count, 0)

    @mock.patch('avocado.utils.process.safe_kill')
    @mock.patch('avocado.utils.process.get_children_pids')
    @mock.patch('avocado.utils.process.time.time')
    @mock.patch('avocado.utils.process.time.sleep')
    @mock.patch('avocado.utils.process.pid_exists')
    def test_kill_process_tree_timeout_3s(self, pid_exists, sleep, p_time,
                                          get_children_pids, safe_kill):
        safe_kill.return_value = True
        get_children_pids.return_value = []
524 525
        p_time.side_effect = [500, 502, 502, 502, 502, 502, 502,
                              504, 504, 504, 520, 520, 520]
526 527
        sleep.return_value = None
        pid_exists.return_value = True
528
        self.assertRaises(RuntimeError, process.kill_process_tree, 17,
529
                          timeout=3)
530
        self.assertLess(p_time.call_count, 10)
531 532 533 534 535 536 537 538 539 540 541 542 543 544

    @mock.patch('avocado.utils.process.safe_kill')
    @mock.patch('avocado.utils.process.get_children_pids')
    @mock.patch('avocado.utils.process.time.time')
    @mock.patch('avocado.utils.process.time.sleep')
    @mock.patch('avocado.utils.process.pid_exists')
    def test_kill_process_tree_dont_timeout_3s(self, pid_exists, sleep,
                                               p_time, get_children_pids,
                                               safe_kill):
        safe_kill.return_value = True
        get_children_pids.return_value = []
        p_time.side_effect = [500, 502, 502, 502, 502, 502, 502, 502, 502, 503]
        sleep.return_value = None
        pid_exists.side_effect = [True, False]
545
        self.assertEqual([76], process.kill_process_tree(76, timeout=3))
546 547 548 549 550 551 552 553 554 555 556 557 558 559
        self.assertLess(p_time.call_count, 10)

    @mock.patch('avocado.utils.process.safe_kill')
    @mock.patch('avocado.utils.process.get_children_pids')
    @mock.patch('avocado.utils.process.time.sleep')
    @mock.patch('avocado.utils.process.pid_exists')
    def test_kill_process_tree_dont_timeout_infinity(self, pid_exists, sleep,
                                                     get_children_pids,
                                                     safe_kill):
        safe_kill.return_value = True
        get_children_pids.return_value = []
        sleep.return_value = None
        pid_exists.side_effect = [True, True, True, True, True, False]

560
        self.assertEqual([31], process.kill_process_tree(31, timeout=-7.354))
561 562 563 564

        self.assertEqual(pid_exists.call_count, 6)
        self.assertEqual(sleep.call_count, 5)

565 566 567 568 569 570 571 572 573 574 575 576
    @mock.patch('avocado.utils.process.time.sleep')
    @mock.patch('avocado.utils.process.safe_kill')
    @mock.patch('avocado.utils.process.get_children_pids')
    def test_kill_process_tree_children(self, get_children_pids, safe_kill,
                                        sleep):
        safe_kill.return_value = True
        get_children_pids.side_effect = [[53, 12], [78, 58, 41], [], [13],
                                         [], [], []]
        self.assertEqual([31, 53, 78, 58, 13, 41, 12],
                         process.kill_process_tree(31))
        self.assertEqual(sleep.call_count, 0)

L
Lukáš Doktor 已提交
577

578 579
class CmdResultTests(unittest.TestCase):

580 581 582 583 584 585 586 587 588 589 590 591 592 593
    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))

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    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 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
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))


636 637 638 639 640 641 642
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()
643
        for content in (b"foo", b"bar", b"baz", b"foo\nbar\nbaz\n\n"):
644
            os.write(write_fd, content)
645
        os.write(write_fd, b"finish")
646
        os.close(write_fd)
647
        fd_drainer.flush()
648
        self.assertEqual(fd_drainer.data.getvalue(),
649
                         b"foobarbazfoo\nbar\nbaz\n\nfinish")
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

    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()
673
        os.write(write_fd, b"should go to the log\n")
674
        os.close(write_fd)
675
        fd_drainer.flush()
676
        self.assertEqual(fd_drainer.data.getvalue(),
677
                         b"should go to the log\n")
678 679
        self.assertTrue(handler.caught_record)

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    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()

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    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")

733

734 735
if __name__ == "__main__":
    unittest.main()