test_utils_process.py 27.7 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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    @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)

118

119 120 121
class TestGDBProcess(unittest.TestCase):

    def setUp(self):
122
        self.current_runtime_expr = gdb.GDB_RUN_BINARY_NAMES_EXPR[:]
123 124

    def cleanUp(self):
125
        gdb.GDB_RUN_BINARY_NAMES_EXPR = self.current_runtime_expr
126 127

    def test_should_run_inside_gdb(self):
128
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['foo']
129 130 131 132
        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'))

133
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('foo:main')
134 135 136
        self.assertTrue(process.should_run_inside_gdb('foo'))
        self.assertFalse(process.should_run_inside_gdb('bar'))

137
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('bar:main.c:5')
138 139 140 141 142
        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'))

143 144 145
    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 ~!@#$%^*()-=[]{}|_+":;'`,>?. """
146 147 148
        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 ' "))
149

150
    def test_get_sub_process_klass(self):
151
        gdb.GDB_RUN_BINARY_NAMES_EXPR = []
152
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
153 154
                      process.SubProcess)

155
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('/bin/false')
156 157 158 159
        self.assertIs(process.get_sub_process_klass('/bin/false'),
                      process.GDBSubProcess)
        self.assertIs(process.get_sub_process_klass('false'),
                      process.GDBSubProcess)
160
        self.assertIs(process.get_sub_process_klass(FICTIONAL_CMD),
161 162 163
                      process.SubProcess)

    def test_split_gdb_expr(self):
164
        binary, break_point = process.split_gdb_expr('foo:debug_print')
165
        self.assertEqual(binary, 'foo')
166 167
        self.assertEqual(break_point, 'debug_print')
        binary, break_point = process.split_gdb_expr('bar')
168
        self.assertEqual(binary, 'bar')
169 170
        self.assertEqual(break_point, 'main')
        binary, break_point = process.split_gdb_expr('baz:main.c:57')
171
        self.assertEqual(binary, 'baz')
172
        self.assertEqual(break_point, 'main.c:57')
173 174 175
        self.assertIsInstance(process.split_gdb_expr('foo'), tuple)
        self.assertIsInstance(process.split_gdb_expr('foo:debug_print'), tuple)

176

C
Caio Carrara 已提交
177
def mock_fail_find_cmd(cmd, default=None):  # pylint: disable=W0613
178 179 180 181 182 183 184
    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):

185
    @mock.patch.object(os, 'getuid',
186
                       mock.Mock(return_value=1000))
187 188 189 190 191
    def test_subprocess_nosudo(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

192
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
193 194 195 196 197
    def test_subprocess_nosudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

198
    @mock.patch.object(path, 'find_command',
199
                       mock.Mock(return_value='/bin/sudo'))
200
    @mock.patch.object(os, 'getuid',
201
                       mock.Mock(return_value=1000))
202
    def test_subprocess_sudo(self):
203
        expected_command = '/bin/sudo -n ls -l'
204
        p = process.SubProcess(cmd='ls -l', sudo=True)
205
        path.find_command.assert_called_once_with('sudo')
206 207
        self.assertEqual(p.cmd, expected_command)

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

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

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

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

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

243
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
244 245 246 247 248
    def test_run_nosudo(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', ignore_status=True)
        self.assertEqual(p.command, expected_command)

249
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
250 251 252 253 254
    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)

255 256
    @unittest.skipUnless(os.path.exists('/bin/sudo'),
                         "/bin/sudo not available")
257
    @mock.patch.object(path, 'find_command',
258
                       mock.Mock(return_value='/bin/sudo'))
259
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
260
    def test_run_sudo(self):
261
        expected_command = '/bin/sudo -n ls -l'
262
        p = process.run(cmd='ls -l', sudo=True, ignore_status=True)
263
        path.find_command.assert_called_once_with('sudo')
264 265
        self.assertEqual(p.command, expected_command)

266
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
267
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
268 269 270 271 272
    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)

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

279
    @mock.patch.object(path, 'find_command',
280
                       mock.Mock(return_value='/bin/sudo'))
281
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
282
    def test_run_sudo_shell(self):
283
        expected_command = '/bin/sudo -n -s ls -l'
284
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
285
        path.find_command.assert_called_once_with('sudo')
286 287
        self.assertEqual(p.command, expected_command)

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

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

301 302 303 304 305 306
    @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"
307 308 309 310 311 312 313
        # 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)
314 315
        cmd = u"%s -n %s" % (ECHO_CMD, text)
        result = process.run(cmd, encoding='utf-8')
316 317
        self.assertEqual(result.stdout, encoded_text)
        self.assertEqual(result.stdout_text, text)
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

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)

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    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"])

361 362 363 364 365 366 367 368
    @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)

369 370 371 372 373 374 375 376
    @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)

377 378 379 380 381 382 383 384 385 386 387 388 389 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 416 417 418 419 420 421 422 423 424 425 426 427 428
    @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)

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    @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)

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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    @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 = []
        process.kill_process_tree(1)
        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 = []
        p_time.side_effect = [500, 502, 504, 506, 508, 510, 512, 514, 516, 518]
        sleep.return_value = None
        pid_exists.return_value = True
        self.assertRaises(RuntimeError, process.kill_process_tree, 1,
                          timeout=3)
        self.assertEqual(p_time.call_count, 5)

    @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]
        process.kill_process_tree(1, timeout=3)
        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]

        process.kill_process_tree(1, timeout=-7.354)

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

L
Lukáš Doktor 已提交
509

510 511
class CmdResultTests(unittest.TestCase):

512 513 514 515 516 517 518 519 520 521 522 523 524 525
    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))

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    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 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
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))


568 569 570 571 572 573 574
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()
575
        for content in (b"foo", b"bar", b"baz", b"foo\nbar\nbaz\n\n"):
576
            os.write(write_fd, content)
577
        os.write(write_fd, b"finish")
578
        os.close(write_fd)
579
        fd_drainer.flush()
580
        self.assertEqual(fd_drainer.data.getvalue(),
581
                         b"foobarbazfoo\nbar\nbaz\n\nfinish")
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

    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()
605
        os.write(write_fd, b"should go to the log\n")
606
        os.close(write_fd)
607
        fd_drainer.flush()
608
        self.assertEqual(fd_drainer.data.getvalue(),
609
                         b"should go to the log\n")
610 611
        self.assertTrue(handler.caught_record)

612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    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()

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    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")

665

666 667
if __name__ == "__main__":
    unittest.main()