xref: /qemu/tests/qemu-iotests/iotests.py (revision 1b3e6f88dc151578acb6158e22570cf3ee7cbb69)
1# Common utilities and Python wrappers for qemu-iotests
2#
3# Copyright (C) 2012 IBM Corp.
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17#
18
19import os
20import re
21import subprocess
22import string
23import unittest
24import sys; sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'QMP'))
25import qmp
26
27__all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
28           'VM', 'QMPTestCase', 'notrun', 'main']
29
30# This will not work if arguments or path contain spaces but is necessary if we
31# want to support the override options that ./check supports.
32qemu_img_args = os.environ.get('QEMU_IMG', 'qemu-img').strip().split(' ')
33qemu_io_args = os.environ.get('QEMU_IO', 'qemu-io').strip().split(' ')
34qemu_args = os.environ.get('QEMU', 'qemu').strip().split(' ')
35
36imgfmt = os.environ.get('IMGFMT', 'raw')
37imgproto = os.environ.get('IMGPROTO', 'file')
38test_dir = os.environ.get('TEST_DIR', '/var/tmp')
39
40def qemu_img(*args):
41    '''Run qemu-img and return the exit code'''
42    devnull = open('/dev/null', 'r+')
43    return subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
44
45def qemu_io(*args):
46    '''Run qemu-io and return the stdout data'''
47    args = qemu_io_args + list(args)
48    return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
49
50class VM(object):
51    '''A QEMU VM'''
52
53    def __init__(self):
54        self._monitor_path = os.path.join(test_dir, 'qemu-mon.%d' % os.getpid())
55        self._qemu_log_path = os.path.join(test_dir, 'qemu-log.%d' % os.getpid())
56        self._args = qemu_args + ['-chardev',
57                     'socket,id=mon,path=' + self._monitor_path,
58                     '-mon', 'chardev=mon,mode=control',
59                     '-qtest', 'stdio', '-machine', 'accel=qtest',
60                     '-display', 'none', '-vga', 'none']
61        self._num_drives = 0
62
63    def add_drive(self, path, opts=''):
64        '''Add a virtio-blk drive to the VM'''
65        options = ['if=virtio',
66                   'format=%s' % imgfmt,
67                   'cache=none',
68                   'file=%s' % path,
69                   'id=drive%d' % self._num_drives]
70        if opts:
71            options.append(opts)
72
73        self._args.append('-drive')
74        self._args.append(','.join(options))
75        self._num_drives += 1
76        return self
77
78    def launch(self):
79        '''Launch the VM and establish a QMP connection'''
80        devnull = open('/dev/null', 'rb')
81        qemulog = open(self._qemu_log_path, 'wb')
82        try:
83            self._qmp = qmp.QEMUMonitorProtocol(self._monitor_path, server=True)
84            self._popen = subprocess.Popen(self._args, stdin=devnull, stdout=qemulog,
85                                           stderr=subprocess.STDOUT)
86            self._qmp.accept()
87        except:
88            os.remove(self._monitor_path)
89            raise
90
91    def shutdown(self):
92        '''Terminate the VM and clean up'''
93        if not self._popen is None:
94            self._qmp.cmd('quit')
95            self._popen.wait()
96            os.remove(self._monitor_path)
97            os.remove(self._qemu_log_path)
98            self._popen = None
99
100    underscore_to_dash = string.maketrans('_', '-')
101    def qmp(self, cmd, **args):
102        '''Invoke a QMP command and return the result dict'''
103        qmp_args = dict()
104        for k in args.keys():
105            qmp_args[k.translate(self.underscore_to_dash)] = args[k]
106
107        return self._qmp.cmd(cmd, args=qmp_args)
108
109    def get_qmp_event(self, wait=False):
110        '''Poll for one queued QMP events and return it'''
111        return self._qmp.pull_event(wait=wait)
112
113    def get_qmp_events(self, wait=False):
114        '''Poll for queued QMP events and return a list of dicts'''
115        events = self._qmp.get_events(wait=wait)
116        self._qmp.clear_events()
117        return events
118
119index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
120
121class QMPTestCase(unittest.TestCase):
122    '''Abstract base class for QMP test cases'''
123
124    def dictpath(self, d, path):
125        '''Traverse a path in a nested dict'''
126        for component in path.split('/'):
127            m = index_re.match(component)
128            if m:
129                component, idx = m.groups()
130                idx = int(idx)
131
132            if not isinstance(d, dict) or component not in d:
133                self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
134            d = d[component]
135
136            if m:
137                if not isinstance(d, list):
138                    self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
139                try:
140                    d = d[idx]
141                except IndexError:
142                    self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
143        return d
144
145    def assert_qmp_absent(self, d, path):
146        try:
147            result = self.dictpath(d, path)
148        except AssertionError:
149            return
150        self.fail('path "%s" has value "%s"' % (path, str(result)))
151
152    def assert_qmp(self, d, path, value):
153        '''Assert that the value for a specific path in a QMP dict matches'''
154        result = self.dictpath(d, path)
155        self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
156
157def notrun(reason):
158    '''Skip this test suite'''
159    # Each test in qemu-iotests has a number ("seq")
160    seq = os.path.basename(sys.argv[0])
161
162    open('%s.notrun' % seq, 'wb').write(reason + '\n')
163    print '%s not run: %s' % (seq, reason)
164    sys.exit(0)
165
166def main(supported_fmts=[]):
167    '''Run tests'''
168
169    if supported_fmts and (imgfmt not in supported_fmts):
170        notrun('not suitable for this image format: %s' % imgfmt)
171
172    # We need to filter out the time taken from the output so that qemu-iotest
173    # can reliably diff the results against master output.
174    import StringIO
175    output = StringIO.StringIO()
176
177    class MyTestRunner(unittest.TextTestRunner):
178        def __init__(self, stream=output, descriptions=True, verbosity=1):
179            unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
180
181    # unittest.main() will use sys.exit() so expect a SystemExit exception
182    try:
183        unittest.main(testRunner=MyTestRunner)
184    finally:
185        sys.stderr.write(re.sub(r'Ran (\d+) test[s] in [\d.]+s', r'Ran \1 tests', output.getvalue()))
186