test_utils_process.py 31.6 KB
Newer Older
1
import io
2
import logging
3
import os
4
import shlex
C
Cleber Rosa 已提交
5
import unittest.mock
6
import sys
7
import time
8

9

10
from avocado.utils import astring
11
from avocado.utils import script
12
from avocado.utils import gdb
13
from avocado.utils import process
14
from avocado.utils import path
15

J
Junxiang Li 已提交
16
from six import string_types, PY2
17

18 19 20 21 22
from .. import setup_avocado_loggers


setup_avocado_loggers()

23

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


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

34 35 36 37 38 39 40 41 42 43 44 45 46 47
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)"""

48

49 50 51 52
class TestSubProcess(unittest.TestCase):

    def test_allow_output_check_parameter(self):
        self.assertRaises(ValueError, process.SubProcess,
53
                          FICTIONAL_CMD, False, "invalid")
54

C
Cleber Rosa 已提交
55 56 57 58 59
    @unittest.mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @unittest.mock.patch('avocado.utils.process.SubProcess.is_sudo_enabled')
    @unittest.mock.patch('avocado.utils.process.SubProcess.get_pid')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
    @unittest.mock.patch('avocado.utils.process.run')
60 61 62 63 64 65 66 67 68 69 70 71
    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)

C
Cleber Rosa 已提交
72 73 74 75 76
    @unittest.mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @unittest.mock.patch('avocado.utils.process.SubProcess.is_sudo_enabled')
    @unittest.mock.patch('avocado.utils.process.SubProcess.get_pid')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
    @unittest.mock.patch('avocado.utils.process.run')
77 78 79 80 81 82 83 84 85 86 87 88 89 90
    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)

C
Cleber Rosa 已提交
91 92 93
    @unittest.mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @unittest.mock.patch('avocado.utils.process.SubProcess.get_pid')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
94 95 96 97 98 99 100 101 102 103 104
    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)

C
Cleber Rosa 已提交
105 106 107
    @unittest.mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @unittest.mock.patch('avocado.utils.process.SubProcess.get_pid')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
108 109 110 111 112 113 114 115 116 117 118
    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)

C
Cleber Rosa 已提交
119 120 121
    @unittest.mock.patch('avocado.utils.process.SubProcess._init_subprocess')
    @unittest.mock.patch('avocado.utils.process.SubProcess.get_pid')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
122 123 124 125 126 127 128 129 130 131 132
    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)

133

134 135 136
class TestGDBProcess(unittest.TestCase):

    def setUp(self):
137
        self.current_runtime_expr = gdb.GDB_RUN_BINARY_NAMES_EXPR[:]
138 139

    def cleanUp(self):
140
        gdb.GDB_RUN_BINARY_NAMES_EXPR = self.current_runtime_expr
141 142

    def test_should_run_inside_gdb(self):
143
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['foo']
144 145 146 147
        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'))

148
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('foo:main')
149 150 151
        self.assertTrue(process.should_run_inside_gdb('foo'))
        self.assertFalse(process.should_run_inside_gdb('bar'))

152
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('bar:main.c:5')
153 154 155 156 157
        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'))

158 159 160
    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 ~!@#$%^*()-=[]{}|_+":;'`,>?. """
161 162 163
        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 ' "))
164

165
    def test_get_sub_process_klass(self):
166
        gdb.GDB_RUN_BINARY_NAMES_EXPR = []
167
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
168 169
                      process.SubProcess)

170
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('/bin/false')
171 172 173 174
        self.assertIs(process.get_sub_process_klass('/bin/false'),
                      process.GDBSubProcess)
        self.assertIs(process.get_sub_process_klass('false'),
                      process.GDBSubProcess)
175
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
176 177 178
                      process.SubProcess)

    def test_split_gdb_expr(self):
179
        binary, break_point = process.split_gdb_expr('foo:debug_print')
180
        self.assertEqual(binary, 'foo')
181 182
        self.assertEqual(break_point, 'debug_print')
        binary, break_point = process.split_gdb_expr('bar')
183
        self.assertEqual(binary, 'bar')
184 185
        self.assertEqual(break_point, 'main')
        binary, break_point = process.split_gdb_expr('baz:main.c:57')
186
        self.assertEqual(binary, 'baz')
187
        self.assertEqual(break_point, 'main.c:57')
