xref: /openbmc/qemu/tests/qapi-schema/test-qapi.py (revision 23394b4c393c832aa3891533587ff97e04c70883)
1#!/usr/bin/env python
2#
3# QAPI parser test harness
4#
5# Copyright (c) 2013 Red Hat Inc.
6#
7# Authors:
8#  Markus Armbruster <armbru@redhat.com>
9#
10# This work is licensed under the terms of the GNU GPL, version 2 or later.
11# See the COPYING file in the top-level directory.
12#
13
14from __future__ import print_function
15
16import argparse
17import difflib
18import os
19import sys
20
21from qapi.error import QAPIError
22from qapi.schema import QAPISchema, QAPISchemaVisitor
23
24if sys.version_info[0] < 3:
25    from cStringIO import StringIO
26else:
27    from io import StringIO
28
29
30class QAPISchemaTestVisitor(QAPISchemaVisitor):
31
32    def visit_module(self, name):
33        print('module %s' % name)
34
35    def visit_include(self, name, info):
36        print('include %s' % name)
37
38    def visit_enum_type(self, name, info, ifcond, members, prefix):
39        print('enum %s' % name)
40        if prefix:
41            print('    prefix %s' % prefix)
42        for m in members:
43            print('    member %s' % m.name)
44            self._print_if(m.ifcond, indent=8)
45        self._print_if(ifcond)
46
47    def visit_array_type(self, name, info, ifcond, element_type):
48        if not info:
49            return              # suppress built-in arrays
50        print('array %s %s' % (name, element_type.name))
51        self._print_if(ifcond)
52
53    def visit_object_type(self, name, info, ifcond, base, members, variants,
54                          features):
55        print('object %s' % name)
56        if base:
57            print('    base %s' % base.name)
58        for m in members:
59            print('    member %s: %s optional=%s'
60                  % (m.name, m.type.name, m.optional))
61            self._print_if(m.ifcond, 8)
62        self._print_variants(variants)
63        self._print_if(ifcond)
64        if features:
65            for f in features:
66                print('    feature %s' % f.name)
67                self._print_if(f.ifcond, 8)
68
69    def visit_alternate_type(self, name, info, ifcond, variants):
70        print('alternate %s' % name)
71        self._print_variants(variants)
72        self._print_if(ifcond)
73
74    def visit_command(self, name, info, ifcond, arg_type, ret_type, gen,
75                      success_response, boxed, allow_oob, allow_preconfig,
76                      features):
77        print('command %s %s -> %s'
78              % (name, arg_type and arg_type.name,
79                 ret_type and ret_type.name))
80        print('    gen=%s success_response=%s boxed=%s oob=%s preconfig=%s'
81              % (gen, success_response, boxed, allow_oob, allow_preconfig))
82        self._print_if(ifcond)
83
84    def visit_event(self, name, info, ifcond, arg_type, boxed):
85        print('event %s %s' % (name, arg_type and arg_type.name))
86        print('    boxed=%s' % boxed)
87        self._print_if(ifcond)
88
89    @staticmethod
90    def _print_variants(variants):
91        if variants:
92            print('    tag %s' % variants.tag_member.name)
93            for v in variants.variants:
94                print('    case %s: %s' % (v.name, v.type.name))
95                QAPISchemaTestVisitor._print_if(v.ifcond, indent=8)
96
97    @staticmethod
98    def _print_if(ifcond, indent=4):
99        if ifcond:
100            print('%sif %s' % (' ' * indent, ifcond))
101
102
103def test_frontend(fname):
104    schema = QAPISchema(fname)
105    schema.visit(QAPISchemaTestVisitor())
106
107    for doc in schema.docs:
108        if doc.symbol:
109            print('doc symbol=%s' % doc.symbol)
110        else:
111            print('doc freeform')
112        print('    body=\n%s' % doc.body.text)
113        for arg, section in doc.args.items():
114            print('    arg=%s\n%s' % (arg, section.text))
115        for section in doc.sections:
116            print('    section=%s\n%s' % (section.name, section.text))
117
118
119def test_and_diff(test_name, dir_name, update):
120    sys.stdout = StringIO()
121    try:
122        test_frontend(os.path.join(dir_name, test_name + '.json'))
123    except QAPIError as err:
124        if err.info.fname is None:
125            print("%s" % err, file=sys.stderr)
126            return 2
127        errstr = str(err) + '\n'
128        if dir_name:
129            errstr = errstr.replace(dir_name + '/', '')
130        actual_err = errstr.splitlines(True)
131    else:
132        actual_err = []
133    finally:
134        actual_out = sys.stdout.getvalue().splitlines(True)
135        sys.stdout.close()
136        sys.stdout = sys.__stdout__
137
138    mode = 'r+' if update else 'r'
139    try:
140        outfp = open(os.path.join(dir_name, test_name + '.out'), mode)
141        errfp = open(os.path.join(dir_name, test_name + '.err'), mode)
142        expected_out = outfp.readlines()
143        expected_err = errfp.readlines()
144    except IOError as err:
145        print("%s: can't open '%s': %s"
146              % (sys.argv[0], err.filename, err.strerror),
147              file=sys.stderr)
148        return 2
149
150    if actual_out == expected_out and actual_err == expected_err:
151        return 0
152
153    print("%s %s" % (test_name, 'UPDATE' if update else 'FAIL'),
154          file=sys.stderr)
155    out_diff = difflib.unified_diff(expected_out, actual_out, outfp.name)
156    err_diff = difflib.unified_diff(expected_err, actual_err, errfp.name)
157    sys.stdout.writelines(out_diff)
158    sys.stdout.writelines(err_diff)
159
160    if not update:
161        return 1
162
163    try:
164        outfp.truncate(0)
165        outfp.seek(0)
166        outfp.writelines(actual_out)
167        errfp.truncate(0)
168        errfp.seek(0)
169        errfp.writelines(actual_err)
170    except IOError as err:
171        print("%s: can't write '%s': %s"
172              % (sys.argv[0], err.filename, err.strerror),
173              file=sys.stderr)
174        return 2
175
176    return 0
177
178
179def main(argv):
180    parser = argparse.ArgumentParser(
181        description='QAPI schema tester')
182    parser.add_argument('-d', '--dir', action='store', default='',
183                        help="directory containing tests")
184    parser.add_argument('-u', '--update', action='store_true',
185                        help="update expected test results")
186    parser.add_argument('tests', nargs='*', metavar='TEST', action='store')
187    args = parser.parse_args()
188
189    status = 0
190    for t in args.tests:
191        (dir_name, base_name) = os.path.split(t)
192        dir_name = dir_name or args.dir
193        test_name = os.path.splitext(base_name)[0]
194        status |= test_and_diff(test_name, dir_name, args.update)
195
196    exit(status)
197
198
199if __name__ == '__main__':
200    main(sys.argv)
201    exit(0)
202