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

try:
    from unittest import mock
except ImportError:
    import mock

12

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

18 19 20
from six import string_types


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


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

31

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

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


39 40 41
class TestGDBProcess(unittest.TestCase):

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

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

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

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

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

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

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

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

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

96 97 98 99 100 101 102 103 104

def mock_fail_find_cmd(cmd, default=None):
    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):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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)

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    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"])

L
Lukáš Doktor 已提交
281

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
class CmdResultTests(unittest.TestCase):

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

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

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

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


309 310 311 312 313 314 315
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()
316
        for content in (b"foo", b"bar", b"baz", b"foo\nbar\nbaz\n\n"):
317
            os.write(write_fd, content)
318
        os.write(write_fd, b"finish")
319
        os.close(write_fd)
320
        fd_drainer.flush()
321
        self.assertEqual(fd_drainer.data.getvalue(),
322
                         b"foobarbazfoo\nbar\nbaz\n\nfinish")
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

    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()
346
        os.write(write_fd, b"should go to the log\n")
347
        os.close(write_fd)
348
        fd_drainer.flush()
349
        self.assertEqual(fd_drainer.data.getvalue(),
350
                         b"should go to the log\n")
351 352
        self.assertTrue(handler.caught_record)

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 382 383 384 385 386 387
    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()

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    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")

406

407 408
if __name__ == "__main__":
    unittest.main()