188 189 190
        self.assertIsInstance(process.split_gdb_expr('foo'), tuple)
        self.assertIsInstance(process.split_gdb_expr('foo:debug_print'), tuple)

191

C
Caio Carrara 已提交
192
def mock_fail_find_cmd(cmd, default=None):  # pylint: disable=W0613
193 194 195 196 197 198 199
    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):

C
Cleber Rosa 已提交
200 201
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
202 203 204 205 206
    def test_subprocess_nosudo(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

C
Cleber Rosa 已提交
207 208
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=0))
209 210 211 212 213
    def test_subprocess_nosudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

C
Cleber Rosa 已提交
214 215 216 217
    @unittest.mock.patch.object(path, 'find_command',
                                unittest.mock.Mock(return_value='/bin/sudo'))
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
218
    def test_subprocess_sudo(self):
219
        expected_command = '/bin/sudo -n ls -l'
220
        p = process.SubProcess(cmd='ls -l', sudo=True)
221
        path.find_command.assert_called_once_with('sudo')
222 223
        self.assertEqual(p.cmd, expected_command)

C
Cleber Rosa 已提交
224 225 226
    @unittest.mock.patch.object(path, 'find_command', mock_fail_find_cmd)
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
227 228 229 230 231
    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)

C
Cleber Rosa 已提交
232 233
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=0))
234 235 236 237 238
    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)

C
Cleber Rosa 已提交
239 240 241 242
    @unittest.mock.patch.object(path, 'find_command',
                                unittest.mock.Mock(return_value='/bin/sudo'))
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
243
    def test_subprocess_sudo_shell(self):
244
        expected_command = '/bin/sudo -n -s ls -l'
245
        p = process.SubProcess(cmd='ls -l', sudo=True, shell=True)
246
        path.find_command.assert_called_once_with('sudo')
247 248
        self.assertEqual(p.cmd, expected_command)

C
Cleber Rosa 已提交
249 250 251
    @unittest.mock.patch.object(path, 'find_command', mock_fail_find_cmd)
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
252 253 254 255 256
    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)

C
Cleber Rosa 已提交
257 258
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.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)

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

C
Cleber Rosa 已提交
271 272
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=0))
273 274 275 276 277
    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)

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

C
Cleber Rosa 已提交
290 291 292
    @unittest.mock.patch.object(path, 'find_command', mock_fail_find_cmd)
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
293 294 295 296 297
    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)

C
Cleber Rosa 已提交
298 299
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=0))
300 301 302 303 304
    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)

C
Cleber Rosa 已提交
305 306 307 308
    @unittest.mock.patch.object(path, 'find_command',
                                unittest.mock.Mock(return_value='/bin/sudo'))
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
309
    def test_run_sudo_shell(self):
310
        expected_command = '/bin/sudo -n -s ls -l'
311
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
312
        path.find_command.assert_called_once_with('sudo')
313 314
        self.assertEqual(p.command, expected_command)

C
Cleber Rosa 已提交
315 316 317
    @unittest.mock.patch.object(path, 'find_command', mock_fail_find_cmd)
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=1000))
318 319 320 321 322
    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)

C
Cleber Rosa 已提交
323 324
    @unittest.mock.patch.object(os, 'getuid',
                                unittest.mock.Mock(return_value=0))
325 326 327 328 329
    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)

330 331 332 333 334 335
    @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"
336 337 338 339 340 341 342
        # 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)
343 344
        cmd = u"%s -n %s" % (ECHO_CMD, text)
        result = process.run(cmd, encoding='utf-8')
345 346
        self.assertEqual(result.stdout, encoded_text)
        self.assertEqual(result.stdout_text, text)
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 374 375 376 377 378 379 380 381
    @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)

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

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)

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    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"])

424 425
    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'
426
        with unittest.mock.patch('builtins.open',
C
Cleber Rosa 已提交
427
                                 return_value=io.BytesIO(stat)):
428 429
            self.assertTrue(process.get_parent_pid(0), 24139)

430 431 432 433 434 435 436 437
    @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)

C
Cleber Rosa 已提交
438 439
    @unittest.mock.patch('avocado.utils.process.os.kill')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
440 441 442 443 444 445 446 447 448 449
    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)

