test_utils_process.py 12.5 KB
Newer Older
1
import logging
2
import os
3
import unittest
4 5 6 7 8 9

try:
    from unittest import mock
except ImportError:
    import mock

10

11
from avocado.utils import gdb
12
from avocado.utils import process
13
from avocado.utils import path
14

15 16 17
from six import string_types


18 19
TRUE_CMD = path.find_command('true')

20

21 22 23 24 25 26 27
class TestSubProcess(unittest.TestCase):

    def test_allow_output_check_parameter(self):
        self.assertRaises(ValueError, process.SubProcess,
                          TRUE_CMD, False, "invalid")


28 29 30
class TestGDBProcess(unittest.TestCase):

    def setUp(self):
31
        self.current_runtime_expr = gdb.GDB_RUN_BINARY_NAMES_EXPR[:]
32 33

    def cleanUp(self):
34
        gdb.GDB_RUN_BINARY_NAMES_EXPR = self.current_runtime_expr
35 36

    def test_should_run_inside_gdb(self):
37
        gdb.GDB_RUN_BINARY_NAMES_EXPR = ['foo']
38 39 40 41
        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'))

42
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('foo:main')
43 44 45
        self.assertTrue(process.should_run_inside_gdb('foo'))
        self.assertFalse(process.should_run_inside_gdb('bar'))

46
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('bar:main.c:5')
47 48 49 50 51
        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'))

52 53 54
    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 ~!@#$%^*()-=[]{}|_+":;'`,>?. """
55 56 57
        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 ' "))
58

59
    def test_get_sub_process_klass(self):
60
        gdb.GDB_RUN_BINARY_NAMES_EXPR = []
61
        self.assertIs(process.get_sub_process_klass(TRUE_CMD),
62 63
                      process.SubProcess)

64
        gdb.GDB_RUN_BINARY_NAMES_EXPR.append('/bin/false')
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        self.assertIs(process.get_sub_process_klass('/bin/false'),
                      process.GDBSubProcess)
        self.assertIs(process.get_sub_process_klass('false'),
                      process.GDBSubProcess)
        self.assertIs(process.get_sub_process_klass('true'),
                      process.SubProcess)

    def test_split_gdb_expr(self):
        binary, breakpoint = process.split_gdb_expr('foo:debug_print')
        self.assertEqual(binary, 'foo')
        self.assertEqual(breakpoint, 'debug_print')
        binary, breakpoint = process.split_gdb_expr('bar')
        self.assertEqual(binary, 'bar')
        self.assertEqual(breakpoint, 'main')
        binary, breakpoint = process.split_gdb_expr('baz:main.c:57')
        self.assertEqual(binary, 'baz')
        self.assertEqual(breakpoint, 'main.c:57')
        self.assertIsInstance(process.split_gdb_expr('foo'), tuple)
        self.assertIsInstance(process.split_gdb_expr('foo:debug_print'), tuple)

85 86 87 88 89 90 91 92 93

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

94
    @mock.patch.object(path, 'find_command',
95
                       mock.Mock(return_value=TRUE_CMD))
96
    @mock.patch.object(os, 'getuid',
97
                       mock.Mock(return_value=1000))
98 99 100 101 102
    def test_subprocess_nosudo(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

103
    @mock.patch.object(path, 'find_command',
104 105
                       mock.Mock(return_value=TRUE_CMD))
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=0))
106 107 108 109 110
    def test_subprocess_nosudo_uid_0(self):
        expected_command = 'ls -l'
        p = process.SubProcess(cmd='ls -l')
        self.assertEqual(p.cmd, expected_command)

111
    @mock.patch.object(path, 'find_command',
112
                       mock.Mock(return_value=TRUE_CMD))
113
    @mock.patch.object(os, 'getuid',
114
                       mock.Mock(return_value=1000))
115
    def test_subprocess_sudo(self):
116
        expected_command = '%s -n ls -l' % TRUE_CMD
117 118 119
        p = process.SubProcess(cmd='ls -l', sudo=True)
        self.assertEqual(p.cmd, expected_command)

120
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
121
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
122 123 124 125 126
    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)

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

135
    @mock.patch.object(path, 'find_command',
136 137
                       mock.Mock(return_value=TRUE_CMD))
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
138
    def test_subprocess_sudo_shell(self):
139
        expected_command = '%s -n -s ls -l' % TRUE_CMD
140 141 142
        p = process.SubProcess(cmd='ls -l', sudo=True, shell=True)
        self.assertEqual(p.cmd, expected_command)

143
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
144
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
145 146 147 148 149
    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)

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

158
    @mock.patch.object(path, 'find_command',
159 160
                       mock.Mock(return_value=TRUE_CMD))
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
161 162 163 164 165
    def test_run_nosudo(self):
        expected_command = 'ls -l'
        p = process.run(cmd='ls -l', ignore_status=True)
        self.assertEqual(p.command, expected_command)

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

174
    @mock.patch.object(path, 'find_command',
175 176
                       mock.Mock(return_value=TRUE_CMD))
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
177
    def test_run_sudo(self):
178
        expected_command = '%s -n ls -l' % TRUE_CMD
179 180 181
        p = process.run(cmd='ls -l', sudo=True, ignore_status=True)
        self.assertEqual(p.command, expected_command)

182
    @mock.patch.object(path, 'find_command', mock_fail_find_cmd)
183
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
184 185 186 187 188
    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)

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

197
    @mock.patch.object(path, 'find_command',
198 199
                       mock.Mock(return_value=TRUE_CMD))
    @mock.patch.object(os, 'getuid', mock.Mock(return_value=1000))
200
    def test_run_sudo_shell(self):
201
        expected_command = '%s -n -s ls -l' % TRUE_CMD
202 203 204
        p = process.run(cmd='ls -l', sudo=True, shell=True, ignore_status=True)
        self.assertEqual(p.command, expected_command)

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

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

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

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)

L
Lukáš Doktor 已提交
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
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)


264 265 266 267 268 269 270
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()
271
        for content in (b"foo", b"bar", b"baz", b"foo\nbar\nbaz\n\n"):
272
            os.write(write_fd, content)
273
        os.write(write_fd, b"finish")
274
        os.close(write_fd)
275
        fd_drainer.flush()
276
        self.assertEqual(fd_drainer.data.getvalue(),
277
                         b"foobarbazfoo\nbar\nbaz\n\nfinish")
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

    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()
301
        os.write(write_fd, b"should go to the log\n")
302
        os.close(write_fd)
303
        fd_drainer.flush()
304
        self.assertEqual(fd_drainer.data.getvalue(),
305
                         b"should go to the log\n")
306 307 308
        self.assertTrue(handler.caught_record)


309 310
if __name__ == "__main__":
    unittest.main()