C
Cleber Rosa 已提交
450 451
    @unittest.mock.patch('avocado.utils.process.os.kill')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
452 453 454 455 456 457 458 459 460 461 462
    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)

C
Cleber Rosa 已提交
463 464
    @unittest.mock.patch('avocado.utils.process.run')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
465 466 467 468 469 470 471 472 473 474 475
    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)

C
Cleber Rosa 已提交
476 477
    @unittest.mock.patch('avocado.utils.process.run')
    @unittest.mock.patch('avocado.utils.process.get_owner_id')
478 479 480 481 482 483 484 485 486 487 488 489
    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)

C
Cleber Rosa 已提交
490
    @unittest.mock.patch('avocado.utils.process.os.stat')
491 492 493
    def test_process_get_owner_id(self, stat_mock):
        process_id = 123
        owner_user_id = 13
C
Cleber Rosa 已提交
494
        stat_mock.return_value = unittest.mock.Mock(st_uid=owner_user_id)
495 496 497 498 499 500

        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)

C
Cleber Rosa 已提交
501
    @unittest.mock.patch('avocado.utils.process.os.stat')
502 503 504 505 506 507 508 509 510
    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)

C
Cleber Rosa 已提交
511 512 513
    @unittest.mock.patch('avocado.utils.process.time.sleep')
    @unittest.mock.patch('avocado.utils.process.safe_kill')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
514 515 516 517
    def test_kill_process_tree_nowait(self, get_children_pids, safe_kill,
                                      sleep):
        safe_kill.return_value = True
        get_children_pids.return_value = []
518
        self.assertEqual([1], process.kill_process_tree(1))
519 520
        self.assertEqual(sleep.call_count, 0)

C
Cleber Rosa 已提交
521 522 523 524 525
    @unittest.mock.patch('avocado.utils.process.safe_kill')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
    @unittest.mock.patch('avocado.utils.process.time.time')
    @unittest.mock.patch('avocado.utils.process.time.sleep')
    @unittest.mock.patch('avocado.utils.process.pid_exists')
526 527 528 529
    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 = []
530 531
        p_time.side_effect = [500, 502, 502, 502, 502, 502, 502,
                              504, 504, 504, 520, 520, 520]
532 533
        sleep.return_value = None
        pid_exists.return_value = True
534
        self.assertRaises(RuntimeError, process.kill_process_tree, 17,
535
                          timeout=3)
536
        self.assertLess(p_time.call_count, 10)
537

C
Cleber Rosa 已提交
538 539 540 541 542
    @unittest.mock.patch('avocado.utils.process.safe_kill')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
    @unittest.mock.patch('avocado.utils.process.time.time')
    @unittest.mock.patch('avocado.utils.process.time.sleep')
    @unittest.mock.patch('avocado.utils.process.pid_exists')
543 544 545 546 547 548 549 550
    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]
551
        self.assertEqual([76], process.kill_process_tree(76, timeout=3))
552 553
        self.assertLess(p_time.call_count, 10)

C
Cleber Rosa 已提交
554 555 556 557
    @unittest.mock.patch('avocado.utils.process.safe_kill')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
    @unittest.mock.patch('avocado.utils.process.time.sleep')
    @unittest.mock.patch('avocado.utils.process.pid_exists')
558 559 560 561 562 563 564 565
    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]

566
        self.assertEqual([31], process.kill_process_tree(31, timeout=-7.354))
567 568 569 570

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

C
Cleber Rosa 已提交
571 572 573
    @unittest.mock.patch('avocado.utils.process.time.sleep')
    @unittest.mock.patch('avocado.utils.process.safe_kill')
    @unittest.mock.patch('avocado.utils.process.get_children_pids')
574 575 576 577 578 579 580 581 582
    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 已提交
583

584 585
class CmdResultTests(unittest.TestCase):

586 587 588 589 590 591 592 593 594 595 596 597 598 599
    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))

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


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

    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()
679
        os.write(write_fd, b"should go to the log\n")
680
        os.close(write_fd)
681
        fd_drainer.flush()
682
        self.assertEqual(fd_drainer.data.getvalue(),
683
                         b"should go to the log\n")
684 685
        self.assertTrue(handler.caught_record)

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 715 716 717 718 719 720
    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()

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    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")

739

740 741
if __name__ == "__main__":
    unittest.main()